sasso 0.2.0

A pure-Rust SCSS to CSS compiler (a dart-sass alternative). Zero dependencies, wasm-friendly, embeddable as a library and usable as a CLI.
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
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
//! The evaluator: walks the AST, resolving variables, nesting (`&` and
//! the parent×child selector product), interpolation and arithmetic, and
//! flattens the result into a list of output rules.
//!
//! Like dart-sass (and unlike grass), a rule's own declarations are
//! gathered into a single block emitted *before* its nested rules bubble
//! out after it.

use std::cell::RefCell;
use std::rc::Rc;

// The compiler's internal maps are all keyed on short identifiers taken from
// the stylesheet being compiled, so they use the fast FxHash hasher rather than
// std's DoS-resistant-but-slow SipHash. Aliased to `HashMap` so the many type
// declarations below read normally; only the construction sites differ
// (`HashMap::default()` rather than `::new()`, since the hasher is non-default).
use crate::fxhash::FxHashMap as HashMap;

use crate::ast::{
    BinOp, CallArg, Callable, Conjunction, CssCustomItem, CssCustomValue, CustomDecl, Declaration, Expr,
    IfClause, IfCond, ImportArg, ImportModifier, MediaFeature, MediaInParens, MediaQuery, MediaQueryList,
    ParamList, PropertySet, Rule, SrcLines, Stmt, Stylesheet, SupportsCondition, SupportsValue, TplPiece,
    UnOp, VarDecl,
};
use crate::error::Error;
use crate::scanner::Pos;
use crate::value::{CalcNode, CalcOp, List, ListSep, Map, Number, SassFunction, SassMixin, SassStr, Value};
use crate::{Importer, OutputStyle, Syntax};

/// One cached `@import` resolution: (resolved canonical key, syntax, parsed
/// sheet), shared across repeated imports within a single compile.
type CachedImport = std::rc::Rc<(String, Syntax, crate::ast::Stylesheet)>;

/// Parse imported/`@use`d source with the front-end matching its file syntax.
fn parse_with_syntax(src: &str, syntax: Syntax) -> Result<crate::ast::Stylesheet, Error> {
    match syntax {
        Syntax::Scss => crate::parser::parse(src),
        Syntax::Css => crate::parser::parse_plain_css(src),
        Syntax::Sass => crate::sass_parser::parse(src),
    }
}

/// A call's evaluated arguments, split into positional values and named
/// `(name, value)` keyword pairs (after splat expansion), plus the rest-
/// argument list separator (a splatted list's separator survives into the
/// callee's arglist; comma otherwise).
type EvaledArgs = (Vec<Value>, Vec<(String, Value)>, ListSep);

/// One variable scope. Lexical scoping shares frames between the active
/// chain and callable closures (dart's Environment maps), so a scope is a
/// shared, interior-mutable map.
pub(crate) type Scope = std::rc::Rc<std::cell::RefCell<HashMap<String, Value>>>;

fn new_scope() -> Scope {
    std::rc::Rc::new(std::cell::RefCell::new(HashMap::default()))
}

/// One function/mixin scope frame, parallel to the variable chain (dart's
/// `Environment._functions`/`_mixins` are lists of maps pushed and popped in
/// lockstep with `_variables`).
pub(crate) type FnScope = std::rc::Rc<std::cell::RefCell<HashMap<String, Rc<UserCallable>>>>;

fn new_fn_scope() -> FnScope {
    std::rc::Rc::new(std::cell::RefCell::new(HashMap::default()))
}

/// A user `@function`/`@mixin` with its LEXICAL environment: the variable and
/// function/mixin scope chains captured at the definition site (shared
/// frames, dart's `Environment.closure()`). The body runs against these
/// chains, not the caller's stack.
pub(crate) struct UserCallable {
    pub def: Rc<Callable>,
    pub env: Vec<Scope>,
    pub env_semi: Vec<bool>,
    pub env_fns: Vec<FnScope>,
    pub env_mixins: Vec<FnScope>,
}

/// A flattened output node.
#[derive(Clone)]
pub(crate) enum OutNode {
    Rule {
        selectors: Vec<String>,
        /// Per-complex "line break before" flags from the source selector list
        /// (`a,\nb` keeps the newline). Empty means none (all comma-joined with
        /// a space); otherwise parallel to `selectors`.
        linebreaks: Vec<bool>,
        items: Vec<OutItem>,
        /// Source lines (`start` = the `{` line, `end` = the `}` line) for the
        /// serializer's trailing-comment rule; default = disabled.
        lines: SrcLines,
        /// The number of `@extend`s already registered when this rule's selector
        /// was established (dart-sass `addSelector` timing). When the rule was
        /// registered AFTER every applicable `@extend` (`extend_base >=`
        /// visible-extension count), dart extends the fresh selector by the whole
        /// store at ONCE — `_extendComplex`'s `paths` unification order (last
        /// choice slowest) — rather than re-extending it incrementally
        /// (registration-order fold). `usize::MAX` marks a non-evaluated rule
        /// (plain-CSS import, `@at-root` graft, reparent shell) for which the
        /// sequential default always applies.
        extend_base: usize,
    },
    Comment(String, SrcLines),
    /// A verbatim line (e.g. a passed-through CSS `@import`).
    Raw(String),
    /// A blank-line separator between top-level groups (expanded only).
    Blank,
    /// An at-rule: `@name prelude { body }` (when `has_block`) or
    /// `@name prelude;` (when not). The body holds the bubbled-out child
    /// nodes; bare declarations appear as [`OutNode::AtDecl`].
    AtRule {
        name: String,
        prelude: String,
        body: Vec<OutNode>,
        has_block: bool,
        /// Source lines (`start` = the `{` line or the statement's own line
        /// for the `;` form, `end` = the `}` line or the same) for the
        /// serializer's trailing-comment rule; default = disabled.
        lines: SrcLines,
    },
    /// A module's spliced CSS, tagged with its canonical key so the extend
    /// pass can scope extensions (dart-sass: an `@extend` affects the module's
    /// own CSS and its transitive upstreams, never siblings or downstream).
    /// Emits transparently as its contents.
    ModuleScope {
        key: String,
        nodes: Vec<OutNode>,
    },
    /// A bare declaration emitted directly inside an at-rule body (e.g.
    /// `@font-face { font-family: x; }`).
    AtDecl {
        prop: String,
        value: String,
        important: bool,
        /// A custom property (`--x`) whose value is emitted verbatim after the
        /// colon (no inserted space); its leading whitespace is part of `value`.
        custom: bool,
        /// Source lines (only `file` and `end` are meaningful) for the
        /// serializer's trailing-comment rule; default = disabled.
        lines: SrcLines,
    },
}

/// A media query resolved to its final string components, ready to serialize
/// and to merge with nested queries (dart-sass `CssMediaQuery`).
#[derive(Clone, PartialEq, Eq)]
struct ResolvedQuery {
    /// `not`/`only`, already lowercased; `None` for a condition-only query.
    modifier: Option<String>,
    /// The media type (e.g. `screen`); `None` for a condition-only query.
    mtype: Option<String>,
    /// Serialized condition strings (e.g. `(a)`, `not (b)`, `((a) or (b))`).
    conditions: Vec<String>,
    /// Whether the conditions are joined by `and` (true) or `or` (false).
    conjunction_and: bool,
}

/// The result of merging two media queries (dart-sass `MediaQueryMergeResult`).
enum MergeResult {
    /// Mutually exclusive — the merged query selects nothing.
    Empty,
    /// The merge can't be represented as a single query; keep them nested.
    Unrepresentable,
    /// A single merged query.
    Query(ResolvedQuery),
}

/// An item inside a rule block.
#[derive(Clone)]
pub(crate) enum OutItem {
    Decl {
        prop: String,
        value: String,
        important: bool,
        /// A custom property (`--x`) whose value is emitted verbatim after the
        /// colon (no inserted space); its leading whitespace is part of `value`.
        custom: bool,
        /// Source lines (only `file` and `end` are meaningful) for the
        /// serializer's trailing-comment rule; default = disabled.
        lines: SrcLines,
    },
    Comment(String, SrcLines),
    /// A childless at-rule (`@e f;`) that appears directly inside a style rule:
    /// dart-sass keeps it in the parent block (interleaved with declarations),
    /// unlike a block at-rule which bubbles out to the document root.
    ChildlessAtRule {
        name: String,
        prelude: String,
        /// Source lines (only `file` and `end` are meaningful) for the
        /// serializer's trailing-comment rule; default = disabled.
        lines: SrcLines,
    },
    /// A style rule nested directly inside another, kept verbatim instead of
    /// flattened. Only produced in plain-CSS mode (a loaded `.css` file).
    NestedRule {
        selectors: Vec<String>,
        items: Vec<OutItem>,
    },
    /// A block at-rule (`@media`, `@supports`, unknown) nested inside an
    /// already-nested plain-CSS rule, kept in place instead of bubbled —
    /// dart-sass `_hasCssNesting`: once the user opts into native CSS nesting,
    /// at-rules stay where they are. Only produced in plain-CSS mode.
    NestedAtRule {
        name: String,
        prelude: String,
        items: Vec<OutItem>,
    },
}

/// Which kind of module member an existence predicate (`function-exists`,
/// `mixin-exists`, `global-variable-exists` with a `$module`) queries.
#[derive(Clone, Copy)]
enum MemberKind {
    Function,
    Mixin,
    Variable,
}

/// Where evaluated statements deposit their output. At the top level each
/// statement forms its own blank-separated group; inside a style rule,
/// declarations join the rule's block and nested rules bubble out after it.
/// This is the seam that lets one block executor serve the top level, rule
/// bodies, and every nested-block construct (conditionals, loops, mixins).
enum Sink<'a> {
    Top(&'a mut Vec<OutNode>),
    Rule {
        /// The enclosing rule's resolved selector list, used to build a block
        /// node when the accumulated `items` must be flushed (i.e. when a nested
        /// rule or at-rule interrupts the parent's own declarations).
        selectors: &'a [String],
        /// Per-complex source line-break flags (parallel to `selectors`).
        linebreaks: &'a [bool],
        /// The source rule's brace/end lines, stamped onto every flushed block
        /// fragment (dart keeps the original rule's span on each copy).
        lines: SrcLines,
        items: &'a mut Vec<OutItem>,
        nested: &'a mut Vec<OutNode>,
        /// The at-rule nesting depth of this rule's body (`at_rule_ctx.len()`
        /// at construction): an `@at-root` hoist marker whose batch escapes
        /// this body (target < depth) is transparent to block anchoring, while
        /// one grafting INTO this body (target == depth) is a solid sibling.
        at_depth: usize,
        /// Index in `nested` of the most recently flushed block fragment, so a
        /// later fragment can JOIN it when only escaping hoist markers landed
        /// in between (dart adds both declaration runs to the same style-rule
        /// copy because the escaped batches aren't siblings inside this node).
        flushed: &'a mut Option<usize>,
        /// The `@extend` registration count when this rule's selector was
        /// established (dart `addSelector` timing), carried onto each flushed
        /// [`OutNode::Rule`]. See [`OutNode::Rule::extend_base`].
        extend_base: usize,
    },
    /// The body of a top-level at-rule (no enclosing selector): bare
    /// declarations land here directly as [`OutNode::AtDecl`], interleaved
    /// in source order with bubbled child rules and nested at-rules.
    AtRoot(&'a mut Vec<OutNode>),
}

impl Sink<'_> {
    fn is_top(&self) -> bool {
        matches!(self, Sink::Top(_))
    }

    fn is_rule(&self) -> bool {
        matches!(self, Sink::Rule { .. })
    }

    /// Deposit a childless at-rule (`@e f;`). Inside a style rule it joins the
    /// parent's block (interleaved with declarations, in source order); at the
    /// top level or inside an at-rule body it is a bubbled-out `OutNode`.
    fn push_childless_at_rule(&mut self, name: String, prelude: String, lines: SrcLines) {
        match self {
            Sink::Rule { items, .. } => items.push(OutItem::ChildlessAtRule { name, prelude, lines }),
            _ => self.push_at_rule(OutNode::AtRule {
                name,
                prelude,
                body: Vec::new(),
                has_block: false,
                lines,
            }),
        }
    }

    fn push_comment(&mut self, text: String, lines: SrcLines) {
        // dart-sass strips a `/*# sourceMappingURL=… */` / `/*# sourceURL=… */`
        // loud comment (it generates its own); the `# ` space is required, so
        // `/*#sourceMappingURL…*/`, `/*! … */`, and other names are kept.
        if text.starts_with("# sourceMappingURL=") || text.starts_with("# sourceURL=") {
            // The comment emits nothing, but the statement it occupied still
            // ends a top-level group (dart's serializer writes a blank line
            // before the following node — and, when the stripped comment leads
            // the document, a leading blank). Leave a group-end sentinel so the
            // next top-level group blank-separates; inside a block (or at-root
            // body) the comment vanishes with no separator, as dart does.
            if let Sink::Top(out) = self {
                out.push(OutNode::Raw(STYLE_GROUP_END.to_string()));
            }
            return;
        }
        match self {
            Sink::Top(out) => {
                let out = &mut **out;
                push_group(out, vec![OutNode::Comment(text, lines)]);
            }
            Sink::Rule { items, .. } => items.push(OutItem::Comment(text, lines)),
            Sink::AtRoot(body) => body.push(OutNode::Comment(text, lines)),
        }
    }

    fn push_item(&mut self, item: OutItem) {
        match self {
            Sink::Rule { items, .. } => items.push(item),
            Sink::AtRoot(body) => match item {
                OutItem::Decl {
                    prop,
                    value,
                    important,
                    custom,
                    lines,
                } => body.push(OutNode::AtDecl {
                    prop,
                    value,
                    important,
                    custom,
                    lines,
                }),
                OutItem::Comment(text, lines) => body.push(OutNode::Comment(text, lines)),
                OutItem::ChildlessAtRule { name, prelude, lines } => body.push(OutNode::AtRule {
                    name,
                    prelude,
                    body: Vec::new(),
                    has_block: false,
                    lines,
                }),
                // A plain-CSS nested rule reaching an at-root sink becomes a
                // top-level rule carrying its items.
                OutItem::NestedRule { selectors, items } => body.push(OutNode::Rule {
                    selectors,
                    linebreaks: Vec::new(),
                    items,
                    lines: SrcLines::default(),
                    extend_base: usize::MAX,
                }),
                // Likewise a plain-CSS nested at-rule becomes a top-level one,
                // its items wrapped as bare at-rule children.
                OutItem::NestedAtRule { name, prelude, items } => body.push(OutNode::AtRule {
                    name,
                    prelude,
                    body: items
                        .into_iter()
                        .map(|it| match it {
                            OutItem::Decl {
                                prop,
                                value,
                                important,
                                custom,
                                lines,
                            } => OutNode::AtDecl {
                                prop,
                                value,
                                important,
                                custom,
                                lines,
                            },
                            OutItem::Comment(text, lines) => OutNode::Comment(text, lines),
                            OutItem::NestedRule { selectors, items } => OutNode::Rule {
                                selectors,
                                linebreaks: Vec::new(),
                                items,
                                lines: SrcLines::default(),
                                extend_base: usize::MAX,
                            },
                            OutItem::ChildlessAtRule { name, prelude, lines } => OutNode::AtRule {
                                name,
                                prelude,
                                body: Vec::new(),
                                has_block: false,
                                lines,
                            },
                            OutItem::NestedAtRule { name, prelude, items } => OutNode::AtRule {
                                name,
                                prelude,
                                body: vec![OutNode::Rule {
                                    selectors: Vec::new(),
                                    linebreaks: Vec::new(),
                                    items,
                                    lines: SrcLines::default(),
                                    extend_base: usize::MAX,
                                }],
                                has_block: true,
                                lines: SrcLines::default(),
                            },
                        })
                        .collect(),
                    has_block: true,
                    lines: SrcLines::default(),
                }),
            },
            Sink::Top(_) => {}
        }
    }

    /// Flush the parent rule's accumulated declarations/loud-comments into a
    /// block node, in source order, before a nested rule or at-rule is emitted.
    /// dart-sass splits the parent block around each bubbled child so that a
    /// declaration (or loud comment) following a nested rule appears AFTER that
    /// rule in the output. No-op for non-`Rule` sinks (which never accumulate a
    /// block) and when there are no pending items.
    fn flush_rule_block(&mut self) {
        if let Sink::Rule {
            selectors,
            linebreaks,
            lines,
            items,
            nested,
            at_depth,
            flushed,
            extend_base,
        } = self
        {
            if !items.is_empty() {
                // A rule whose every complex selector was a dropped bogus
                // combinator has no selectors left, so it emits no block.
                if selectors.is_empty() {
                    items.clear();
                } else {
                    // The rule's block precedes any hoist markers that
                    // accumulated while it was open (the bubbled rules leave
                    // the style rule entirely and follow it in the output);
                    // an `@at-root` graft INTO this body (target == depth) is
                    // a real sibling, so the block stays after it.
                    let insert_at = nested
                        .iter()
                        .position(|n| is_escaping_marker(n, *at_depth))
                        .unwrap_or(nested.len());
                    // Both declaration runs target the same style-rule copy
                    // when only escaped batches landed between them (dart's
                    // entry copy has no following sibling inside this node).
                    if insert_at > 0 && **flushed == Some(insert_at - 1) {
                        if let Some(OutNode::Rule { items: prev, .. }) = nested.get_mut(insert_at - 1) {
                            prev.append(*items);
                            return;
                        }
                        // (a non-Rule at that index can't happen: `flushed`
                        // only ever records a flushed block fragment)
                    }
                    let rule = OutNode::Rule {
                        selectors: selectors.to_vec(),
                        linebreaks: linebreaks.to_vec(),
                        items: std::mem::take(*items),
                        lines: *lines,
                        extend_base: *extend_base,
                    };
                    nested.insert(insert_at, rule);
                    **flushed = Some(insert_at);
                }
            }
        }
    }

    /// Emit a produced style rule's fully interleaved output (its own block
    /// fragments plus the rules that bubbled out of it, in source order).
    fn emit_style_rule(&mut self, output: Vec<OutNode>) {
        match self {
            Sink::Top(out) => {
                let out = &mut **out;
                push_group(out, output);
                // A completed top-level style rule marks its LAST produced
                // node (which may be a bubbled at-rule) as a group end: the
                // next group gets a blank line even after an at-rule
                // (dart-sass isGroupEnd, set only by visitStyleRule).
                if !out.is_empty() {
                    out.push(OutNode::Raw(STYLE_GROUP_END.to_string()));
                }
            }
            Sink::Rule { .. } => {
                // Split the enclosing rule's own block around this nested rule.
                self.flush_rule_block();
                if let Sink::Rule { nested, .. } = self {
                    nested.extend(output);
                }
            }
            Sink::AtRoot(body) => body.extend(output),
        }
    }

    /// Deposit a produced at-rule (or `@at-root` output). At the top level it
    /// forms its own group; inside a style rule it joins the rules that bubble
    /// out to the document root (splitting the parent's own block around it);
    /// inside another at-rule's body it nests.
    fn push_at_rule(&mut self, node: OutNode) {
        match self {
            Sink::Top(out) => {
                let out = &mut **out;
                push_group(out, vec![node]);
            }
            Sink::Rule { .. } => {
                // A hoist marker whose batch ESCAPES this body only matters to
                // an OUTER at-rule's segmenting: the batch leaves this style
                // rule entirely, so its own block is NOT split around it. An
                // `@at-root` graft INTO this body is a real sibling and splits
                // the block like any other bubbled child.
                let depth = match self {
                    Sink::Rule { at_depth, .. } => *at_depth,
                    _ => 0,
                };
                if !is_escaping_marker(&node, depth) {
                    self.flush_rule_block();
                }
                if let Sink::Rule { nested, .. } = self {
                    nested.push(node);
                }
            }
            Sink::AtRoot(body) => body.push(node),
        }
    }
}

/// Options visible to the evaluator (subset of the public `Options`).
pub(crate) struct EvalOptions<'a> {
    pub style: OutputStyle,
    pub importer: Option<&'a dyn Importer>,
    /// The entrypoint's source text, for rendering byte-exact diagnostic
    /// snippets. Empty when the embedder does not supply it (diagnostics then
    /// fall back to the legacy one-liner).
    pub source: &'a str,
    /// The entrypoint's file path/URL as it should appear in diagnostics
    /// (e.g. `input.scss`).
    pub url: &'a str,
    /// The glyph set for snippet/gutter decoration (ASCII under `--no-unicode`).
    pub glyphs: crate::diag::GlyphSet,
}

pub(crate) struct Evaluator<'a> {
    scopes: Vec<Scope>,
    /// Whether each scope in `scopes` is "semi-global" (dart-sass): a control
    /// flow scope (`@for`/`@each`/`@while`/`@if`) that lets a fresh assignment
    /// reach the global scope, but only when every enclosing scope up to the
    /// root is itself semi-global. Rule/mixin/function scopes are not.
    scope_semi_global: Vec<bool>,
    options: EvalOptions<'a>,
    /// Import paths currently being loaded, deepest last. Re-entering one is a
    /// load cycle (dart-sass "This file is already being loaded."); a path that
    /// has finished loading may be imported again (`@import` re-evaluates).
    loading: Vec<String>,
    /// Per-compile `@import` cache (dart-sass ImportCache analogue): keyed by
    /// (url, importing dir), holding (resolved key, syntax, parsed sheet).
    import_cache: HashMap<(String, Option<String>), CachedImport>,
    /// The current file's interned diagnostic id for [`Self::stamp`], or 0
    /// when not yet interned. Every `current_url` assignment resets it.
    current_url_stamp: u32,
    /// User function/mixin scope chains, parallel to `scopes` (dart's
    /// `Environment._functions`/`_mixins`): a definition always lands in the
    /// innermost frame, so a nested `@function`/`@mixin` shadows an outer one
    /// only within its block.
    functions: Vec<FnScope>,
    mixins: Vec<FnScope>,
    /// Stack of `@content` blocks, one per active `@include`.
    content_stack: Vec<Option<ContentBlock>>,
    /// Whether we are *directly* executing a mixin body (dart-sass `_inMixin`).
    /// `true` is pushed while a mixin body runs; running a `@content` block or a
    /// function body pushes `false` (those execute in the caller's context), so
    /// `meta.content-exists()` errors there. Empty at the document root.
    in_mixin: Vec<bool>,
    /// The resolved query list of the enclosing `@media` context (empty at the
    /// document root). Used to merge nested `@media` queries.
    media_queries: Vec<ResolvedQuery>,
    /// The resolved selector list of the enclosing style rule, used to resolve
    /// `&` in value position. `None` at the document root (where `&` is `null`).
    /// Each element is one resolved complex selector (space-joined).
    current_selector: Option<Vec<String>>,
    /// Source line-break flags parallel to `current_selector` (whether each
    /// resolved complex selector started on a fresh source line). A nested
    /// rule's complex inherits its parent's flag OR its own part's flag.
    current_linebreaks: Vec<bool>,
    /// Collected `@extend` directives, applied in a post-eval extension pass.
    extends: Vec<PendingExtend>,
    /// The current nested-property-set name prefix (e.g. `font` then `font-x`).
    /// Empty at the document root and inside ordinary rules; a child declaration
    /// emitted while this is non-empty is namespaced as `<prefix>-<name>`.
    decl_prefix: Option<String>,
    /// Whether we are evaluating the value of a `@supports` declaration. When
    /// set, `calc()` interiors are NOT simplified (dart-sass keeps
    /// `calc(1 + 2)` literal in `@supports (a: calc(1 + 2))`), matching
    /// dart-sass `_inSupportsDeclaration`.
    in_supports_declaration: bool,
    /// True while evaluating a plain-CSS (`.css`) module's statements: no
    /// function — user-defined or built-in — is invoked there (dart-sass
    /// `plainCss`); calls re-serialize verbatim. CSS calculations still
    /// simplify.
    in_plain_css: bool,
    /// True while the pending configuration is the *implicit* one built from
    /// an `@import`'s visible variables (dart `Configuration.implicit`): an
    /// already-loaded module is then reused silently instead of erroring with
    /// "can't be configured using with".
    config_is_implicit: bool,
    /// The canonical key of the module currently being evaluated (empty for
    /// the root stylesheet) — stamped onto each registered `@extend`.
    current_module: String,
    /// Module dependency edges: user key -> the canonical keys it loads
    /// (via `@use`/`@forward`/`meta.load-css`). An extension whose origin can
    /// reach a module along these edges may rewrite that module's CSS.
    module_deps: RefCell<HashMap<String, std::collections::HashSet<String>>>,
    /// The same load edges in *load order* (for `meta.load-css` subtree
    /// re-emission, which walks dependencies upstream-first).
    module_dep_order: RefCell<HashMap<String, Vec<String>>>,
    /// `meta.load-css` copy scopes: (copy key, base module key). An origin
    /// inside the base's subtree also sees the copy (its extensions apply to
    /// the clone), in addition to the caller-edge reachability.
    load_css_copies: RefCell<Vec<(String, String)>>,
    /// Monotonic counter for unique load-css copy keys.
    copy_counter: std::cell::Cell<usize>,
    /// Queue of merged nested `@media` nodes bubbling out of an enclosing
    /// media rule, taken in order at the `\u{0}MEDIA_HOIST\u{0}` markers the
    /// inner rule leaves in the outer body.
    media_hoist: Vec<Vec<OutNode>>,
    /// Batches hoisted by `@at-root` queries, taken in order at the
    /// `AT_ROOT_HOIST_MARKER`s; each batch is already re-wrapped in the kept
    /// at-rule layers BELOW its graft target and travels outward to it.
    at_root_hoist: std::collections::VecDeque<AtRootBatch>,
    /// The enclosing at-rule layers (outermost first), so `@at-root` queries
    /// can re-wrap their body in the layers the query keeps.
    at_rule_ctx: Vec<AtCtx>,
    /// Bogus-combinator selectors omitted from the CSS (`.a > + x`): they
    /// still satisfy `@extend` target matching like dart's extend graph.
    bogus_selectors: Vec<String>,
    /// Placeholder-rule selectors seen during eval (module key, selector).
    /// An empty placeholder rule is pruned from the output tree but still
    /// counts as an `@extend` target within the modules the extension sees.
    placeholder_rules: Vec<(String, String)>,
    /// Set while module loads run inside a module-loading `@import`: dart
    /// clones the whole import subtree's CSS at the import site (the same
    /// `_combineCss(clone: true)` as meta.load-css). All loads in the chain
    /// share ONE copy scope key and ONE visited set (a diamond emits its
    /// shared upstream once per import, not once per use edge), and record no
    /// main-tree edge.
    import_clone: Option<(String, std::collections::HashSet<String>)>,
    /// The directory of the file currently being evaluated, used to resolve
    /// relative `@use`/`@forward`/`@import` URLs against the containing file
    /// first (dart-sass resolution order).
    current_file_dir: Option<String>,
    /// Whether evaluation is inside a `@keyframes` body: frame blocks are not
    /// style rules in dart-sass, so nested at-rules do not bubble out of them
    /// and frame selectors get keyframe normalization (`E` -> `e`).
    in_keyframes: bool,
    /// dart `_atRootExcludingStyleRule`: inside `@at-root` (before the first
    /// nested style rule) the implicit parent join is disabled — `&` still
    /// resolves against the enclosing rule, but a plain selector stays at the
    /// root instead of nesting under it.
    at_root_excluding_style_rule: bool,
    /// Global variables that were written by an `@import`ed `@forward` merge,
    /// with the source module each came from (by pointer). In dart-sass such
    /// a variable stays bound to its module: re-importing the SAME forwards
    /// must not clobber an intervening assignment (`@import "f"; $a: changed;
    /// @import "f"` keeps `changed`), while a user-defined global IS
    /// overwritten by the first merge — and a forward of the same name from a
    /// DIFFERENT module overrides the previous binding (sass/dart-sass#888).
    forwarded_globals: HashMap<String, usize>,
    /// Built-in modules made available via `@use "sass:<mod>"`, keyed by the
    /// in-scope namespace (default = the part after `sass:`, or the `as ns`
    /// override). The value is the canonical built-in module name (e.g.
    /// `math`).
    used_modules: HashMap<String, String>,
    /// Built-in modules brought into scope unprefixed via `@use "sass:<mod>"
    /// as *`. Their members resolve as bare calls/variables.
    star_modules: Vec<String>,
    /// User stylesheet modules brought into scope via `@use "<file>" [as ns]`,
    /// keyed by the in-scope namespace.
    used_user_modules: HashMap<String, Rc<Module>>,
    /// User modules brought into scope unprefixed via `@use "<file>" as *`.
    star_user_modules: Vec<Rc<Module>>,
    /// All user modules loaded so far, keyed by the importer's canonical key so
    /// each file is evaluated once and shared between every `@use`/`@forward`.
    /// Shared so a module's own forwarded sub-modules see the same cache.
    module_cache: Rc<RefCell<HashMap<String, Rc<Module>>>>,
    /// Members re-exported from the module currently being evaluated, collected
    /// from its `@forward` rules. Empty when not evaluating a module.
    forwarded: Forwarded,
    /// Configuration (`@use/@forward ... with`) supplied for the module
    /// currently being evaluated, consumed by its `!default` declarations.
    /// Maps variable name -> (value, is_default_override).
    pending_config: HashMap<String, (Value, bool)>,
    /// The opaque identity of the ORIGINAL explicit configuration the pending
    /// config derives from (0 = none/implicit). dart-sass allows re-loading
    /// an already-loaded module with a configuration that shares the same
    /// original (a `with (...)` distributed through several forwards).
    pending_config_id: usize,
    /// Counter for fresh explicit-configuration identities.
    config_id_counter: std::cell::Cell<usize>,
    /// Config keys actually consumed by a `!default` declaration in the module
    /// currently being evaluated (used to reject unused configuration).
    consumed_config: Vec<String>,
    /// The name of the member whose body is currently executing, as it appears
    /// in a diagnostic stack frame: `root stylesheet` at the entrypoint, or
    /// `<name>()` inside a user mixin/function. dart-sass `_member`.
    member: String,
    /// The diagnostic call stack: one entry per active user callable/import,
    /// recording the call site and the *caller's* member name. dart-sass
    /// `_stack`. Used to render byte-exact stack traces under errors/warnings.
    call_stack: Vec<DiagFrame>,
    /// The file path/URL the statements currently being evaluated came from
    /// (the entrypoint URL, or an imported/used partial's path).
    current_url: String,
    /// The source text of [`Self::current_url`], for rendering snippets that
    /// point into the currently-executing file.
    current_source: Rc<str>,
    /// Sources of every file seen so far, keyed by URL, so a stack trace can
    /// render a snippet that points into a file other than the current one.
    file_sources: Rc<RefCell<HashMap<String, Rc<str>>>>,
    /// Per-id count of deprecation warnings already *printed* (capped at 5 each,
    /// dart-sass). Keyed by the deprecation `[id]`.
    deprecations_shown: HashMap<&'static str, u32>,
    /// Total deprecation warnings *omitted* by the per-id cap, summed across
    /// ids; rendered into the aggregate footer at the end of the compile.
    deprecations_omitted: u32,
    /// Per-location dedup: a `(id, url, line, col)` already warned about is not
    /// warned about again (dart-sass collapses identical repeated warnings).
    deprecations_seen: std::collections::HashSet<(&'static str, String, usize, usize)>,
    /// Small interned ids for source URLs, stamped into [`SrcLines`] so the
    /// serializer's trailing-comment rule can require same-file adjacency.
    file_ids: HashMap<String, u32>,
}

/// One frame of the diagnostic call stack: the call site (file + 1-based
/// position) and the name of the member that contained that call.
#[derive(Clone)]
struct DiagFrame {
    url: String,
    pos: Pos,
    /// The member name to print for this frame (`root stylesheet` or `name()`).
    member: String,
    /// Byte length of the call-site span, to size the snippet caret when this
    /// frame is the primary (innermost) one — used by `@error`.
    length: usize,
}

/// An evaluated user module: its public members plus the bindings it itself
/// `@use`d (so a `ns.member` lookup can recurse through forwards).
struct Module {
    /// Top-level variables (the module's global scope). Shared and mutable so an
    /// outside `ns.$var: value` assignment updates the module and its own
    /// functions/mixins observe the new value on their next call.
    vars: Scope,
    /// Top-level functions/mixins (the module's global frame). Shared by Rc
    /// with the chains the module's own callables captured, so they resolve
    /// each other (and forwarded members merged after evaluation).
    functions: FnScope,
    mixins: FnScope,
    /// Namespaced user modules this module `@use`d (for transitive `ns.fn()`
    /// calls evaluated inside this module's own functions/mixins).
    used_user_modules: HashMap<String, Rc<Module>>,
    star_user_modules: Vec<Rc<Module>>,
    /// Built-in modules this module `@use`d, by namespace, and unprefixed.
    used_builtin_modules: HashMap<String, String>,
    star_builtin_modules: Vec<String>,
    /// Built-in `sass:*` modules re-exported via `@forward`. A `ns.member` that
    /// misses every captured member is retried against these.
    forwarded_builtins: Vec<ForwardedBuiltin>,
    /// For members re-exported via `@forward`, the module they actually live
    /// in (the variable entry also carries the ORIGINAL name): reads, writes
    /// and calls route there so the defining module's environment is live.
    var_origins: HashMap<String, (Rc<Module>, String)>,
    /// Like `var_origins`, but kept even when the module's own same-named
    /// variable SHADOWS the forwarded one: dart reads the own variable but a
    /// namespaced *assignment* still writes through to the forwarded module.
    var_write_origins: HashMap<String, (Rc<Module>, String)>,
    fn_origins: HashMap<String, Rc<Module>>,
    mixin_origins: HashMap<String, Rc<Module>>,
    /// The path/URL of this module's file, for diagnostic snippets pointing
    /// into the module (empty when diagnostics are disabled / unknown).
    diag_url: String,
    /// The identity of the original explicit configuration this module was
    /// first evaluated with (0 = none/implicit).
    config_origin: std::cell::Cell<usize>,
    /// The directory of the module's resolved file (for relative URL
    /// resolution while the module's own code runs); empty when unknown.
    file_dir: String,
    /// Whether this module's CSS has been emitted into the MAIN tree (an
    /// ordinary `@use`/`@forward` load). A module first loaded inside an
    /// `@import`/load-css clone has not — the next plain load emits it.
    emitted_main: std::cell::Cell<bool>,
    /// The module's emitted CSS, captured at first evaluation so an
    /// `@import`-reached module can re-emit it at each import site (dart
    /// clones the module's CSS tree per import).
    css: Vec<OutNode>,
}

impl Module {
    /// Look up a public variable. Names are dash/underscore-insensitive, so an
    /// exact miss falls back to comparing the canonical (dashed) form against
    /// every key. Private members (leading `-`/`_`) are the caller's
    /// responsibility to exclude.
    fn var(&self, name: &str) -> Option<Value> {
        // A forwarded member reads live from its defining module.
        if let Some((m, oname)) = self.var_origin(name) {
            return m.var(&oname);
        }
        let vars = self.vars.borrow();
        if let Some(v) = vars.get(name) {
            return Some(v.clone());
        }
        let norm = normalize_var_name(name);
        vars.iter()
            .find(|(k, _)| normalize_var_name(k) == norm)
            .map(|(_, v)| v.clone())
    }
    /// The defining module (and original variable name) of a forwarded
    /// variable, dash/underscore-insensitively.
    fn var_origin(&self, name: &str) -> Option<(Rc<Module>, String)> {
        if let Some((m, o)) = self.var_origins.get(name) {
            return Some((Rc::clone(m), o.clone()));
        }
        let norm = normalize_var_name(name);
        self.var_origins
            .iter()
            .find(|(k, _)| normalize_var_name(k) == norm)
            .map(|(_, (m, o))| (Rc::clone(m), o.clone()))
    }
    /// The write-through target of a forwarded variable (kept even when
    /// shadowed by the module's own same-named variable).
    fn var_write_origin(&self, name: &str) -> Option<(Rc<Module>, String)> {
        if let Some((m, o)) = self.var_write_origins.get(name) {
            return Some((Rc::clone(m), o.clone()));
        }
        let norm = normalize_var_name(name);
        self.var_write_origins
            .iter()
            .find(|(k, _)| normalize_var_name(k) == norm)
            .map(|(_, (m, o))| (Rc::clone(m), o.clone()))
    }
    /// The defining module of a forwarded function/mixin.
    fn fn_origin(&self, name: &str) -> Option<Rc<Module>> {
        if let Some(m) = self.fn_origins.get(name) {
            return Some(Rc::clone(m));
        }
        let norm = normalize_var_name(name);
        self.fn_origins
            .iter()
            .find(|(k, _)| normalize_var_name(k) == norm)
            .map(|(_, m)| Rc::clone(m))
    }
    fn mixin_origin(&self, name: &str) -> Option<Rc<Module>> {
        if let Some(m) = self.mixin_origins.get(name) {
            return Some(Rc::clone(m));
        }
        let norm = normalize_var_name(name);
        self.mixin_origins
            .iter()
            .find(|(k, _)| normalize_var_name(k) == norm)
            .map(|(_, m)| Rc::clone(m))
    }
    fn function(&self, name: &str) -> Option<Rc<UserCallable>> {
        let fns = self.functions.borrow();
        if let Some(f) = fns.get(name) {
            return Some(Rc::clone(f));
        }
        let norm = normalize_var_name(name);
        fns.iter()
            .find(|(k, _)| normalize_var_name(k) == norm)
            .map(|(_, f)| Rc::clone(f))
    }
    fn mixin(&self, name: &str) -> Option<Rc<UserCallable>> {
        let mixins = self.mixins.borrow();
        if let Some(m) = mixins.get(name) {
            return Some(Rc::clone(m));
        }
        let norm = normalize_var_name(name);
        mixins
            .iter()
            .find(|(k, _)| normalize_var_name(k) == norm)
            .map(|(_, m)| Rc::clone(m))
    }
}

/// A `@content` block plus, when the enclosing `@include` targets a mixin from
/// another module, a snapshot of the call-site environment in which the content
/// must run (dart-sass: a content block closes over its definition site).
struct ContentBlock {
    stmts: Rc<Vec<Stmt>>,
    /// The `using (params)` clause's parameters; `@content(args)` binds its
    /// arguments to these before the block runs.
    params: Option<Rc<ParamList>>,
    /// `Some` only for a cross-module include: the environment to install while
    /// the block runs, so the content resolves against the call site, not the
    /// mixin's module.
    caller_env: Option<Box<SavedModuleEnv>>,
}

/// The caller-side environment saved while a cross-module member call runs in
/// the callee module's environment.
#[derive(Clone)]
struct SavedModuleEnv {
    scopes: Vec<Scope>,
    scope_semi_global: Vec<bool>,
    functions: Vec<FnScope>,
    mixins: Vec<FnScope>,
    used_modules: HashMap<String, String>,
    star_modules: Vec<String>,
    used_user_modules: HashMap<String, Rc<Module>>,
    star_user_modules: Vec<Rc<Module>>,
    /// When set (a cross-module call), the module whose global scope was
    /// installed: `leave_module` writes the (possibly mutated) global scope back
    /// so a `!global` assignment inside the module persists.
    write_back: Option<Rc<Module>>,
}

/// Members a module re-exports via `@forward`, accumulated while it evaluates.
#[derive(Default)]
struct Forwarded {
    vars: HashMap<String, Value>,
    functions: HashMap<String, Rc<UserCallable>>,
    mixins: HashMap<String, Rc<UserCallable>>,
    /// The module each re-exported member actually lives in (with the
    /// member's ORIGINAL name for variables), so calls/assignments through
    /// the forward run against the defining module's environment.
    var_origins: HashMap<String, (Rc<Module>, String)>,
    fn_origins: HashMap<String, Rc<Module>>,
    mixin_origins: HashMap<String, Rc<Module>>,
    /// Built-in `sass:*` modules re-exported via `@forward "sass:x"`.
    builtins: Vec<ForwardedBuiltin>,
    /// For each re-exported member name, the source module it came from (by
    /// pointer). Re-forwarding the SAME module is idempotent (no conflict);
    /// forwarding a same-named member from a DIFFERENT module is a conflict.
    var_src: HashMap<String, *const Module>,
    fn_src: HashMap<String, *const Module>,
    mixin_src: HashMap<String, *const Module>,
}

/// A built-in module re-exported via `@forward "sass:x" [as p-*] [show|hide ...]`.
#[derive(Clone)]
struct ForwardedBuiltin {
    module: String,
    prefix: Option<String>,
    /// `show` allow-list of member names; `None` when no `show` clause.
    show: Option<std::collections::HashSet<String>>,
    /// `hide` deny-list of member names.
    hide: Option<std::collections::HashSet<String>>,
}

impl ForwardedBuiltin {
    /// Whether a re-exported built-in member (given by its bare, un-prefixed
    /// name) is visible through this forward.
    fn visible(&self, bare: &str) -> bool {
        if let Some(show) = &self.show {
            return show.contains(bare);
        }
        if let Some(hide) = &self.hide {
            return !hide.contains(bare);
        }
        true
    }
}

/// A pending `@extend`, captured during eval and applied after flattening.
struct PendingExtend {
    /// The resolved target simple selector (e.g. `.foo`, `%bar`).
    target: crate::selector::Simple,
    /// The resolved target selector string, for error messages.
    target_str: String,
    /// The enclosing rule's resolved selector list (the extenders).
    extenders: Vec<String>,
    /// Source line-break flags parallel to `extenders` (an extend product
    /// inherits its extender's flag, dart's ComplexSelector.lineBreak).
    extender_breaks: Vec<bool>,
    optional: bool,
    /// Whether this `@extend` was registered inside a `@media` context.
    in_media: bool,
    /// The canonical key of the module this `@extend` was written in
    /// (empty for the root stylesheet).
    origin: String,
    pos: Pos,
}

impl<'a> Evaluator<'a> {
    pub(crate) fn new(options: EvalOptions<'a>) -> Self {
        let url = options.url.to_string();
        let entry_dir = dirname_of(options.url).unwrap_or_default();
        let source: Rc<str> = Rc::from(options.source);
        let file_sources: HashMap<String, Rc<str>> =
            [(url.clone(), Rc::clone(&source))].into_iter().collect();
        Evaluator {
            member: "root stylesheet".to_string(),
            call_stack: Vec::new(),
            current_url: url,
            current_source: source,
            file_sources: Rc::new(RefCell::new(file_sources)),
            deprecations_shown: HashMap::default(),
            deprecations_omitted: 0,
            deprecations_seen: std::collections::HashSet::new(),
            file_ids: HashMap::default(),
            scopes: vec![new_scope()],
            // The global scope is treated as semi-global so a top-level control
            // flow scope (its child) becomes semi-global too.
            scope_semi_global: vec![true],
            options,
            loading: Vec::new(),
            import_cache: HashMap::default(),
            current_url_stamp: 0,
            functions: vec![new_fn_scope()],
            mixins: vec![new_fn_scope()],
            content_stack: Vec::new(),
            in_mixin: Vec::new(),
            media_queries: Vec::new(),
            current_selector: None,
            current_linebreaks: Vec::new(),
            extends: Vec::new(),
            decl_prefix: None,
            in_supports_declaration: false,
            in_plain_css: false,
            config_is_implicit: false,
            forwarded_globals: HashMap::default(),
            current_module: String::new(),
            module_deps: RefCell::new(HashMap::default()),
            module_dep_order: RefCell::new(HashMap::default()),
            load_css_copies: RefCell::new(Vec::new()),
            copy_counter: std::cell::Cell::new(0),
            in_keyframes: false,
            at_root_excluding_style_rule: false,
            import_clone: None,
            // The entry file's containing directory (possibly "" = the
            // CWD-relative root): relative imports resolve against it first,
            // like dart — NOT via an implicit load path.
            current_file_dir: Some(entry_dir),
            media_hoist: Vec::new(),
            at_root_hoist: std::collections::VecDeque::new(),
            at_rule_ctx: Vec::new(),
            bogus_selectors: Vec::new(),
            placeholder_rules: Vec::new(),
            used_modules: HashMap::default(),
            star_modules: Vec::new(),
            used_user_modules: HashMap::default(),
            star_user_modules: Vec::new(),
            module_cache: Rc::new(RefCell::new(HashMap::default())),
            forwarded: Forwarded::default(),
            pending_config: HashMap::default(),
            pending_config_id: 0,
            config_id_counter: std::cell::Cell::new(0),
            consumed_config: Vec::new(),
        }
    }

    /// Intern the current file's diagnostics URL as a small id for SrcLines.
    /// Parser-produced lines (`file == 0`) become "this file"; a default
    /// (all-zero) value stays disabled.
    fn stamp(&mut self, mut lines: SrcLines) -> SrcLines {
        if lines == SrcLines::default() {
            return lines;
        }
        // stamp runs for every source-line-carrying node; the id is interned
        // once per file entry (every `current_url` assignment resets it), so
        // the per-node cost is a u32 check.
        if self.current_url_stamp != 0 {
            lines.file = self.current_url_stamp;
            return lines;
        }
        let next = self.file_ids.len() as u32 + 1;
        let id = *self.file_ids.entry(self.current_url.clone()).or_insert(next);
        self.current_url_stamp = id;
        lines.file = id;
        lines
    }

    pub(crate) fn eval_sheet(&mut self, sheet: &Stylesheet, out: &mut Vec<OutNode>) -> Result<(), Error> {
        {
            let mut sink = Sink::Top(out);
            let r = self.exec(&sheet.stmts, &[], &mut sink);
            // At the outermost boundary, finalize any error into a rendered
            // diagnostic block (header + snippet + frames) if we have a span.
            if let Err(e) = r {
                let e = self.finalize_error(e);
                self.emit_deprecation_footer();
                return Err(e);
            }
        }
        self.apply_extends(out)?;
        hoist_css_imports(out);
        self.emit_deprecation_footer();
        Ok(())
    }

    // ---- diagnostic rendering -------------------------------------------

    /// Whether the entrypoint supplied source text (so snippets can render).
    fn diag_enabled(&self) -> bool {
        !self.options.source.is_empty()
    }

    /// Build the diagnostic stack-frame list (innermost first) for a primary
    /// span located at `pos` in `self.current_url`, executed by `self.member`.
    /// This is `[(current file, pos, member)]` followed by the recorded call
    /// stack, outermost last — exactly dart-sass's `_stackTrace`.
    fn frames_for(&self, pos: Pos) -> Vec<DiagFrame> {
        let mut frames = Vec::with_capacity(self.call_stack.len() + 1);
        frames.push(DiagFrame {
            url: self.current_url.clone(),
            pos,
            member: self.member.clone(),
            length: 0,
        });
        frames.extend(self.call_stack.iter().rev().cloned());
        frames
    }

    /// Render the stack-frame list into the column-aligned block dart-sass
    /// appends under a snippet/warning. `indent` is 2 (errors) or 4
    /// (warnings/deprecations).
    fn render_frame_block(frames: &[DiagFrame], indent: usize) -> String {
        // Column-align: pad each `<url> <line>:<col>` field to the longest.
        let fields: Vec<String> = frames
            .iter()
            .map(|f| format!("{} {}:{}", f.url, f.pos.line, f.pos.col))
            .collect();
        let width = fields.iter().map(String::len).max().unwrap_or(0);
        let pad: String = " ".repeat(indent);
        let mut out = String::new();
        for (i, (field, frame)) in fields.iter().zip(frames).enumerate() {
            if i > 0 {
                out.push('\n');
            }
            out.push_str(&pad);
            out.push_str(field);
            for _ in 0..width.saturating_sub(field.len()) {
                out.push(' ');
            }
            out.push_str("  ");
            out.push_str(&frame.member);
        }
        out
    }

    /// Look up the source text for `url`, defaulting to the current file's.
    fn source_for(&self, url: &str) -> Rc<str> {
        if url == self.current_url {
            return Rc::clone(&self.current_source);
        }
        self.file_sources
            .borrow()
            .get(url)
            .map(Rc::clone)
            .unwrap_or_else(|| Rc::clone(&self.current_source))
    }

    /// Convert an `Error` into a fully-rendered diagnostic block (header +
    /// snippet + 2-space frame trace), if diagnostics are enabled and the error
    /// carries a position. Idempotent: an already-rendered error is returned
    /// unchanged.
    fn finalize_error(&self, mut e: Error) -> Error {
        if e.rendered.is_some() || !self.diag_enabled() || !e.has_position() {
            return e;
        }
        let frames = self.frames_for(Pos {
            line: e.line,
            col: e.col,
        });
        e.rendered = Some(self.render_error_with_frames(&e, &frames));
        e
    }

    /// Build the "expected selector." error for a `@` in a resolved selector:
    /// when the offending column falls inside an interpolation's output the
    /// error renders dart's dual-span "error in interpolated output" block;
    /// when it maps to literal selector text the source column is recovered
    /// by shifting across the interpolations before it.
    fn interp_selector_error(
        &self,
        rule: &Rule,
        sel_str: &str,
        interp_bounds: &[(usize, usize)],
        at_idx: usize,
    ) -> Error {
        const MSG: &str = "expected selector.";
        let spans = &rule.selector_interp_spans;
        let single_line = !sel_str.contains('\n');
        // Inside an interpolation's output -> dual-span rendering, positioned
        // at the interpolation expression's start.
        if spans.len() == interp_bounds.len() {
            for (k, &(start, len)) in interp_bounds.iter().enumerate() {
                if at_idx >= start && at_idx < start + len {
                    let (line, col_start, col_end) = spans[k];
                    let pos = Pos {
                        line: line as usize,
                        col: col_start as usize,
                    };
                    let mut e = Error::at(MSG, pos);
                    if self.diag_enabled() {
                        let source = self.source_for(&self.current_url.clone());
                        let frames = self.frames_for(pos);
                        let mut rendered = format!("Error: {MSG}\n");
                        rendered.push_str(&crate::diag::render_interp_error_snippet(
                            &source,
                            line as usize,
                            col_start as usize,
                            col_end as usize,
                            sel_str,
                            at_idx + 1,
                            &frames[0].url,
                            self.options.glyphs,
                        ));
                        rendered.push('\n');
                        rendered.push_str(&Self::render_frame_block(&frames, 2));
                        e.rendered = Some(rendered);
                    }
                    return e;
                }
            }
        }
        // Literal text: recover the source column by shifting across the
        // interpolations that precede the offending index.
        if single_line
            && spans.len() == interp_bounds.len()
            && spans
                .iter()
                .all(|&(l, _, _)| l as usize == rule.selector_pos.line)
        {
            let mut shift: i64 = 0;
            for (k, &(start, len)) in interp_bounds.iter().enumerate() {
                if at_idx >= start + len {
                    let (_, col_start, col_end) = spans[k];
                    // The source text `#{ ... }` spans from 2 before the
                    // expression start through the closing brace.
                    let src_total = (col_end as i64 + 1) - (col_start as i64 - 2);
                    shift += src_total - len as i64;
                }
            }
            let col = (rule.selector_pos.col as i64 + at_idx as i64 + shift).max(1) as usize;
            return Error::at(
                MSG,
                Pos {
                    line: rule.selector_pos.line,
                    col,
                },
            );
        }
        Error::at(MSG, rule.selector_pos)
    }

    /// Render `Error: <msg>` + the snippet pointing at the innermost frame +
    /// the 2-space-indented frame trace.
    fn render_error_with_frames(&self, e: &Error, frames: &[DiagFrame]) -> String {
        let primary = &frames[0];
        let source = self.source_for(&primary.url);
        // Prefer the primary frame's own span length (set for `@error`'s call
        // site); otherwise the error's recorded length.
        let length = if primary.length > 0 {
            primary.length
        } else {
            e.length
        };
        let span = crate::diag::Span {
            line: primary.pos.line,
            col: primary.pos.col,
            length,
        };
        let mut out = format!("Error: {}\n", e.message);
        out.push_str(&crate::diag::render_snippet(
            &source,
            span,
            &[],
            self.options.glyphs,
        ));
        out.push('\n');
        out.push_str(&Self::render_frame_block(frames, 2));
        out
    }

    /// Emit a deprecation warning at `pos` (caret length `len`): the header
    /// block + a snippet pointing at the deprecated construct + a 4-space stack
    /// trace + a trailing blank line. Honours dart-sass's per-location dedup and
    /// per-id cap of 5 (further occurrences are counted into the aggregate
    /// footer rendered by [`Self::emit_deprecation_footer`]). No-op when
    /// diagnostics are disabled.
    fn emit_deprecation(&mut self, dep: &crate::deprecation::Deprecation, pos: Pos, len: usize) {
        if !self.diag_enabled() {
            return;
        }
        // Per-location dedup: an identical (id, file, line, col) warning fires
        // only once.
        let key = (dep.id, self.current_url.clone(), pos.line, pos.col);
        if !self.deprecations_seen.insert(key) {
            return;
        }
        let count = self.deprecations_shown.entry(dep.id).or_insert(0);
        if *count >= 5 {
            self.deprecations_omitted += 1;
            return;
        }
        *count += 1;

        let frames = self.frames_for(pos);
        let span = crate::diag::Span {
            line: pos.line,
            col: pos.col,
            length: len,
        };
        let source = self.source_for(&self.current_url.clone());
        let mut block = dep.render_header();
        block.push_str(&crate::diag::render_snippet(
            &source,
            span,
            &[],
            self.options.glyphs,
        ));
        block.push('\n');
        block.push_str(&Self::render_frame_block(&frames, 4));
        eprintln!("{block}\n");
    }

    /// Emit the aggregate "N repetitive deprecation warnings omitted" footer at
    /// the end of the compile, if the per-id cap dropped any warnings.
    fn emit_deprecation_footer(&self) {
        if self.deprecations_omitted == 0 {
            return;
        }
        eprintln!(
            "WARNING: {} repetitive deprecation warnings omitted.\nRun in verbose mode to see all warnings.\n",
            self.deprecations_omitted
        );
    }

    /// Enter a user callable (mixin/function) for diagnostics: record a stack
    /// frame at `call_pos` (caret length `call_len`) attributed to the *current*
    /// member, then make `new_member` the current member. Returns the previous
    /// member name, to be restored by [`Self::leave_call`].
    fn enter_call(&mut self, call_pos: Pos, call_len: usize, new_member: &str) -> String {
        self.call_stack.push(DiagFrame {
            url: self.current_url.clone(),
            pos: call_pos,
            member: self.member.clone(),
            length: call_len,
        });
        std::mem::replace(&mut self.member, new_member.to_string())
    }

    /// Leave a user callable: pop its diagnostic frame and restore `member`.
    fn leave_call(&mut self, saved_member: String) {
        self.call_stack.pop();
        self.member = saved_member;
    }

    /// Execute a `@warn`: emit `WARNING: <message>` + the 4-space-indented stack
    /// trace + a trailing blank line to stderr. The message is the string value
    /// unquoted; exit code is unaffected.
    fn emit_warn(&mut self, value: &Expr, pos: Pos) -> Result<(), Error> {
        let v = self.eval_expr(value)?;
        let msg = v.to_message();
        if self.diag_enabled() {
            let frames = self.frames_for(pos);
            eprintln!("WARNING: {}\n{}\n", msg, Self::render_frame_block(&frames, 4));
        } else {
            eprintln!("WARNING: {msg}");
        }
        Ok(())
    }

    /// Execute a `@debug`: emit `<path>:<line> DEBUG: <value>` to stderr (the
    /// value serialized as in CSS, a string unquoted). No snippet, no frames.
    fn emit_debug(&mut self, value: &Expr, pos: Pos) -> Result<(), Error> {
        let v = self.eval_expr(value)?;
        let msg = v.to_message();
        if self.diag_enabled() {
            eprintln!("{}:{} DEBUG: {}", self.current_url, pos.line, msg);
        } else {
            eprintln!("DEBUG: {msg}");
        }
        Ok(())
    }

    /// Build the error for an `@error`: its message is the serialized argument
    /// (a string keeps its quotes). The snippet points at the innermost active
    /// call site (so an `@error` inside a mixin highlights the `@include`), or
    /// at the `@error` statement itself when there is no enclosing call. dart's
    /// "unspanned exception attaches at the boundary" rule.
    fn build_error(&mut self, value: &Expr, pos: Pos, length: usize) -> Error {
        let msg = match self.eval_expr(value) {
            Ok(v) => v.to_error_message(),
            Err(e) => return e,
        };
        if !self.diag_enabled() {
            return Error::unpositioned(msg);
        }
        // The @error throws unspanned; the nearest enclosing call boundary
        // attaches its span. With an active call stack, the snippet points at
        // the innermost call site and the trace is the callers only (the
        // @error's own frame is dropped). At the root, the @error span is used.
        let frames: Vec<DiagFrame> = if self.call_stack.is_empty() {
            vec![DiagFrame {
                url: self.current_url.clone(),
                pos,
                member: self.member.clone(),
                length,
            }]
        } else {
            self.call_stack.iter().rev().cloned().collect()
        };
        let mut e = Error::at(msg, frames[0].pos);
        e.length = frames[0].length;
        e.rendered = Some(self.render_error_with_frames(&e, &frames));
        e
    }

    /// Register an `@extend` directive: validate the (interpolation-resolved)
    /// target, then record one [`PendingExtend`] per comma-separated target.
    /// `parents` is the enclosing style-rule selector list; `@extend` outside a
    /// style rule (top level or directly inside `@at-root`/an at-rule) is an
    /// error.
    fn register_extend(
        &mut self,
        selector: &[TplPiece],
        optional: bool,
        pos: Pos,
        parents: &[String],
    ) -> Result<(), Error> {
        // dart checks `_styleRule` (null inside `@at-root` before any nested
        // rule), not `_styleRuleIgnoringAtRoot` (which still feeds `&`).
        if parents.is_empty() || self.at_root_excluding_style_rule {
            return Err(Error::at("@extend may only be used within style rules.", pos));
        }
        let extenders = self.current_selector.clone().unwrap_or_else(|| parents.to_vec());
        let target = self.eval_template(selector)?;
        if target.trim().is_empty() {
            return Err(Error::at("expected selector.", pos));
        }
        let in_media = !self.media_queries.is_empty();
        for t in split_commas(&target) {
            let t = t.trim();
            if t.is_empty() {
                continue;
            }
            match crate::selector::classify_target(t) {
                crate::selector::TargetClass::Simple(simple) => {
                    self.extends.push(PendingExtend {
                        origin: self.current_module.clone(),
                        target: simple,
                        target_str: t.to_string(),
                        extenders: extenders.clone(),
                        extender_breaks: self.current_linebreaks.clone(),
                        optional,
                        in_media,
                        pos,
                    });
                }
                crate::selector::TargetClass::Complex => {
                    return Err(Error::at("complex selectors may not be extended.", pos));
                }
                crate::selector::TargetClass::Compound => {
                    return Err(Error::at(
                        "compound selectors may no longer be extended.\n\
                         Consider `@extend a, :hover` instead.\n\
                         See https://sass-lang.com/d/extend-compound for details.",
                        pos,
                    ));
                }
                crate::selector::TargetClass::Invalid => {
                    return Err(Error::at("expected selector.", pos));
                }
            }
        }
        Ok(())
    }

    /// Post-eval extension pass: rewrite every emitted style-rule selector list
    /// according to the collected `@extend` directives, drop placeholder-only
    /// rules, and error on an unmatched non-`!optional` extend.
    fn apply_extends(&mut self, out: &mut Vec<OutNode>) -> Result<(), Error> {
        // Per-origin upstream closures over the recorded load edges (the
        // module keys each origin can see, including itself).
        let deps = self.module_deps.borrow();
        let bfs = |start: &str| {
            let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
            seen.insert(start.to_string());
            let mut stack = vec![start.to_string()];
            while let Some(k) = stack.pop() {
                if let Some(nexts) = deps.get(&k) {
                    for n in nexts {
                        if seen.insert(n.clone()) {
                            stack.push(n.clone());
                        }
                    }
                }
            }
            seen
        };
        let mut raw_cache: HashMap<String, std::collections::HashSet<String>> = HashMap::default();
        for pe in &self.extends {
            if raw_cache.contains_key(&pe.origin) {
                continue;
            }
            let seen = bfs(&pe.origin);
            raw_cache.insert(pe.origin.clone(), seen);
        }
        // A `meta.load-css` copy is also visible to any origin inside the
        // copied module's subtree: the clone carries that subtree's own
        // extensions (dart bakes them into the cloned CSS).
        let copies = self.load_css_copies.borrow();
        for (copy_key, base) in copies.iter() {
            let base_reach = bfs(base);
            for (origin, set) in raw_cache.iter_mut() {
                if base_reach.contains(origin) {
                    set.insert(copy_key.clone());
                }
            }
        }
        // An origin NOT reachable from the root tree (it was only ever
        // pulled in through `meta.load-css`) exists solely inside the
        // clones: its extensions apply to copy scopes only, never to the
        // main tree's module scopes (dart: such a module's extension store
        // never joins the root `_combineCss`).
        if !copies.is_empty() {
            let main_reach = bfs("");
            for (origin, set) in raw_cache.iter_mut() {
                if !origin.is_empty() && !main_reach.contains(origin) {
                    set.retain(|s| copies.iter().any(|(ck, _)| ck == s));
                }
            }
        }
        drop(copies);
        drop(deps);
        let closure_cache: HashMap<String, std::rc::Rc<std::collections::HashSet<String>>> = raw_cache
            .into_iter()
            .map(|(k, v)| (k, std::rc::Rc::new(v)))
            .collect();
        let mut extensions: Vec<crate::selector::Extension> = Vec::new();
        for pe in &self.extends {
            let mut extenders = Vec::new();
            let mut extender_breaks = Vec::new();
            for (i, ext) in pe.extenders.iter().enumerate() {
                if let Some(c) = crate::selector::parse_complex_one(ext) {
                    // A bogus extender with a trailing combinator (`d +`) can't
                    // extend anything — dart-sass drops it (with a deprecation).
                    if c.trailing.is_empty() {
                        extenders.push(c);
                        extender_breaks.push(pe.extender_breaks.get(i).copied().unwrap_or(false));
                    }
                }
            }
            extensions.push(crate::selector::Extension {
                target: Some(pe.target.clone()),
                extenders,
                extender_breaks,
                optional: pe.optional,
                matched: std::rc::Rc::new(std::cell::Cell::new(false)),
                origin: pe.origin.clone(),
                origin_closure: std::rc::Rc::clone(&closure_cache[&pe.origin]),
            });
        }
        // Apply DOWNSTREAM origins first (dart `_combineCss` concatenates module
        // extension stores upstream-first, so the most-downstream store's
        // products land LAST in the output). A downstream module's closure is a
        // strict superset of its upstreams', so a STABLE sort by descending
        // closure size orders the fold's batches downstream-first while keeping
        // same-module document order. With the per-selector origin gating and the
        // fixpoint re-fold, this reproduces dart's cross-module output order —
        // e.g. a root `@import`ed `@extend` (closure = everything) applies first
        // so its product trails a `@use`d module's (use/extend/scope:*), while a
        // transitive upstream chain still settles via the fixpoint.
        extensions.sort_by_key(|e| std::cmp::Reverse(closure_cache.get(&e.origin).map_or(0, |c| c.len())));

        // An `@extend` registered inside `@media` may not extend a selector
        // outside any media context (dart-sass "You may not @extend selectors
        // across media queries."). Detect when an in-media extend's target
        // matches a root-level (non-media) rule.
        for pe in &self.extends {
            if pe.in_media && root_rule_contains_target(out, &pe.target) {
                return Err(Error::at(
                    "You may not @extend selectors across media queries.",
                    pe.pos,
                ));
            }
        }

        // Per-module visibility: an extension's origin can rewrite a module's
        // CSS when that module is (transitively) loaded by the origin.
        // Parallel to the (sorted) extensions list.
        let origins: Vec<String> = extensions.iter().map(|e| e.origin.clone()).collect();
        let closures: HashMap<String, std::collections::HashSet<String>> = closure_cache
            .iter()
            .map(|(k, v)| (k.clone(), (**v).clone()))
            .collect();
        rewrite_nodes_scoped(out, "", &extensions, &origins, &closures);

        // Report the first unmatched non-optional extend. A target that only
        // appears in an omitted bogus-combinator rule still counts as found
        // (dart extends it; the result is bogus too and is omitted).
        for (pe, ext) in self.extends.iter().zip(extensions.iter()) {
            // A private placeholder (`%-x`/`%_x`) is only visible within its
            // own module; any other target is visible across the extension's
            // module closure.
            let private = matches!(&pe.target,
                crate::selector::Simple::Placeholder(n) if n.starts_with('-') || n.starts_with('_'));
            if !ext.optional
                && !ext.matched.get()
                && !self
                    .bogus_selectors
                    .iter()
                    .any(|s| crate::selector::selector_contains_simple(s, &pe.target))
                && !self.placeholder_rules.iter().any(|(m, s)| {
                    let visible = if private {
                        *m == ext.origin
                    } else {
                        ext.origin_closure.contains(m)
                    };
                    visible && crate::selector::selector_contains_simple(s, &pe.target)
                })
            {
                return Err(Error::at(
                    format!(
                        "The target selector was not found.\nUse \"@extend {} !optional\" to avoid this error.",
                        pe.target_str
                    ),
                    pe.pos,
                ));
            }
        }
        Ok(())
    }

    fn compressed(&self) -> bool {
        matches!(self.options.style, OutputStyle::Compressed)
    }

    // ---- scopes ------------------------------------------------------

    fn lookup(&self, name: &str) -> Option<Value> {
        for scope in self.scopes.iter().rev() {
            if let Some(v) = scope.borrow().get(name) {
                return Some(v.clone());
            }
        }
        None
    }

    /// Capture the current variable and function/mixin scope chains as a
    /// callable's lexical closure (dart `Environment.closure()` — shared
    /// frames, not snapshots).
    fn capture_callable(&self, def: &Rc<Callable>) -> Rc<UserCallable> {
        Rc::new(UserCallable {
            def: Rc::clone(def),
            env: self.scopes.clone(),
            env_semi: self.scope_semi_global.clone(),
            env_fns: self.functions.clone(),
            env_mixins: self.mixins.clone(),
        })
    }

    /// Push a new scope. `semi_global` requests semi-global behavior (control
    /// flow), which only takes effect when the current innermost scope is
    /// already semi-global (dart-sass `Environment.scope`). The function and
    /// mixin chains push in lockstep with the variable chain.
    fn push_scope(&mut self, semi_global: bool) {
        let effective = semi_global && self.scope_semi_global.last().copied().unwrap_or(false);
        self.scopes.push(new_scope());
        self.scope_semi_global.push(effective);
        self.functions.push(new_fn_scope());
        self.mixins.push(new_fn_scope());
    }

    /// Push a pre-populated, non-semi-global scope (a mixin/function argument
    /// frame).
    fn push_scope_frame(&mut self, frame: HashMap<String, Value>) {
        self.scopes.push(std::rc::Rc::new(std::cell::RefCell::new(frame)));
        self.scope_semi_global.push(false);
        self.functions.push(new_fn_scope());
        self.mixins.push(new_fn_scope());
    }

    fn pop_scope(&mut self) {
        self.scopes.pop();
        self.scope_semi_global.pop();
        self.functions.pop();
        self.mixins.pop();
    }

    /// Define a user `@function` in the innermost frame (dart
    /// `visitFunctionRule`: always `_functions.length - 1`, no semi-global
    /// special case), so the definition is scoped to the enclosing block.
    /// Keys are dash-normalized like dart's parse-time `identifier(normalize:
    /// true)` — `@function a_b` and `@function a-b` define the SAME name (the
    /// AST keeps the original spelling for plain-CSS fallback and messages).
    fn define_function(&mut self, name: &str, c: Rc<UserCallable>) {
        if let Some(frame) = self.functions.last() {
            frame.borrow_mut().insert(normalize_arg_name(name), c);
        }
    }

    /// Define a user `@mixin` in the innermost frame (dart `visitMixinRule`).
    fn define_mixin(&mut self, name: &str, c: Rc<UserCallable>) {
        if let Some(frame) = self.mixins.last() {
            frame.borrow_mut().insert(normalize_arg_name(name), c);
        }
    }

    /// Look up a user `@function` (dash/underscore-insensitively, like dart),
    /// innermost frame first.
    fn lookup_function(&self, name: &str) -> Option<Rc<UserCallable>> {
        let key = normalize_arg_name(name);
        for frame in self.functions.iter().rev() {
            if let Some(f) = frame.borrow().get(&key) {
                return Some(Rc::clone(f));
            }
        }
        None
    }

    /// Look up a user `@mixin` (dash/underscore-insensitively), innermost
    /// frame first.
    fn lookup_mixin(&self, name: &str) -> Option<Rc<UserCallable>> {
        let key = normalize_arg_name(name);
        for frame in self.mixins.iter().rev() {
            if let Some(m) = frame.borrow().get(&key) {
                return Some(Rc::clone(m));
            }
        }
        None
    }

    /// Look up a user `@function` dash/underscore-insensitively (for the
    /// `meta` introspection functions), innermost frame first.
    fn lookup_function_norm(&self, key: &str) -> Option<Rc<UserCallable>> {
        for frame in self.functions.iter().rev() {
            let frame = frame.borrow();
            if let Some((_, f)) = frame.iter().find(|(k, _)| normalize_arg_name(k) == key) {
                return Some(Rc::clone(f));
            }
        }
        None
    }

    /// Look up a user `@mixin` dash/underscore-insensitively, innermost first.
    fn lookup_mixin_norm(&self, key: &str) -> Option<Rc<UserCallable>> {
        for frame in self.mixins.iter().rev() {
            let frame = frame.borrow();
            if let Some((_, m)) = frame.iter().find(|(k, _)| normalize_arg_name(k) == key) {
                return Some(Rc::clone(m));
            }
        }
        None
    }

    /// Assign a non-global variable (dart-sass `Environment.setVariable`). The
    /// value updates the variable at the innermost scope where it already
    /// exists; if it exists only in the global scope and the current scope is
    /// not semi-global, a new local is created instead so a nested rule cannot
    /// silently rewrite a global.
    fn assign(&mut self, name: &str, val: Value) {
        if self.scopes.len() == 1 {
            if let Some(g) = self.scopes.first_mut() {
                g.borrow_mut().insert(name.to_string(), val);
            }
            return;
        }
        // Innermost scope index holding the variable (None if undeclared).
        let mut index = None;
        for (i, scope) in self.scopes.iter().enumerate().rev() {
            if scope.borrow().contains_key(name) {
                index = Some(i);
                break;
            }
        }
        let in_semi_global = self.scope_semi_global.last().copied().unwrap_or(false);
        let target = match index {
            Some(0) if !in_semi_global => self.scopes.len() - 1,
            Some(i) => i,
            None => self.scopes.len() - 1,
        };
        if let Some(scope) = self.scopes.get_mut(target) {
            scope.borrow_mut().insert(name.to_string(), val);
        }
    }

    fn apply_var(&mut self, v: &VarDecl) -> Result<(), Error> {
        // A namespaced assignment `ns.$name: value` updates the variable in the
        // `@use`d module bound to `ns`.
        if let Some(ns) = &v.namespace {
            return self.assign_module_var(ns, v);
        }
        // A top-level `!default` declaration whose name is exposed by more than
        // one `@use … as *` module can't resolve which global it shadows.
        if v.is_default
            && self.scopes.len() == 1
            && self.lookup(&v.name).is_none()
            && !is_private_member(&v.name)
            && self
                .star_user_modules
                .iter()
                .filter(|m| m.var(&v.name).is_some())
                .count()
                > 1
        {
            return Err(Error::unpositioned(
                "This variable is available from multiple global modules.",
            ));
        }
        // A top-level `!default` variable in a module being evaluated with
        // configuration: the supplied value overrides the default (unless the
        // override itself is `!default` and the variable already has a value).
        // Configuration is keyed by the canonical (dashed) variable name.
        if v.is_default && self.scopes.len() == 1 {
            let key = normalize_var_name(&v.name);
            if let Some((cfg_val, cfg_is_default)) = self.pending_config.get(&key).cloned() {
                self.consumed_config.push(key);
                let already_set = matches!(self.lookup(&v.name), Some(x) if !matches!(x, Value::Null));
                // A `null` configuration value leaves the `!default` in place;
                // a `@forward ... with ($x !default)` only applies if the module
                // hasn't already defined the variable.
                if !(matches!(cfg_val, Value::Null) || cfg_is_default && already_set) {
                    if let Some(g) = self.scopes.first_mut() {
                        g.borrow_mut().insert(v.name.clone(), cfg_val);
                    }
                    return Ok(());
                }
            }
        }
        let val = self.eval_expr(&v.value)?;
        if v.is_default {
            if let Some(existing) = self.lookup(&v.name) {
                if !matches!(existing, Value::Null) {
                    return Ok(());
                }
            }
        }
        // A top-level (or nested `!global`) assignment to a name not in the
        // global scope but exposed by exactly one `@use … as *` module updates
        // that module's variable (so the module's own functions/mixins observe
        // the change).
        if (self.scopes.len() == 1 || v.is_global) && !is_private_member(&v.name) {
            if let Some(g) = self.scopes.first() {
                if !g.borrow().contains_key(&v.name) {
                    let targets: Vec<Rc<Module>> = self
                        .star_user_modules
                        .iter()
                        .filter(|m| m.var(&v.name).is_some())
                        .cloned()
                        .collect();
                    if targets.len() == 1 {
                        if v.is_default {
                            if let Some(existing) = targets[0].var(&v.name) {
                                if !matches!(existing, Value::Null) {
                                    return Ok(());
                                }
                            }
                        }
                        targets[0].vars.borrow_mut().insert(v.name.clone(), val);
                        return Ok(());
                    }
                }
            }
        }
        if v.is_global {
            if let Some(g) = self.scopes.first_mut() {
                g.borrow_mut().insert(v.name.clone(), val);
            }
        } else {
            self.assign(&v.name, val);
        }
        Ok(())
    }

    /// Assign to a `@use`d module's variable (`ns.$name: value`). The variable
    /// must already exist in the module and be public; `!default` only assigns
    /// when the existing value is null; built-in modules are immutable.
    fn assign_module_var(&mut self, ns: &str, v: &VarDecl) -> Result<(), Error> {
        if is_private_member(&v.name) {
            return Err(Error::unpositioned(
                "Private members can't be accessed from outside their modules.",
            ));
        }
        let module = match self.used_user_modules.get(ns).cloned() {
            Some(m) => m,
            None => {
                if self.used_modules.contains_key(ns) {
                    return Err(Error::unpositioned("Cannot modify built-in variable."));
                }
                return Err(Error::unpositioned(format!(
                    "There is no module with the namespace \"{ns}\"."
                )));
            }
        };
        // A forwarded variable writes through to its defining module (under
        // its ORIGINAL name), so the module's own functions see the new value.
        let (target, name) = match module.var_write_origin(&v.name) {
            Some((m, o)) => (m, o),
            None => (Rc::clone(&module), v.name.clone()),
        };
        let exists = target.var(&name).is_some();
        if !exists {
            return Err(Error::unpositioned("Undefined variable."));
        }
        if v.is_default {
            if let Some(existing) = target.var(&name) {
                if !matches!(existing, Value::Null) {
                    return Ok(());
                }
            }
        }
        let val = self.eval_expr(&v.value)?.without_slash();
        target.vars.borrow_mut().insert(name, val);
        Ok(())
    }

    // ---- loop helpers ------------------------------------------------

    /// Set a variable in the innermost scope. A loop pushes its own scope, so a
    /// loop variable bound here lives in the loop's scope and is re-bound each
    /// iteration (dart-sass `setLocalVariable`).
    fn set_local(&mut self, name: &str, val: Value) {
        if let Some(sc) = self.scopes.last_mut() {
            sc.borrow_mut().insert(name.to_string(), val);
        }
    }

    /// Evaluate a `@for` bound to a [`Number`], preserving its unit (the loop
    /// variable inherits the `from` bound's unit).
    fn eval_for_number(&mut self, e: &Expr) -> Result<Number, Error> {
        match self.eval_expr(e)? {
            Value::Number(n) => Ok(n),
            other => Err(Error::unpositioned(format!(
                "{} is not a number.",
                other.type_name()
            ))),
        }
    }

    /// Resolve a `@for`'s bounds: the integer start, the integer end (the TO
    /// bound converted to the FROM bound's unit), and the loop variable's unit
    /// (taken from FROM). Errors on incompatible units or a non-integer bound,
    /// matching dart-sass.
    fn for_bounds(&mut self, from: &Expr, to: &Expr) -> Result<(i64, i64, String), Error> {
        let start = self.eval_for_number(from)?;
        let end = self.eval_for_number(to)?;
        // The loop variable takes FROM's unit; TO is converted to match. A
        // unitless side defers (no conversion); two incompatible real units err.
        let end_value = if start.is_unitless() || end.is_unitless() {
            end.value
        } else {
            match crate::value::convert_factor(end.unit(), start.unit()) {
                Some(f) => end.value * f,
                None => {
                    return Err(Error::unpositioned(format!(
                        "Expected {} to have unit {}.",
                        Value::Number(end.clone()).to_css(false),
                        start.unit(),
                    )))
                }
            }
        };
        // Both bounds must be integers (dart-sass: "<n> is not an int.").
        let to_int = |v: f64, n: Number| -> Result<i64, Error> {
            if (v - v.round()).abs() < 1e-11 {
                Ok(v.round() as i64)
            } else {
                Err(Error::unpositioned(format!(
                    "{} is not an int.",
                    Value::Number(n).to_css(false)
                )))
            }
        };
        let start_i = to_int(start.value, start.clone())?;
        let end_i = to_int(end_value, Number::with_unit(end_value, start.unit().to_string()))?;
        Ok((start_i, end_i, start.unit().to_string()))
    }

    /// The values `@each` iterates: a list yields its items, `null` yields
    /// nothing, and any other value is iterated once.
    fn eval_each_items(&mut self, e: &Expr) -> Result<Vec<Value>, Error> {
        match self.eval_expr(e)? {
            Value::List(l) => Ok(l.items),
            // `@each` over a map yields each `key value` pair as a two-element
            // space list, so `@each $k, $v in $map` destructures correctly.
            Value::Map(m) => Ok(m
                .entries
                .into_iter()
                .map(|(k, v)| {
                    Value::List(List {
                        items: vec![k, v],
                        sep: ListSep::Space,
                        bracketed: false,
                        keywords: None,
                    })
                })
                .collect()),
            Value::Null => Ok(Vec::new()),
            other => Ok(vec![other]),
        }
    }

    /// Bind `@each` variables to an item, destructuring a list across
    /// multiple variables (missing elements become `null`).
    fn bind_each(&mut self, vars: &[String], item: Value) {
        if vars.len() == 1 {
            self.set_local(&vars[0], item);
            return;
        }
        let elems: Vec<Value> = match item {
            Value::List(l) => l.items,
            other => vec![other],
        };
        for (i, v) in vars.iter().enumerate() {
            let val = elems.get(i).cloned().unwrap_or(Value::Null);
            self.set_local(v, val);
        }
    }

    // ---- callables ---------------------------------------------------

    /// Evaluate call arguments and bind them to a parameter list, returning
    /// the call frame: positional args fill params in order, then keyword
    /// args by name, then declared defaults; extra positionals collect into
    /// a `$rest...` parameter or are an error.
    /// Evaluate a call's argument list into separate positional and keyword
    /// vectors, expanding any `...` splat (a list spreads into positional
    /// args, a map into keyword args). Duplicate keyword names (after
    /// hyphen/underscore normalization) are rejected, and a positional arg
    /// after a keyword arg is an error — matching dart-sass.
    fn eval_call_args(&mut self, args: &[CallArg]) -> Result<EvaledArgs, Error> {
        // Explicit positional args are gathered first; positionals spread from
        // a `...` splat are appended after them, so `f([1, 2]..., 3)` binds
        // `3` before `1, 2` (matching dart-sass's misplaced-rest behaviour).
        let mut explicit_pos = Vec::new();
        let mut splat_pos = Vec::new();
        let mut keyword: Vec<(String, Value)> = Vec::new();
        let mut seen_named = false;
        // A splatted list's separator survives into the callee's rest arglist
        // (`foo(c d e...)` binds `$zs` as a SPACE-separated arglist).
        let mut rest_sep = ListSep::Comma;
        let push_named = |keyword: &mut Vec<(String, Value)>, name: String, v: Value| -> Result<(), Error> {
            let norm = normalize_arg_name(&name);
            if keyword.iter().any(|(n, _)| normalize_arg_name(n) == norm) {
                return Err(Error::unpositioned("Duplicate argument."));
            }
            keyword.push((name, v));
            Ok(())
        };
        for a in args {
            let v = self.eval_expr(&a.value)?;
            if a.splat {
                // A splat list spreads into positional args; a map spreads
                // into keyword args (string keys only). A single non-list/map
                // value acts as one positional arg; `null` spreads to nothing.
                match v {
                    Value::Map(m) => {
                        for (k, val) in m.entries {
                            let key = match &k {
                                Value::Str(s) => s.text.clone(),
                                other => {
                                    return Err(Error::unpositioned(format!(
                                        "{} is not a string in $args.",
                                        other.to_css(false)
                                    )))
                                }
                            };
                            push_named(&mut keyword, key, val)?;
                        }
                    }
                    Value::List(l) => {
                        if !matches!(l.sep, ListSep::Undecided) {
                            rest_sep = l.sep;
                        }
                        splat_pos.extend(l.items);
                        // An argument-list splat (`$args...`) also forwards its
                        // captured keyword arguments as named arguments.
                        if let Some(kw) = l.keywords {
                            for (k, val) in kw {
                                if let Value::Str(s) = k {
                                    push_named(&mut keyword, s.text, val)?;
                                }
                            }
                        }
                    }
                    Value::Null => {}
                    other => splat_pos.push(other),
                }
                continue;
            }
            match &a.name {
                Some(n) => {
                    push_named(&mut keyword, n.clone(), v)?;
                    seen_named = true;
                }
                None => {
                    // A plain positional arg may not follow a keyword arg.
                    if seen_named {
                        return Err(Error::unpositioned(
                            "Positional arguments must come before keyword arguments.",
                        ));
                    }
                    explicit_pos.push(v);
                }
            }
        }
        explicit_pos.extend(splat_pos);
        Ok((explicit_pos, keyword, rest_sep))
    }

    fn bind_args(
        &mut self,
        params: &ParamList,
        args: &[CallArg],
        name: &str,
    ) -> Result<HashMap<String, Value>, Error> {
        let evaled = self.eval_call_args(args)?;
        self.bind_evaled(params, evaled, name)
    }

    /// Bind evaluated arguments into the CURRENT (freshly pushed) scope.
    /// Parameter defaults evaluate inside the callee environment with the
    /// already-bound parameters visible (`@mixin m($a, $b: $a)`), matching
    /// dart's progressive binding.
    fn bind_evaled_into_scope(
        &mut self,
        params: &ParamList,
        evaled: EvaledArgs,
        name: &str,
    ) -> Result<(), Error> {
        let (positional, keyword_vec, rest_sep) = evaled;
        let mut keyword: HashMap<String, Value> = HashMap::default();
        let mut keyword_order: Vec<(String, String)> = Vec::new();
        for (n, v) in keyword_vec {
            let norm = normalize_arg_name(&n);
            if !keyword.contains_key(&norm) {
                keyword_order.push((norm.clone(), n));
            }
            keyword.insert(norm, v);
        }
        let mut pos_iter = positional.into_iter();
        for param in &params.params {
            let val = if let Some(v) = pos_iter.next() {
                v
            } else if let Some(v) = keyword.remove(&normalize_arg_name(&param.name)) {
                v
            } else if let Some(def) = &param.default {
                self.eval_expr(def)?
            } else {
                return Err(Error::unpositioned(format!("Missing argument ${}.", param.name)));
            };
            if let Some(sc) = self.scopes.last() {
                sc.borrow_mut().insert(param.name.clone(), val);
            }
        }
        if let Some(rest) = &params.rest {
            let remaining: Vec<Value> = pos_iter.collect();
            let kw: Vec<(Value, Value)> = keyword_order
                .iter()
                .filter_map(|(norm, _)| {
                    keyword.remove(norm).map(|v| {
                        (
                            Value::Str(SassStr {
                                text: norm.clone(),
                                quoted: false,
                            }),
                            v,
                        )
                    })
                })
                .collect();
            if let Some(sc) = self.scopes.last() {
                sc.borrow_mut().insert(
                    rest.clone(),
                    Value::List(List {
                        items: remaining,
                        sep: rest_sep,
                        bracketed: false,
                        keywords: Some(kw),
                    }),
                );
            }
        } else if pos_iter.next().is_some() {
            return Err(Error::unpositioned(format!(
                "{name} was passed too many arguments."
            )));
        }
        if params.rest.is_none() && !keyword.is_empty() {
            let leftover: Vec<&str> = keyword_order
                .iter()
                .filter(|(norm, _)| keyword.contains_key(norm))
                .map(|(_, orig)| orig.as_str())
                .collect();
            if let Some((last, init)) = leftover.split_last() {
                let msg = if init.is_empty() {
                    format!("No parameter named ${last}.")
                } else {
                    let head = init
                        .iter()
                        .map(|n| format!("${n}"))
                        .collect::<Vec<_>>()
                        .join(", ");
                    format!("No parameters named {head} or ${last}.")
                };
                return Err(Error::unpositioned(msg));
            }
        }
        Ok(())
    }

    /// Bind already-evaluated `(positional, keyword)` arguments into a call
    /// frame. Used by `meta.call`, which has only evaluated values to pass on.
    fn bind_evaled(
        &mut self,
        params: &ParamList,
        evaled: EvaledArgs,
        name: &str,
    ) -> Result<HashMap<String, Value>, Error> {
        let (positional, keyword_vec, rest_sep) = evaled;
        let mut keyword: HashMap<String, Value> = HashMap::default();
        // Track the order and source spelling of keyword names so an
        // "unknown parameter" error can list them as the caller wrote them.
        let mut keyword_order: Vec<(String, String)> = Vec::new();
        for (n, v) in keyword_vec {
            let norm = normalize_arg_name(&n);
            if !keyword.contains_key(&norm) {
                keyword_order.push((norm.clone(), n));
            }
            keyword.insert(norm, v);
        }
        let mut frame = HashMap::default();
        let mut pos_iter = positional.into_iter();
        for param in &params.params {
            let val = if let Some(v) = pos_iter.next() {
                v
            } else if let Some(v) = keyword.remove(&normalize_arg_name(&param.name)) {
                v
            } else if let Some(def) = &param.default {
                self.eval_expr(def)?
            } else {
                return Err(Error::unpositioned(format!("Missing argument ${}.", param.name)));
            };
            frame.insert(param.name.clone(), val);
        }
        if let Some(rest) = &params.rest {
            let remaining: Vec<Value> = pos_iter.collect();
            // Any keyword args left after binding the declared params become the
            // arglist's keywords, in caller order and keyed by their
            // hyphen-normalized name (what `meta.keywords` reports).
            let kw: Vec<(Value, Value)> = keyword_order
                .iter()
                .filter_map(|(norm, _)| {
                    keyword.remove(norm).map(|v| {
                        (
                            Value::Str(SassStr {
                                text: norm.clone(),
                                quoted: false,
                            }),
                            v,
                        )
                    })
                })
                .collect();
            frame.insert(
                rest.clone(),
                Value::List(List {
                    items: remaining,
                    sep: rest_sep,
                    bracketed: false,
                    keywords: Some(kw),
                }),
            );
        } else if pos_iter.next().is_some() {
            return Err(Error::unpositioned(format!(
                "{name} was passed too many arguments."
            )));
        }
        // Reject keyword arguments that name no declared parameter. A `...`
        // rest parameter would absorb them into an arglist (whose keywords
        // are not yet modelled), so only validate when there is no rest.
        if params.rest.is_none() && !keyword.is_empty() {
            let leftover: Vec<&str> = keyword_order
                .iter()
                .filter(|(norm, _)| keyword.contains_key(norm))
                .map(|(_, orig)| orig.as_str())
                .collect();
            if let Some((last, init)) = leftover.split_last() {
                let msg = if init.is_empty() {
                    format!("No parameter named ${last}.")
                } else {
                    let head = init
                        .iter()
                        .map(|n| format!("${n}"))
                        .collect::<Vec<_>>()
                        .join(", ");
                    format!("No parameters named {head} or ${last}.")
                };
                return Err(Error::unpositioned(msg));
            }
        }
        Ok(frame)
    }

    /// Call a user-defined `@function`, returning its `@return` value. `call`,
    /// when present, is the (name-start position, byte length) of the call
    /// expression, recorded as a diagnostic stack frame around the body.
    fn call_function(
        &mut self,
        func: &Rc<UserCallable>,
        args: &[CallArg],
        call: Option<(Pos, usize)>,
    ) -> Result<Value, Error> {
        // Arguments evaluate in the CALLER's environment; the body (and the
        // parameter defaults) run against the callable's LEXICAL closure.
        let evaled = self.eval_call_args(args)?;
        let saved = call.map(|(pos, len)| self.enter_call(pos, len, &format!("{}()", func.def.name)));
        let saved_scopes = std::mem::replace(&mut self.scopes, func.env.clone());
        let saved_semi = std::mem::replace(&mut self.scope_semi_global, func.env_semi.clone());
        let saved_fns = std::mem::replace(&mut self.functions, func.env_fns.clone());
        let saved_mixins = std::mem::replace(&mut self.mixins, func.env_mixins.clone());
        self.push_scope(false);
        let result = self
            .bind_evaled_into_scope(&func.def.params, evaled, &func.def.name)
            .and_then(|()| {
                // A function body is not a mixin body: `meta.content-exists()`
                // called from a function (even one invoked by a mixin) errors.
                self.in_mixin.push(false);
                let r = self.run_fn_body(&func.def.body);
                self.in_mixin.pop();
                r
            });
        self.pop_scope();
        self.scopes = saved_scopes;
        self.scope_semi_global = saved_semi;
        self.functions = saved_fns;
        self.mixins = saved_mixins;
        if let Some(saved) = saved {
            self.leave_call(saved);
        }
        match result? {
            // A bare slash-division returned from a function collapses to
            // its number (dart-sass `withoutSlash`); slashes nested in a
            // returned list are preserved.
            Some(v) => Ok(v.without_slash()),
            None => Err(Error::unpositioned(format!(
                "Function {}() did not @return a value.",
                func.def.name
            ))),
        }
    }

    /// Run a function body, propagating the first `@return` (including from
    /// nested control flow). Functions emit no CSS, so a returned value
    /// short-circuits the whole call.
    fn run_fn_body(&mut self, stmts: &[Stmt]) -> Result<Option<Value>, Error> {
        for stmt in stmts {
            match stmt {
                Stmt::VarDecl(v) => self.apply_var(v)?,
                Stmt::Comment(..) => {}
                Stmt::Return(e) => return Ok(Some(self.eval_expr(e)?)),
                Stmt::FunctionDef(c) => {
                    let captured = self.capture_callable(c);
                    self.define_function(&c.name, captured);
                }
                Stmt::If(branches) => {
                    for branch in branches {
                        let take = match &branch.cond {
                            None => true,
                            Some(c) => self.eval_expr(c)?.is_truthy(),
                        };
                        if take {
                            self.push_scope(true);
                            let result = self.run_fn_body(&branch.body);
                            self.pop_scope();
                            if let Some(v) = result? {
                                return Ok(Some(v));
                            }
                            break;
                        }
                    }
                }
                Stmt::For {
                    var,
                    from,
                    to,
                    inclusive,
                    body,
                } => {
                    let (start_i, end_i, unit) = self.for_bounds(from, to)?;
                    self.push_scope(true);
                    let mut result = Ok(None);
                    for i in for_indices(start_i, end_i, *inclusive) {
                        self.set_local(var, Value::Number(Number::with_unit(i as f64, unit.clone())));
                        result = self.run_fn_body(body);
                        if matches!(result, Ok(None)) {
                            continue;
                        }
                        break;
                    }
                    self.pop_scope();
                    if let Some(v) = result? {
                        return Ok(Some(v));
                    }
                }
                Stmt::Each { vars, list, body } => {
                    let items = self.eval_each_items(list)?;
                    self.push_scope(true);
                    let mut result = Ok(None);
                    for item in items {
                        self.bind_each(vars, item);
                        result = self.run_fn_body(body);
                        if matches!(result, Ok(None)) {
                            continue;
                        }
                        break;
                    }
                    self.pop_scope();
                    if let Some(v) = result? {
                        return Ok(Some(v));
                    }
                }
                Stmt::While { cond, body } => {
                    self.push_scope(true);
                    let mut result: Result<Option<Value>, Error> = Ok(None);
                    let mut guard = 0u32;
                    loop {
                        match self.eval_expr(cond) {
                            Ok(v) if v.is_truthy() => {}
                            Ok(_) => break,
                            Err(e) => {
                                result = Err(e);
                                break;
                            }
                        }
                        result = self.run_fn_body(body);
                        if !matches!(result, Ok(None)) {
                            break;
                        }
                        guard += 1;
                        if guard >= 100_000 {
                            result = Err(Error::unpositioned("@while exceeded 100000 iterations"));
                            break;
                        }
                    }
                    self.pop_scope();
                    if let Some(v) = result? {
                        return Ok(Some(v));
                    }
                }
                Stmt::Warn { value, pos } => self.emit_warn(value, *pos)?,
                Stmt::Debug { value, pos } => self.emit_debug(value, *pos)?,
                Stmt::Error { value, pos, length } => {
                    return Err(self.build_error(value, *pos, *length));
                }
                _ => {
                    return Err(Error::unpositioned(
                        "only variable assignments, control flow and @return are allowed in a function.",
                    ));
                }
            }
        }
        Ok(None)
    }

    /// Execute an `@include`: bind args into a call frame, make the content
    /// block available, and run the mixin body into the current sink.
    #[allow(clippy::too_many_arguments)]
    fn exec_include(
        &mut self,
        name: &str,
        args: &[CallArg],
        content: Option<Rc<Vec<Stmt>>>,
        content_params: Option<Rc<ParamList>>,
        module: Option<&str>,
        pos: Pos,
        parents: &[String],
        sink: &mut Sink<'_>,
    ) -> Result<(), Error> {
        // NOTE: the diagnostic call frame for this `@include` is pushed by the
        // caller (the `Stmt::Include` arm) so it wraps every resolution path.
        // The built-in `@include meta.apply(...)` / `meta.load-css(...)` are
        // bound to the `sass:meta` namespace, so resolve them before the generic
        // module path.
        if let Some(ns) = module {
            if self.used_modules.get(ns).map(String::as_str) == Some("meta") {
                if name == "apply" {
                    return self.exec_apply(args, content, content_params, parents, sink);
                }
                if name == "load-css" {
                    return self.exec_load_css(args, content, pos, parents, sink);
                }
            }
        }
        // A namespaced `@include ns.mixin`: resolve a user module bound to the
        // namespace, then a built-in (which exposes no mixins in this build).
        if let Some(ns) = module {
            if let Some(target) = self.used_user_modules.get(ns).cloned() {
                if is_private_member(name) {
                    return Err(Error::unpositioned(
                        "Private members can't be accessed from outside their modules.",
                    ));
                }
                let mixin = target
                    .mixin(name)
                    .ok_or_else(|| Error::unpositioned("Undefined mixin."))?;
                // A forwarded mixin runs in its DEFINING module's environment.
                let exec = target.mixin_origin(name).unwrap_or(target);
                return self.run_module_mixin(&exec, &mixin, args, content, content_params, parents, sink);
            }
            if !self.used_modules.contains_key(ns) {
                return Err(Error::unpositioned(format!(
                    "There is no module with the namespace \"{ns}\"."
                )));
            }
            return Err(Error::unpositioned("Undefined mixin."));
        }
        // A bare `@include` may resolve a user module mixin exposed unprefixed
        // via `@use … as *`.
        if self.lookup_mixin(name).is_none() && !self.star_user_modules.is_empty() && !is_private_member(name)
        {
            let hits: Vec<(Rc<Module>, Rc<UserCallable>)> = self
                .star_user_modules
                .iter()
                .filter_map(|m| m.mixin(name).map(|mx| (Rc::clone(m), mx)))
                .collect();
            if hits.len() > 1 {
                return Err(Error::unpositioned(
                    "This mixin is available from multiple global modules.",
                ));
            }
            if let Some((m, mx)) = hits.into_iter().next() {
                return self.run_module_mixin(&m, &mx, args, content, content_params, parents, sink);
            }
        }
        let mixin = self
            .lookup_mixin(name)
            .ok_or_else(|| Error::unpositioned(format!("Undefined mixin {name}.")))?;
        // dart-sass: passing a content block to a mixin that never uses
        // `@content` is an error, even when the block is empty.
        if content.is_some() && !body_uses_content(&mixin.def.body) {
            return Err(Error::unpositioned("Mixin doesn't accept a content block."));
        }
        // Arguments evaluate in the caller's environment; the body runs in
        // the mixin's lexical closure. The content block captures the CALL
        // SITE so `@content` sees the includer's variables.
        let evaled = self.eval_call_args(args)?;
        let content_block = content.map(|stmts| {
            let snapshot = self.snapshot_env();
            ContentBlock {
                stmts,
                params: content_params.clone(),
                caller_env: Some(Box::new(snapshot)),
            }
        });
        let saved_scopes = std::mem::replace(&mut self.scopes, mixin.env.clone());
        let saved_semi = std::mem::replace(&mut self.scope_semi_global, mixin.env_semi.clone());
        let saved_fns = std::mem::replace(&mut self.functions, mixin.env_fns.clone());
        let saved_mixins = std::mem::replace(&mut self.mixins, mixin.env_mixins.clone());
        self.push_scope(false);
        let result = self
            .bind_evaled_into_scope(&mixin.def.params, evaled, &mixin.def.name)
            .and_then(|()| {
                self.content_stack.push(content_block);
                self.in_mixin.push(true);
                let r = self.exec(&mixin.def.body, parents, sink);
                self.in_mixin.pop();
                self.content_stack.pop();
                r
            });
        self.pop_scope();
        self.scopes = saved_scopes;
        self.scope_semi_global = saved_semi;
        self.functions = saved_fns;
        self.mixins = saved_mixins;
        result
    }

    /// Execute an `@include ns.mixin` where `ns` is a user module: run the mixin
    /// body in the module's own environment, while its `@content` block (if any)
    /// runs back in the call site's environment.
    #[allow(clippy::too_many_arguments)]
    fn run_module_mixin(
        &mut self,
        module: &Rc<Module>,
        mixin: &Rc<UserCallable>,
        args: &[CallArg],
        content: Option<Rc<Vec<Stmt>>>,
        content_params: Option<Rc<ParamList>>,
        parents: &[String],
        sink: &mut Sink<'_>,
    ) -> Result<(), Error> {
        if content.is_some() && !body_uses_content(&mixin.def.body) {
            return Err(Error::unpositioned("Mixin doesn't accept a content block."));
        }
        // Evaluate the arguments at the call site (so they resolve in the
        // caller's scope), then enter the module's environment and the
        // mixin's lexical closure for the body. Snapshot the call-site env
        // so a `@content` block runs there, not in the module.
        let evaled = self.eval_call_args(args)?;
        let content_block = content.map(|stmts| {
            let snapshot = self.snapshot_env();
            ContentBlock {
                stmts,
                params: content_params.clone(),
                caller_env: Some(Box::new(snapshot)),
            }
        });
        let saved = self.enter_module(module);
        let saved_file = self.enter_module_file(module);
        let saved_scopes = std::mem::replace(&mut self.scopes, mixin.env.clone());
        let saved_semi = std::mem::replace(&mut self.scope_semi_global, mixin.env_semi.clone());
        let saved_fns = std::mem::replace(&mut self.functions, mixin.env_fns.clone());
        let saved_mixins = std::mem::replace(&mut self.mixins, mixin.env_mixins.clone());
        self.push_scope(false);
        let result = self
            .bind_evaled_into_scope(&mixin.def.params, evaled, &mixin.def.name)
            .and_then(|()| {
                self.content_stack.push(content_block);
                let r = self.exec(&mixin.def.body, parents, sink);
                self.content_stack.pop();
                r
            });
        self.pop_scope();
        self.scopes = saved_scopes;
        self.scope_semi_global = saved_semi;
        self.functions = saved_fns;
        self.mixins = saved_mixins;
        self.leave_module_file(saved_file);
        self.leave_module(saved);
        result
    }

    /// `@include meta.apply($mixin, $args...)`: invoke a first-class mixin
    /// reference. The first argument is the mixin reference; the rest are the
    /// arguments passed on to that mixin (which may also accept a `@content`
    /// block).
    fn exec_apply(
        &mut self,
        args: &[CallArg],
        content: Option<Rc<Vec<Stmt>>>,
        content_params: Option<Rc<ParamList>>,
        parents: &[String],
        sink: &mut Sink<'_>,
    ) -> Result<(), Error> {
        // Evaluate apply's own arguments (expanding any `...` splat). The first
        // positional (or named `$mixin`) is the mixin reference; the remainder
        // are forwarded to the mixin.
        let (mut pos_args, mut named, _) = self.eval_call_args(args)?;
        for v in &mut pos_args {
            *v = std::mem::replace(v, Value::Null).without_slash();
        }
        for (_, v) in &mut named {
            *v = std::mem::replace(v, Value::Null).without_slash();
        }
        let (mixin_val, rest_pos): (Value, Vec<Value>) = if !pos_args.is_empty() {
            let mut iter = pos_args.into_iter();
            let first = iter.next().unwrap_or(Value::Null);
            (first, iter.collect())
        } else if let Some(idx) = named.iter().position(|(n, _)| n == "mixin") {
            (named.remove(idx).1, Vec::new())
        } else {
            return Err(Error::unpositioned("Missing argument $mixin."));
        };
        let rest_named: Vec<(String, Value)> = named.into_iter().filter(|(n, _)| n != "mixin").collect();
        let mixin = match mixin_val {
            Value::Mixin(m) => m,
            other => {
                return Err(Error::unpositioned(format!(
                    "$mixin: {} is not a mixin reference.",
                    other.to_css(false)
                )))
            }
        };
        self.invoke_mixin_ref(
            &mixin,
            rest_pos,
            rest_named,
            content,
            content_params,
            parents,
            sink,
        )
    }

    /// `@include meta.load-css($url, $with: (...))`: load the module at `$url`
    /// and emit its CSS into the current sink, optionally configuring it with
    /// `$with`. Unlike `@use`, it binds no namespace and exposes no members; it
    /// reuses the shared `load_module` machinery (cache, cycle guard, CSS emit).
    fn exec_load_css(
        &mut self,
        args: &[CallArg],
        content: Option<Rc<Vec<Stmt>>>,
        pos: Pos,
        parents: &[String],
        sink: &mut Sink<'_>,
    ) -> Result<(), Error> {
        if content.is_some() {
            return Err(Error::at(
                "Mixin doesn't accept a content block.".to_string(),
                pos,
            ));
        }
        let (pos_args, named, _) = self.eval_call_args(args)?;
        let mut iter = pos_args.into_iter();
        let mut url_val = iter.next();
        let mut with_val = iter.next();
        if iter.next().is_some() {
            return Err(Error::at(
                "Only 2 arguments allowed, but 3 were passed.".to_string(),
                pos,
            ));
        }
        for (n, v) in named {
            match n.as_str() {
                "url" => url_val = Some(v),
                "with" => with_val = Some(v),
                other => return Err(Error::at(format!("No argument named ${other}."), pos)),
            }
        }
        let url = match url_val {
            Some(Value::Str(s)) => s.text,
            Some(other) => {
                return Err(Error::at(
                    format!("$url: {} is not a string.", other.to_css(false)),
                    pos,
                ))
            }
            None => return Err(Error::at("Missing argument $url.".to_string(), pos)),
        };
        // Build the configuration from the `$with` map (string keys → variables).
        let mut config: HashMap<String, (Value, bool)> = HashMap::default();
        match with_val.take() {
            None => {}
            // An empty literal `()` parses as an empty list, not a map.
            Some(Value::List(l)) if l.items.is_empty() => {}
            Some(Value::Map(m)) => {
                for (k, v) in m.entries {
                    let key = match k {
                        Value::Str(s) => normalize_var_name(&s.text),
                        other => {
                            return Err(Error::at(
                                format!("$with key: {} is not a string.", other.to_css(false)),
                                pos,
                            ))
                        }
                    };
                    // Dash/underscore-insensitive: `a-b` and `a_b` collide.
                    if config.contains_key(&key) {
                        return Err(Error::at(
                            format!("The variable ${key} was configured twice."),
                            pos,
                        ));
                    }
                    config.insert(key, (v.without_slash(), false));
                }
            }
            Some(other) => {
                return Err(Error::at(
                    format!("$with: {} is not a map.", other.to_css(false)),
                    pos,
                ))
            }
        }
        // A built-in `sass:*` module emits no CSS (and can't be configured).
        if let Some(m) = url.strip_prefix("sass:") {
            if crate::builtins::is_module(m) {
                if !config.is_empty() {
                    return Err(Error::at(
                        format!("Built-in module sass:{m} can't be configured."),
                        pos,
                    ));
                }
                return Ok(());
            }
            return Err(Error::at("Can't find stylesheet to import.".to_string(), pos));
        }
        let conf_keys: Vec<String> = config.keys().cloned().collect();
        // Evaluate the module into a fresh TOP-LEVEL buffer so its body runs in
        // its own top-level context — a module top-level declaration errors no
        // matter where load-css is invoked (dart-sass) — then splice the emitted
        // nodes into the caller's position.
        let mut buf: Vec<OutNode> = Vec::new();
        let consumed = {
            let mut module_sink = Sink::Top(&mut buf);
            let config_id = if config.is_empty() {
                0
            } else {
                self.fresh_config_id()
            };
            let (_module, consumed) =
                self.load_module(&url, config, config_id, pos, parents, true, &mut module_sink)?;
            consumed
        };
        if conf_keys.iter().any(|k| !consumed.contains(k)) {
            return Err(Error::at(
                "This variable was not declared with !default in the @used module.".to_string(),
                pos,
            ));
        }
        splice_nodes(sink, buf);
        Ok(())
    }

    /// Invoke a resolved mixin reference with already-evaluated arguments and an
    /// optional `@content` block, emitting into `sink`.
    #[allow(clippy::too_many_arguments)]
    fn invoke_mixin_ref(
        &mut self,
        mixin: &SassMixin,
        pos_args: Vec<Value>,
        named: Vec<(String, Value)>,
        content: Option<Rc<Vec<Stmt>>>,
        content_params: Option<Rc<ParamList>>,
        parents: &[String],
        sink: &mut Sink<'_>,
    ) -> Result<(), Error> {
        // A captured user `@mixin`: recover the type-erased `Callable`.
        let callable = match &mixin.user {
            Some(any) => match Rc::clone(any).downcast::<UserCallable>() {
                Ok(c) => c,
                Err(_) => return Err(Error::unpositioned("Undefined mixin.")),
            },
            // A built-in mixin reference (`meta.load-css`/`meta.apply`). Only the
            // content-block validation is observable in the supported cases.
            None => {
                if content.is_some() {
                    return Err(Error::unpositioned("Mixin doesn't accept a content block."));
                }
                return Err(Error::unpositioned("Undefined mixin."));
            }
        };
        if content.is_some() && !body_uses_content(&callable.def.body) {
            return Err(Error::unpositioned("Mixin doesn't accept a content block."));
        }
        let content_block = content.map(|stmts| {
            let snapshot = self.snapshot_env();
            ContentBlock {
                stmts,
                params: content_params.clone(),
                caller_env: Some(Box::new(snapshot)),
            }
        });
        // A mixin captured from another module runs in that module's
        // environment; either way the body runs in its lexical closure and
        // the `@content` block runs back at the call site.
        let module = mixin
            .module
            .as_ref()
            .and_then(|m| Rc::clone(m).downcast::<Module>().ok());
        let saved = module.as_ref().map(|m| self.enter_module(m));
        let saved_scopes = std::mem::replace(&mut self.scopes, callable.env.clone());
        let saved_semi = std::mem::replace(&mut self.scope_semi_global, callable.env_semi.clone());
        let saved_fns = std::mem::replace(&mut self.functions, callable.env_fns.clone());
        let saved_mixins = std::mem::replace(&mut self.mixins, callable.env_mixins.clone());
        self.push_scope(false);
        let result = self
            .bind_evaled_into_scope(
                &callable.def.params,
                (pos_args, named, ListSep::Comma),
                &callable.def.name,
            )
            .and_then(|()| {
                self.content_stack.push(content_block);
                self.in_mixin.push(true);
                let r = self.exec(&callable.def.body, parents, sink);
                self.in_mixin.pop();
                self.content_stack.pop();
                r
            });
        self.pop_scope();
        self.scopes = saved_scopes;
        self.scope_semi_global = saved_semi;
        self.functions = saved_fns;
        self.mixins = saved_mixins;
        if let Some(saved) = saved {
            self.leave_module(saved);
        }
        result
    }

    /// Run the innermost active `@content` block. For a cross-module include the
    /// block carries a snapshot of the call-site environment, which is installed
    /// for the duration so the content resolves there rather than in the mixin's
    /// module.
    fn exec_content(
        &mut self,
        args: &[CallArg],
        parents: &[String],
        sink: &mut Sink<'_>,
    ) -> Result<(), Error> {
        let (stmts, params, caller_env) = match self.content_stack.last() {
            Some(Some(block)) => (
                Rc::clone(&block.stmts),
                block.params.clone(),
                block.caller_env.as_ref().map(|e| (**e).clone()),
            ),
            _ => return Ok(()),
        };
        // `@content(args)` evaluates its arguments at the call site (the mixin
        // body), then binds them to the content block's `using (params)`, which
        // become visible inside the block.
        let frame = match &params {
            Some(p) => Some(self.bind_args(p, args, "@content")?),
            None => {
                // A content block with no `using (params)` accepts no
                // arguments; passing any is an error (dart-sass).
                if !args.is_empty() {
                    let n = args.len();
                    let verb = if n == 1 { "was" } else { "were" };
                    return Err(Error::unpositioned(format!(
                        "Only 0 arguments allowed, but {n} {verb} passed."
                    )));
                }
                None
            }
        };
        let restore = caller_env.map(|env| self.install_env(env));
        // A content block is a user-defined callable in dart: its body always
        // runs in a fresh child scope, so a `$var:` first declared inside it
        // stays local to the block (and a `using` frame binds there).
        match frame {
            Some(frame) => self.push_scope_frame(frame),
            None => self.push_scope(false),
        }
        // The block runs in its DEFINITION environment's content context: a
        // `@content` inside it forwards to the block one level up, not to
        // itself (a recursive mixin chaining `@content` must terminate).
        let running = self.content_stack.pop();
        let result = self.exec(&stmts, parents, sink);
        if let Some(top) = running {
            self.content_stack.push(top);
        }
        self.pop_scope();
        if let Some(restore) = restore {
            self.leave_module(restore);
        }
        result
    }

    /// Install a saved environment snapshot, returning the displaced one to
    /// restore afterwards.
    fn install_env(&mut self, env: SavedModuleEnv) -> SavedModuleEnv {
        SavedModuleEnv {
            scopes: std::mem::replace(&mut self.scopes, env.scopes),
            scope_semi_global: std::mem::replace(&mut self.scope_semi_global, env.scope_semi_global),
            functions: std::mem::replace(&mut self.functions, env.functions),
            mixins: std::mem::replace(&mut self.mixins, env.mixins),
            used_modules: std::mem::replace(&mut self.used_modules, env.used_modules),
            star_modules: std::mem::replace(&mut self.star_modules, env.star_modules),
            used_user_modules: std::mem::replace(&mut self.used_user_modules, env.used_user_modules),
            star_user_modules: std::mem::replace(&mut self.star_user_modules, env.star_user_modules),
            write_back: None,
        }
    }

    /// Clone the current per-module environment (for capturing a content block's
    /// call-site closure).
    fn snapshot_env(&self) -> SavedModuleEnv {
        SavedModuleEnv {
            scopes: self.scopes.clone(),
            scope_semi_global: self.scope_semi_global.clone(),
            functions: self.functions.clone(),
            mixins: self.mixins.clone(),
            used_modules: self.used_modules.clone(),
            star_modules: self.star_modules.clone(),
            used_user_modules: self.used_user_modules.clone(),
            star_user_modules: self.star_user_modules.clone(),
            write_back: None,
        }
    }

    /// Process a `@use "<url>" [as ns|as *] [with (...)];` for a built-in
    /// `sass:*` module or a user stylesheet.
    #[allow(clippy::too_many_arguments)]
    fn exec_use(
        &mut self,
        url: &str,
        namespace: Option<&str>,
        star: bool,
        config: &[crate::ast::ConfigEntry],
        pos: Pos,
        parents: &[String],
        sink: &mut Sink<'_>,
    ) -> Result<(), Error> {
        // Built-in `sass:<mod>` modules.
        if let Some(m) = url.strip_prefix("sass:") {
            if !crate::builtins::is_module(m) {
                return Err(Error::at("Can't find stylesheet to import.".to_string(), pos));
            }
            if !config.is_empty() {
                return Err(Error::at(
                    "Built-in modules can't be configured.".to_string(),
                    pos,
                ));
            }
            let module = m.to_string();
            if star {
                if !self.star_modules.contains(&module) {
                    self.star_modules.push(module);
                }
                return Ok(());
            }
            let ns = namespace.unwrap_or(&module).to_string();
            self.check_namespace_free(&ns, pos)?;
            self.used_modules.insert(ns, module);
            return Ok(());
        }

        // A user stylesheet module.
        let conf = self.eval_config(config)?;
        let conf_keys: Vec<String> = conf.keys().cloned().collect();
        let config_id = if conf.is_empty() {
            0
        } else {
            self.fresh_config_id()
        };
        // `parents` is only non-empty when this `@use` sits at the top of a
        // sheet imported INSIDE a style rule: the module still evaluates in a
        // clean context, but its emitted CSS joins the importing rule's
        // selectors (dart nests the whole import subtree's CSS —
        // nested_import_into_use).
        let (module, consumed) = self.load_module(url, conf, config_id, pos, parents, false, sink)?;
        // Any configured variable the module did not consume via a `!default`
        // declaration is an error.
        if conf_keys.iter().any(|k| !consumed.contains(k)) {
            return Err(Error::at(
                "This variable was not declared with !default in the @used module.".to_string(),
                pos,
            ));
        }
        if star {
            // A member the new global module exposes that the current sheet
            // already defines at the top level is a conflict.
            if let Some(g) = self.scopes.first() {
                for name in module.vars.borrow().keys() {
                    if !is_private_member(name) && g.borrow().contains_key(name) {
                        return Err(Error::at(
                            format!(
                                "This module and the new module both define a variable named \"${name}\"."
                            ),
                            pos,
                        ));
                    }
                }
            }
            // `@use`ing the same module twice as `*` is idempotent (no
            // ambiguity), so de-duplicate by module identity.
            let ptr = Rc::as_ptr(&module);
            if !self.star_user_modules.iter().any(|m| Rc::as_ptr(m) == ptr) {
                self.star_user_modules.push(module);
            }
            return Ok(());
        }
        let ns = match namespace {
            Some(n) => n.to_string(),
            None => default_namespace(url, pos)?,
        };
        self.check_namespace_free(&ns, pos)?;
        self.used_user_modules.insert(ns, module);
        Ok(())
    }

    /// Reject a namespace already bound by another `@use` in the same sheet.
    fn check_namespace_free(&self, ns: &str, pos: Pos) -> Result<(), Error> {
        if self.used_modules.contains_key(ns) || self.used_user_modules.contains_key(ns) {
            return Err(Error::at(
                format!("There's already a module with namespace \"{ns}\"."),
                pos,
            ));
        }
        Ok(())
    }

    /// Evaluate a `with (...)` configuration clause into a name -> (value,
    /// is_default) map.
    fn eval_config(
        &mut self,
        config: &[crate::ast::ConfigEntry],
    ) -> Result<HashMap<String, (Value, bool)>, Error> {
        let mut map = HashMap::default();
        for entry in config {
            let v = self.eval_expr(&entry.value)?.without_slash();
            // Variable names are dash/underscore-insensitive: store the
            // canonical (dashed) form so `$a_b` and `$a-b` configure the same
            // variable. A duplicate key is an error.
            let key = normalize_var_name(&entry.name);
            if map.contains_key(&key) {
                return Err(Error::unpositioned(format!(
                    "The variable ${} was configured twice.",
                    entry.name
                )));
            }
            map.insert(key, (v, entry.is_default));
        }
        Ok(map)
    }

    /// Load (and cache) a user module: resolve its URL, evaluate it once into an
    /// isolated environment with `config` applied to its `!default` variables,
    /// emit its CSS into `sink`, and return the shared module instance plus the
    /// list of config keys the module consumed (for `@forward ... with`
    /// pass-through).
    /// Collect a module's full subtree CSS (dependencies upstream-first,
    /// each module once), un-wrapping embedded module-scope nodes — used for
    /// `meta.load-css`, which re-emits the whole subtree at the call site
    /// (dart `_combineCss` with `clone: true`).
    /// A fresh explicit-configuration identity.
    fn fresh_config_id(&self) -> usize {
        let n = self.config_id_counter.get() + 1;
        self.config_id_counter.set(n);
        n
    }

    fn subtree_css(&self, key: &str) -> Vec<OutNode> {
        let mut out = Vec::new();
        let mut visited = std::collections::HashSet::new();
        self.walk_subtree(key, &mut visited, &mut out);
        trim_leading_blanks(&mut out);
        out
    }

    fn walk_subtree(
        &self,
        key: &str,
        visited: &mut std::collections::HashSet<String>,
        out: &mut Vec<OutNode>,
    ) {
        if !visited.insert(key.to_string()) {
            return;
        }
        let deps = self
            .module_dep_order
            .borrow()
            .get(key)
            .cloned()
            .unwrap_or_default();
        for d in deps {
            self.walk_subtree(&d, visited, out);
        }
        if let Some(m) = self.module_cache.borrow().get(key) {
            for n in &m.css {
                // An embedded dependency's scope wrapper is covered by the
                // dependency walk above; a materialized clone (no load edge)
                // stays.
                if let OutNode::ModuleScope { key: k, .. } = n {
                    if !k.contains("#copy") && !k.contains("#import") {
                        continue;
                    }
                }
                out.push(n.clone());
            }
        }
    }

    /// Register a unique `meta.load-css` copy scope for `key` at the current
    /// call site: the caller gains a load edge to the copy (its extensions
    /// apply to it), and origins inside the base's subtree are linked during
    /// `apply_extends`.
    fn register_load_css_copy(&self, key: &str) -> String {
        let n = self.copy_counter.get() + 1;
        self.copy_counter.set(n);
        let copy_key = format!("{key}#copy{n}");
        self.module_deps
            .borrow_mut()
            .entry(self.current_module.clone())
            .or_default()
            .insert(copy_key.clone());
        self.load_css_copies
            .borrow_mut()
            .push((copy_key.clone(), key.to_string()));
        copy_key
    }

    /// The copy scope and subtree CSS for one forced re-emit. Inside a
    /// module-loading `@import`, all loads share the import's single copy key
    /// and visited set (a diamond's shared upstream emits once per import);
    /// a `meta.load-css` call gets its own key and a fresh walk.
    fn clone_module_css(&mut self, key: &str) -> (String, Vec<OutNode>) {
        let state = self.import_clone.take();
        if let Some((k, mut visited)) = state {
            let copy_key = k.clone();
            self.module_deps
                .borrow_mut()
                .entry(self.current_module.clone())
                .or_default()
                .insert(copy_key.clone());
            self.load_css_copies
                .borrow_mut()
                .push((copy_key.clone(), key.to_string()));
            let mut out = Vec::new();
            self.walk_subtree(key, &mut visited, &mut out);
            trim_leading_blanks(&mut out);
            self.import_clone = Some((k, visited));
            (copy_key, out)
        } else {
            let copy_key = self.register_load_css_copy(key);
            (copy_key, self.subtree_css(key))
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn load_module(
        &mut self,
        url: &str,
        config: HashMap<String, (Value, bool)>,
        config_id: usize,
        pos: Pos,
        parents: &[String],
        force_reemit: bool,
        sink: &mut Sink<'_>,
    ) -> Result<(Rc<Module>, Vec<String>), Error> {
        // Inside a module-loading `@import`, every load re-emits as a clone.
        let force_reemit = force_reemit || self.import_clone.is_some();
        let importer = self.options.importer;
        // The caller's importer runs OUTSIDE the arena scope: anything it
        // allocates (e.g. a cache of paths it owns) must survive past this
        // compile's arena reset, so route its allocations to the system
        // allocator. The returned `String`s are then deep-copied into the arena
        // below by the parse/eval pipeline.
        let saved = crate::arena::pause();
        let base = self.current_file_dir.clone();
        let resolved = importer.and_then(|imp| imp.resolve_module_with_syntax_in(url, base.as_deref()));
        crate::arena::resume(saved);
        let (key, src, syntax) = match resolved {
            Some(triple) => triple,
            None => {
                return Err(Error::at("Can't find stylesheet to import.".to_string(), pos));
            }
        };
        // A module evaluated once and cached is shared; its CSS is NOT
        // re-emitted. Re-loading it with configuration is an error — unless the
        // configuration targets no variable the module actually defines (a
        // module with no configurable variables may be loaded with or without
        // config). The keys it *does* define count as consumed for the caller.
        let cached = self.module_cache.borrow().get(&key).cloned();
        if let Some(existing) = cached {
            let consumed: Vec<String> = config
                .keys()
                .filter(|k| existing.var(k).is_some())
                .cloned()
                .collect();
            if !consumed.is_empty() {
                // An *implicit* configuration (an `@import`'s visible
                // variables) silently reuses the already-evaluated module —
                // `$a: changed; @import "fwd"` keeps the first load's values
                // (dart `Configuration.implicit`) — and re-emits its CSS at
                // this import site (dart clones the module's CSS per import).
                if self.config_is_implicit {
                    self.module_deps
                        .borrow_mut()
                        .entry(self.current_module.clone())
                        .or_default()
                        .insert(key.clone());
                    {
                        let mut ord = self.module_dep_order.borrow_mut();
                        let v = ord.entry(self.current_module.clone()).or_default();
                        if !v.contains(&key) {
                            v.push(key.clone());
                        }
                    }
                    splice_nodes(
                        sink,
                        vec![OutNode::ModuleScope {
                            key: key.clone(),
                            nodes: reparent_nodes(existing.css.clone(), parents),
                        }],
                    );
                    return Ok((existing, consumed));
                }
                // A configuration distributed through several forwards keeps
                // its ORIGINAL identity: re-reaching an already-loaded module
                // with the same original silently reuses it (dart-sass
                // sameOriginal).
                if config_id != 0 && existing.config_origin.get() == config_id {
                    return Ok((existing, consumed));
                }
                return Err(Error::at(
                    "This module was already loaded, so it can't be configured using \"with\".".to_string(),
                    pos,
                ));
            }
            // The cached module consumed nothing (it defines none of the
            // configured variables); the caller's own/forwarded handling decides
            // whether the leftover configuration is an error. `meta.load-css`
            // still re-emits the cached CSS at the call site — WITHOUT a load
            // edge to the base module (the caller only gains the copy edge, so
            // a module pulled in solely through load-css never joins the main
            // tree's extension reachability).
            if !force_reemit {
                self.module_deps
                    .borrow_mut()
                    .entry(self.current_module.clone())
                    .or_default()
                    .insert(key.clone());
                let mut ord = self.module_dep_order.borrow_mut();
                let v = ord.entry(self.current_module.clone()).or_default();
                if !v.contains(&key) {
                    v.push(key.clone());
                }
            }
            if force_reemit {
                // A `meta.load-css` copy re-emits the module's whole SUBTREE
                // at the call site under a unique copy scope: the caller's
                // extensions apply to it (caller -> copy edge), the subtree's
                // own extensions apply to the clone, and other loaders'
                // extensions do not (dart `_combineCss` with `clone: true`).
                let (copy_key, nodes) = self.clone_module_css(&key);
                splice_nodes(
                    sink,
                    vec![OutNode::ModuleScope {
                        key: copy_key,
                        nodes: reparent_nodes(nodes, parents),
                    }],
                );
            } else if !existing.emitted_main.get() {
                // First loaded inside an import/load-css clone: this plain
                // load is the module's first appearance in the MAIN tree.
                existing.emitted_main.set(true);
                splice_nodes(
                    sink,
                    vec![OutNode::ModuleScope {
                        key: key.clone(),
                        nodes: reparent_nodes(existing.css.clone(), parents),
                    }],
                );
            }
            return Ok((existing, Vec::new()));
        }
        // Guard against a load cycle.
        if self.loading.iter().any(|p| p == &key) {
            return Err(Error::at(
                "Module loop: this module is already being loaded.".to_string(),
                pos,
            ));
        }
        let sheet = parse_with_syntax(&src, syntax)?;
        // Register the module's source under a diagnostic display URL so a
        // snippet/frame that points into this file renders against its text.
        let diag_url = self.module_diag_url(url, &key);
        if self.diag_enabled() {
            self.file_sources
                .borrow_mut()
                .insert(diag_url.clone(), Rc::from(src.as_str()));
        }
        let is_css = matches!(syntax, Syntax::Css);
        // A `meta.load-css` first load also records only the copy edge (see
        // the cache-hit branch above).
        if !force_reemit {
            self.module_deps
                .borrow_mut()
                .entry(self.current_module.clone())
                .or_default()
                .insert(key.clone());
            let mut ord = self.module_dep_order.borrow_mut();
            let v = ord.entry(self.current_module.clone()).or_default();
            if !v.contains(&key) {
                v.push(key.clone());
            }
        }
        // Evaluate into a buffer so the emitted CSS can be captured on the
        // module (for per-import re-emission) before splicing into the
        // caller's sink.
        let mut css_buf: Vec<OutNode> = Vec::new();
        let (mut module, consumed) = {
            let mut buf_sink = Sink::Top(&mut css_buf);
            self.eval_module(
                &key,
                &diag_url,
                &sheet,
                config,
                config_id,
                pos,
                &mut buf_sink,
                is_css,
            )?
        };
        module.css = css_buf.clone();
        let module = Rc::new(module);
        self.module_cache
            .borrow_mut()
            .insert(key.clone(), Rc::clone(&module));
        // A first load through `meta.load-css` (force_reemit) splices the
        // module's whole subtree under a unique copy scope at the call site;
        // an ordinary `@use`/`@forward` load wraps its own CSS in its module
        // scope.
        if force_reemit {
            let (copy_key, nodes) = self.clone_module_css(&key);
            splice_nodes(
                sink,
                vec![OutNode::ModuleScope {
                    key: copy_key,
                    nodes: reparent_nodes(nodes, parents),
                }],
            );
        } else {
            module.emitted_main.set(true);
            splice_nodes(
                sink,
                vec![OutNode::ModuleScope {
                    key: key.clone(),
                    nodes: reparent_nodes(css_buf, parents),
                }],
            );
        }
        Ok((module, consumed))
    }

    /// Emit a plain-CSS (`.css`) module's statements, preserving nesting (no
    /// Sass flattening), keeping `&` parent references literal, and resolving
    /// only `#{…}` interpolation. The parser has already rejected Sass-only
    /// constructs, so the remaining statements are plain CSS.
    fn exec_css(&mut self, stmts: &[Stmt], parents: &[String], sink: &mut Sink<'_>) -> Result<(), Error> {
        let saved = std::mem::replace(&mut self.in_plain_css, true);
        let result = self.exec_css_inner(stmts, parents, sink);
        self.in_plain_css = saved;
        result
    }

    fn exec_css_inner(
        &mut self,
        stmts: &[Stmt],
        parents: &[String],
        sink: &mut Sink<'_>,
    ) -> Result<(), Error> {
        // When the plain-CSS sheet is imported inside a style rule, top-level
        // rules whose selector contains a parent reference `&` keep native
        // CSS-nesting semantics: they are emitted VERBATIM as nested children
        // of one leading parent-selector shell (dart `nestWithin` with
        // `preserveParentSelectors`), while `&`-less rules get the descendant
        // join below.
        if !parents.is_empty() {
            let mut preserved: Vec<OutItem> = Vec::new();
            for stmt in stmts {
                if let Stmt::Rule(r) = stmt {
                    let own = self.css_selectors(&r.selector, true)?;
                    if own.iter().any(|s| part_has_parent_ref(s)) {
                        let inner = self.css_body(&r.body)?;
                        if !inner.is_empty() {
                            preserved.push(OutItem::NestedRule {
                                selectors: own,
                                items: inner,
                            });
                        }
                    }
                }
            }
            if !preserved.is_empty() {
                sink.push_at_rule(OutNode::Rule {
                    selectors: parents.to_vec(),
                    linebreaks: Vec::new(),
                    items: preserved,
                    lines: SrcLines::default(),
                    extend_base: usize::MAX,
                });
            }
        }
        for stmt in stmts {
            match stmt {
                Stmt::Rule(r) => {
                    // When the plain-CSS sheet is imported inside a style rule,
                    // its outermost rules nest under the Sass parent (descendant
                    // join); inner nesting stays native (dart-sass `nestWithin`
                    // with `preserveParentSelectors`). The sheet's own top level
                    // always rejects leading combinators — also when merged
                    // under a Sass parent (dart checks in the merge branch).
                    let own = self.css_selectors(&r.selector, true)?;
                    // A `&`-bearing rule was already emitted in the leading
                    // parent shell above.
                    if !parents.is_empty() && own.iter().any(|s| part_has_parent_ref(s)) {
                        continue;
                    }
                    let selectors: Vec<String> = if parents.is_empty() {
                        own
                    } else {
                        parents
                            .iter()
                            .flat_map(|p| own.iter().map(move |s| format!("{p} {s}")))
                            .collect()
                    };
                    let (items, bubbled) = self.css_rule_children(&r.body, &selectors)?;
                    // A childless rule is invisible (dart-sass skips it when
                    // serializing) — e.g. when its whole body bubbled out.
                    if !items.is_empty() {
                        sink.push_at_rule(OutNode::Rule {
                            selectors,
                            linebreaks: Vec::new(),
                            items,
                            lines: self.stamp(SrcLines {
                                file: 0,
                                start: r.brace_line,
                                end: r.end_line,
                                col: 0,
                            }),
                            extend_base: usize::MAX,
                        });
                    }
                    for node in bubbled {
                        sink.push_at_rule(node);
                    }
                }
                Stmt::Comment(c, lines) => {
                    let text = self.eval_template(c)?;
                    let lines = self.stamp(*lines);
                    sink.push_at_rule(OutNode::Comment(text, lines));
                }
                // A plain CSS file never inlines an `@import`; every entry is
                // emitted verbatim (`@import "x";` / `@import url(x);`), matching
                // dart-sass loading a `.css` stylesheet.
                Stmt::Import(args) => {
                    for arg in args {
                        let text = match arg {
                            ImportArg::Css { url, modifiers } => self.serialize_css_import(url, modifiers)?,
                            ImportArg::Sass { path, .. } => format!("\"{path}\""),
                        };
                        sink.push_at_rule(OutNode::Raw(format!("@import {text};")));
                    }
                }
                Stmt::Media { query, body, lines } => {
                    let queries = self.resolve_media_queries(query)?;
                    let prelude = serialize_media_queries(&queries);
                    let out_body = self.css_at_body(body)?;
                    if !out_body.is_empty() {
                        let lines = self.stamp(*lines);
                        sink.push_at_rule(OutNode::AtRule {
                            name: "media".to_string(),
                            prelude,
                            body: out_body,
                            has_block: true,
                            lines,
                        });
                    }
                }
                Stmt::Supports { condition, body } => {
                    let prelude = self.serialize_supports_condition(condition)?;
                    let out_body = self.css_at_body(body)?;
                    if !out_body.is_empty() {
                        sink.push_at_rule(OutNode::AtRule {
                            name: "supports".to_string(),
                            prelude,
                            body: out_body,
                            has_block: true,
                            lines: SrcLines::default(),
                        });
                    }
                }
                Stmt::AtRule {
                    name,
                    prelude,
                    body,
                    lines,
                } => {
                    let prelude_s = self.eval_template(prelude)?.trim().to_string();
                    let lines = self.stamp(*lines);
                    match body {
                        None => sink.push_at_rule(OutNode::AtRule {
                            name: name.clone(),
                            prelude: prelude_s,
                            body: Vec::new(),
                            has_block: false,
                            lines,
                        }),
                        Some(b) => {
                            let out_body = self.css_at_body(b)?;
                            sink.push_at_rule(OutNode::AtRule {
                                name: name.clone(),
                                prelude: prelude_s,
                                body: out_body,
                                has_block: true,
                                lines,
                            });
                        }
                    }
                }
                Stmt::Keyframes {
                    name,
                    prelude,
                    body,
                    lines,
                } => {
                    let prelude_s = self.eval_template(prelude)?.trim().to_string();
                    let out_body = self.css_at_body(body)?;
                    let lines = self.stamp(*lines);
                    sink.push_at_rule(OutNode::AtRule {
                        name: name.clone(),
                        prelude: prelude_s,
                        body: out_body,
                        has_block: true,
                        lines,
                    });
                }
                // A plain-CSS custom `@function --x` is emitted verbatim, same
                // as in an SCSS sheet.
                Stmt::CssCustomAtRule { name, prelude, body } => {
                    self.eval_css_custom_at_rule(name, prelude, body, sink)?;
                }
                _ => {}
            }
        }
        Ok(())
    }

    /// Build the body of a top-level plain-CSS at-rule: style rules (with their
    /// own first-level bubbling), bare declarations, comments, and nested
    /// at-rules.
    fn css_at_body(&mut self, stmts: &[Stmt]) -> Result<Vec<OutNode>, Error> {
        let mut out: Vec<OutNode> = Vec::new();
        for stmt in stmts {
            match stmt {
                Stmt::Rule(r) => {
                    let selectors = self.css_selectors(&r.selector, false)?;
                    let (items, bubbled) = self.css_rule_children(&r.body, &selectors)?;
                    if !items.is_empty() {
                        out.push(OutNode::Rule {
                            selectors,
                            linebreaks: Vec::new(),
                            items,
                            lines: self.stamp(SrcLines {
                                file: 0,
                                start: r.brace_line,
                                end: r.end_line,
                                col: 0,
                            }),
                            extend_base: usize::MAX,
                        });
                    }
                    out.extend(bubbled);
                }
                Stmt::Decl(d) => {
                    let prop = self.eval_template(&d.property)?.trim().to_string();
                    let value = self.eval_expr(&d.value)?.to_css(false);
                    out.push(OutNode::AtDecl {
                        prop,
                        value,
                        important: d.important,
                        custom: false,
                        lines: self.stamp(SrcLines {
                            file: 0,
                            start: d.pos.line as u32,
                            end: d.end_line,
                            col: 0,
                        }),
                    });
                }
                Stmt::CustomDecl(d) => {
                    let prop = self.eval_template(&d.property)?.trim().to_string();
                    let value = self.eval_template(&d.value)?;
                    out.push(OutNode::AtDecl {
                        prop,
                        value,
                        important: false,
                        custom: true,
                        lines: self.stamp(SrcLines {
                            file: 0,
                            start: d.pos.line as u32,
                            end: d.end_line,
                            col: 0,
                        }),
                    });
                }
                Stmt::Comment(c, lines) => {
                    let text = self.eval_template(c)?;
                    let lines = self.stamp(*lines);
                    out.push(OutNode::Comment(text, lines));
                }
                Stmt::Media { query, body, lines } => {
                    let queries = self.resolve_media_queries(query)?;
                    let prelude = serialize_media_queries(&queries);
                    let inner = self.css_at_body(body)?;
                    if !inner.is_empty() {
                        let lines = self.stamp(*lines);
                        out.push(OutNode::AtRule {
                            name: "media".to_string(),
                            prelude,
                            body: inner,
                            has_block: true,
                            lines,
                        });
                    }
                }
                Stmt::Supports { condition, body } => {
                    let prelude = self.serialize_supports_condition(condition)?;
                    let inner = self.css_at_body(body)?;
                    if !inner.is_empty() {
                        out.push(OutNode::AtRule {
                            name: "supports".to_string(),
                            prelude,
                            body: inner,
                            has_block: true,
                            lines: SrcLines::default(),
                        });
                    }
                }
                Stmt::AtRule {
                    name,
                    prelude,
                    body,
                    lines,
                } => {
                    let prelude_s = self.eval_template(prelude)?.trim().to_string();
                    let lines = self.stamp(*lines);
                    match body {
                        None => out.push(OutNode::AtRule {
                            name: name.clone(),
                            prelude: prelude_s,
                            body: Vec::new(),
                            has_block: false,
                            lines,
                        }),
                        Some(b) => {
                            let inner = self.css_at_body(b)?;
                            out.push(OutNode::AtRule {
                                name: name.clone(),
                                prelude: prelude_s,
                                body: inner,
                                has_block: true,
                                lines,
                            });
                        }
                    }
                }
                Stmt::Import(args) => {
                    for arg in args {
                        let text = match arg {
                            ImportArg::Css { url, modifiers } => self.serialize_css_import(url, modifiers)?,
                            ImportArg::Sass { path, .. } => format!("\"{path}\""),
                        };
                        out.push(OutNode::Raw(format!("@import {text};")));
                    }
                }
                _ => {}
            }
        }
        Ok(out)
    }

    /// Build the children of a *top-level* plain-CSS style rule: declarations
    /// and nested rules stay in the block; a block at-rule (`@media` etc.)
    /// bubbles out wrapping a copy of the parent rule (dart-sass's standard
    /// at-rule bubbling — `a {@media b {c: d}}` → `@media b { a { c: d } }`).
    /// Deeper levels never bubble (see [`Evaluator::css_body`]).
    #[allow(clippy::type_complexity)]
    fn css_rule_children(
        &mut self,
        stmts: &[Stmt],
        parent_selectors: &[String],
    ) -> Result<(Vec<OutItem>, Vec<OutNode>), Error> {
        let mut items = Vec::new();
        let mut bubbled: Vec<OutNode> = Vec::new();
        let bubble = |name: &str, prelude: String, inner: Vec<OutItem>, bubbled: &mut Vec<OutNode>| {
            if inner.is_empty() {
                return;
            }
            bubbled.push(OutNode::AtRule {
                name: name.to_string(),
                prelude,
                body: vec![OutNode::Rule {
                    selectors: parent_selectors.to_vec(),
                    linebreaks: Vec::new(),
                    items: inner,
                    lines: SrcLines::default(),
                    extend_base: usize::MAX,
                }],
                has_block: true,
                lines: SrcLines::default(),
            });
        };
        for stmt in stmts {
            match stmt {
                Stmt::Media {
                    query,
                    body,
                    lines: _,
                } => {
                    let queries = self.resolve_media_queries(query)?;
                    let prelude = serialize_media_queries(&queries);
                    let inner = self.css_body(body)?;
                    bubble("media", prelude, inner, &mut bubbled);
                }
                Stmt::Supports { condition, body } => {
                    let prelude = self.serialize_supports_condition(condition)?;
                    let inner = self.css_body(body)?;
                    bubble("supports", prelude, inner, &mut bubbled);
                }
                Stmt::AtRule {
                    name,
                    prelude,
                    body: Some(b),
                    ..
                } => {
                    let prelude_s = self.eval_template(prelude)?.trim().to_string();
                    let inner = self.css_body(b)?;
                    bubble(name, prelude_s, inner, &mut bubbled);
                }
                other => self.css_body_stmt(other, &mut items)?,
            }
        }
        Ok((items, bubbled))
    }

    /// Resolve a plain-CSS selector to its comma-separated parts, keeping `&`
    /// and combinators verbatim (no parent resolution), and rejecting the
    /// Sass-only selector forms that plain CSS forbids.
    fn css_selectors(&mut self, sel: &[crate::ast::TplPiece], top_level: bool) -> Result<Vec<String>, Error> {
        let s = self.eval_template(sel)?;
        let parts: Vec<String> = split_commas(&s)
            .into_iter()
            .map(|p| p.trim().to_string())
            .filter(|p| !p.is_empty())
            .collect();
        for p in &parts {
            validate_plain_css_selector(p, top_level)?;
        }
        Ok(parts)
    }

    /// Build a plain-CSS rule body below the first nesting level: declarations
    /// and nested style rules with nesting preserved (`OutItem::NestedRule`),
    /// and block at-rules kept in place (`OutItem::NestedAtRule`) — dart-sass
    /// `_hasCssNesting` skips bubbling once nesting is already native.
    fn css_body(&mut self, stmts: &[Stmt]) -> Result<Vec<OutItem>, Error> {
        let mut items = Vec::new();
        for stmt in stmts {
            self.css_body_stmt(stmt, &mut items)?;
        }
        Ok(items)
    }

    /// Process one plain-CSS statement into rule-body items (the shared body of
    /// [`Evaluator::css_body`] and the non-bubbling arm of
    /// [`Evaluator::css_rule_children`]).
    fn css_body_stmt(&mut self, stmt: &Stmt, items: &mut Vec<OutItem>) -> Result<(), Error> {
        match stmt {
            Stmt::Decl(d) => {
                let prop = self.eval_template(&d.property)?.trim().to_string();
                let value = self.eval_expr(&d.value)?.to_css(false);
                items.push(OutItem::Decl {
                    prop,
                    value,
                    important: d.important,
                    custom: false,
                    lines: self.stamp(SrcLines {
                        file: 0,
                        start: d.pos.line as u32,
                        end: d.end_line,
                        col: 0,
                    }),
                });
            }
            Stmt::CustomDecl(d) => {
                let prop = self.eval_template(&d.property)?.trim().to_string();
                let value = self.eval_template(&d.value)?;
                items.push(OutItem::Decl {
                    prop,
                    value,
                    important: false,
                    custom: true,
                    lines: self.stamp(SrcLines {
                        file: 0,
                        start: d.pos.line as u32,
                        end: d.end_line,
                        col: 0,
                    }),
                });
            }
            Stmt::Rule(r) => {
                let selectors = self.css_selectors(&r.selector, false)?;
                let inner = self.css_body(&r.body)?;
                // An (recursively) empty nested rule is invisible (dart-sass
                // skips childless rules when serializing).
                if !inner.is_empty() {
                    items.push(OutItem::NestedRule {
                        selectors,
                        items: inner,
                    });
                }
            }
            Stmt::Comment(c, lines) => {
                let text = self.eval_template(c)?;
                let lines = self.stamp(*lines);
                items.push(OutItem::Comment(text, lines));
            }
            // A nested `@import` inside a plain-CSS rule is preserved
            // verbatim, like a top-level one (see `exec_css`).
            Stmt::Import(args) => {
                for arg in args {
                    let prelude = match arg {
                        ImportArg::Css { url, modifiers } => self.serialize_css_import(url, modifiers)?,
                        ImportArg::Sass { path, .. } => format!("\"{path}\""),
                    };
                    items.push(OutItem::ChildlessAtRule {
                        name: "import".to_string(),
                        prelude,
                        lines: SrcLines::default(),
                    });
                }
            }
            Stmt::Media {
                query,
                body,
                lines: _,
            } => {
                let queries = self.resolve_media_queries(query)?;
                let prelude = serialize_media_queries(&queries);
                let inner = self.css_body(body)?;
                if !inner.is_empty() {
                    items.push(OutItem::NestedAtRule {
                        name: "media".to_string(),
                        prelude,
                        items: inner,
                    });
                }
            }
            Stmt::Supports { condition, body } => {
                let prelude = self.serialize_supports_condition(condition)?;
                let inner = self.css_body(body)?;
                if !inner.is_empty() {
                    items.push(OutItem::NestedAtRule {
                        name: "supports".to_string(),
                        prelude,
                        items: inner,
                    });
                }
            }
            Stmt::AtRule {
                name,
                prelude,
                body,
                lines,
            } => {
                let prelude_s = self.eval_template(prelude)?.trim().to_string();
                match body {
                    None => {
                        let lines = self.stamp(*lines);
                        items.push(OutItem::ChildlessAtRule {
                            name: name.clone(),
                            prelude: prelude_s,
                            lines,
                        });
                    }
                    Some(b) => {
                        let inner = self.css_body(b)?;
                        if !inner.is_empty() {
                            items.push(OutItem::NestedAtRule {
                                name: name.clone(),
                                prelude: prelude_s,
                                items: inner,
                            });
                        }
                    }
                }
            }
            _ => {}
        }
        Ok(())
    }

    /// Evaluate a parsed module sheet in an isolated environment. The module's
    /// top-level CSS is emitted into `sink`; its members are captured into a
    /// [`Module`]. `config` overrides its `!default` variables.
    #[allow(clippy::too_many_arguments)]
    fn eval_module(
        &mut self,
        key: &str,
        diag_url: &str,
        sheet: &Stylesheet,
        config: HashMap<String, (Value, bool)>,
        config_id: usize,
        pos: Pos,
        sink: &mut Sink<'_>,
        css: bool,
    ) -> Result<(Module, Vec<String>), Error> {
        // Save and reset the per-module environment, then restore on the way out.
        // The module's body runs against its own source file for diagnostics.
        let module_source = self.source_for(diag_url);
        // Relative URLs inside the module resolve against ITS directory.
        let module_dir = dirname_of(key);
        let saved_dir = std::mem::replace(&mut self.current_file_dir, module_dir);
        let saved_url = std::mem::replace(&mut self.current_url, diag_url.to_string());
        self.current_url_stamp = 0;
        let saved_source = std::mem::replace(&mut self.current_source, module_source);
        let saved_scopes = std::mem::replace(&mut self.scopes, vec![new_scope()]);
        let saved_semi = std::mem::replace(&mut self.scope_semi_global, vec![true]);
        let saved_funcs = std::mem::replace(&mut self.functions, vec![new_fn_scope()]);
        let saved_mixins = std::mem::replace(&mut self.mixins, vec![new_fn_scope()]);
        let saved_used = std::mem::take(&mut self.used_modules);
        let saved_star = std::mem::take(&mut self.star_modules);
        let saved_used_user = std::mem::take(&mut self.used_user_modules);
        let saved_star_user = std::mem::take(&mut self.star_user_modules);
        let saved_fwd = std::mem::take(&mut self.forwarded);
        let saved_config = std::mem::replace(&mut self.pending_config, config);
        let saved_config_id = std::mem::replace(&mut self.pending_config_id, config_id);
        let saved_consumed = std::mem::take(&mut self.consumed_config);
        let saved_selector = self.current_selector.take();
        let saved_module = std::mem::replace(&mut self.current_module, key.to_string());
        self.loading.push(key.to_string());

        // A `$var: ... !global` anywhere in the module — even in a branch that
        // never evaluates — creates a variable slot defaulting to null, so the
        // module always exposes the same members regardless of how it's
        // evaluated (dart-sass).
        if !css {
            let mut slots: Vec<String> = Vec::new();
            collect_global_var_decls(&sheet.stmts, &mut slots);
            if let Some(g) = self.scopes.first() {
                let mut g = g.borrow_mut();
                for name in slots {
                    g.entry(name).or_insert(Value::Null);
                }
            }
        }

        // A plain-CSS module preserves its nesting (no Sass flattening, `&` kept
        // literal); a Sass module runs the normal evaluator.
        let result = if css {
            self.exec_css(&sheet.stmts, &[], sink)
        } else {
            self.exec(&sheet.stmts, &[], sink)
        };

        self.loading.pop();
        // Capture this module's evaluated members before restoring the caller's
        // environment.
        let vars_scope = std::mem::take(&mut self.scopes)
            .into_iter()
            .next()
            .unwrap_or_else(new_scope);
        // The module's top-level function/mixin frames, shared by Rc with the
        // chains the module's own callables captured.
        let functions = std::mem::take(&mut self.functions)
            .into_iter()
            .next()
            .unwrap_or_else(new_fn_scope);
        let mixins = std::mem::take(&mut self.mixins)
            .into_iter()
            .next()
            .unwrap_or_else(new_fn_scope);
        let used_user_modules = std::mem::take(&mut self.used_user_modules);
        let star_user_modules = std::mem::take(&mut self.star_user_modules);
        let used_builtin_modules = std::mem::take(&mut self.used_modules);
        let star_builtin_modules = std::mem::take(&mut self.star_modules);
        let forwarded = std::mem::take(&mut self.forwarded);
        // Config keys this module actually consumed (via a `!default` declaration
        // or by passing them through a `@forward ... with`).
        let consumed = std::mem::take(&mut self.consumed_config);

        // Restore the caller's environment.
        self.scopes = saved_scopes;
        self.scope_semi_global = saved_semi;
        self.functions = saved_funcs;
        self.mixins = saved_mixins;
        self.used_modules = saved_used;
        self.star_modules = saved_star;
        self.used_user_modules = saved_used_user;
        self.star_user_modules = saved_star_user;
        self.forwarded = saved_fwd;
        self.pending_config = saved_config;
        self.pending_config_id = saved_config_id;
        self.consumed_config = saved_consumed;
        self.current_selector = saved_selector;
        self.current_module = saved_module;
        self.current_file_dir = saved_dir;
        self.current_url = saved_url;
        self.current_url_stamp = 0;
        self.current_source = saved_source;

        result?;
        let _ = pos;

        // Merge `@forward`ed members (lower precedence than the module's own).
        // A member the module did NOT shadow keeps its origin binding, so
        // reads/writes/calls route to the defining module.
        let mut var_origins: HashMap<String, (Rc<Module>, String)> = HashMap::default();
        let mut fn_origins: HashMap<String, Rc<Module>> = HashMap::default();
        let mut mixin_origins: HashMap<String, Rc<Module>> = HashMap::default();
        // Assignments write through to the forwarded module even when the
        // module's own same-named variable shadows it for reads.
        let var_write_origins: HashMap<String, (Rc<Module>, String)> = forwarded
            .var_origins
            .iter()
            .map(|(k, (m, o))| (k.clone(), (Rc::clone(m), o.clone())))
            .collect();
        {
            let mut vars = vars_scope.borrow_mut();
            for (k, v) in forwarded.vars {
                if let std::collections::hash_map::Entry::Vacant(e) = vars.entry(k.clone()) {
                    e.insert(v);
                    if let Some(o) = forwarded.var_origins.get(&k) {
                        var_origins.insert(k, (Rc::clone(&o.0), o.1.clone()));
                    }
                }
            }
        }
        {
            let mut fns = functions.borrow_mut();
            for (k, v) in forwarded.functions {
                if let std::collections::hash_map::Entry::Vacant(e) = fns.entry(k.clone()) {
                    e.insert(v);
                    if let Some(o) = forwarded.fn_origins.get(&k) {
                        fn_origins.insert(k, Rc::clone(o));
                    }
                }
            }
        }
        {
            let mut mxs = mixins.borrow_mut();
            for (k, v) in forwarded.mixins {
                if let std::collections::hash_map::Entry::Vacant(e) = mxs.entry(k.clone()) {
                    e.insert(v);
                    if let Some(o) = forwarded.mixin_origins.get(&k) {
                        mixin_origins.insert(k, Rc::clone(o));
                    }
                }
            }
        }

        Ok((
            Module {
                vars: vars_scope,
                functions,
                mixins,
                used_user_modules,
                star_user_modules,
                used_builtin_modules,
                star_builtin_modules,
                forwarded_builtins: forwarded.builtins,
                var_origins,
                var_write_origins,
                fn_origins,
                mixin_origins,
                diag_url: diag_url.to_string(),
                config_origin: std::cell::Cell::new(self.pending_config_id),
                file_dir: dirname_of(key).unwrap_or_default(),
                emitted_main: std::cell::Cell::new(false),
                css: Vec::new(),
            },
            consumed,
        ))
    }

    /// Process a `@forward "<url>" [as p-*] [show ..|hide ..] [with (..)];`:
    /// load the target module (emitting its CSS), then re-export its public
    /// members from the module currently being evaluated, applying prefix and
    /// show/hide filters.
    #[allow(clippy::too_many_arguments)]
    fn exec_forward(
        &mut self,
        url: &str,
        prefix: Option<&str>,
        show: &Option<Vec<crate::ast::ForwardMember>>,
        hide: &Option<Vec<crate::ast::ForwardMember>>,
        config: &[crate::ast::ConfigEntry],
        pos: Pos,
        parents: &[String],
        sink: &mut Sink<'_>,
    ) -> Result<(), Error> {
        // `@forward "sass:<mod>"` re-exports a built-in module. Built-ins can't
        // be configured.
        if let Some(m) = url.strip_prefix("sass:") {
            if !crate::builtins::is_module(m) {
                return Err(Error::at("Can't find stylesheet to import.".to_string(), pos));
            }
            if !config.is_empty() {
                return Err(Error::at(
                    "Built-in modules can't be configured.".to_string(),
                    pos,
                ));
            }
            self.forwarded.builtins.push(ForwardedBuiltin {
                module: m.to_string(),
                prefix: prefix.map(str::to_string),
                show: member_set(show, false),
                hide: member_set(hide, false),
            });
            return Ok(());
        }

        // Build the configuration passed to the forwarded module. The forward's
        // own `with (...)` entries combine with the configuration of the module
        // currently being evaluated (`pending_config`): a non-`!default` forward
        // entry hard-overrides; a `!default` forward entry yields to a matching
        // downstream override; downstream entries for variables the forward
        // re-exports (visible and matching its `as` prefix) flow through.
        let forward_conf = self.eval_config(config)?;
        let downstream = self.pending_config.clone();
        // Only downstream config for variables this forward actually re-exports
        // flows through. A `show`/`hide` filter or an `as p-*` prefix that hides
        // a variable also makes it unconfigurable through this forward. The map
        // value tracks (upstream-name, downstream-name) so consumption maps back.
        let var_visible = forward_var_visibility(show, hide);
        let pfx_opt = prefix;
        let mut passthrough: HashMap<String, (Value, bool)> = HashMap::default();
        // upstream config key -> downstream key it came from.
        let mut passthrough_origin: HashMap<String, String> = HashMap::default();
        for (dk, dv) in &downstream {
            // Map a downstream (prefixed) name back to the upstream member name.
            let upstream_name = match pfx_opt {
                Some(p) => match dk.strip_prefix(p) {
                    Some(rest) => rest.to_string(),
                    None => continue,
                },
                None => dk.clone(),
            };
            if is_private_member(&upstream_name) || !var_visible(&upstream_name) {
                continue;
            }
            passthrough.insert(upstream_name.clone(), dv.clone());
            passthrough_origin.insert(upstream_name, dk.clone());
        }
        let mut combined: HashMap<String, (Value, bool)> = passthrough.clone();
        // Keys whose downstream entry a `!default` forward override consumed.
        let mut forward_claimed: Vec<String> = Vec::new();
        // The forward's own (non-passthrough) keys, which the forwarded module
        // must consume (else configuring a non-`!default` variable -> error).
        let mut forward_own: Vec<String> = Vec::new();
        // Keys (upstream-side) a non-`!default` forward entry hard-overrode.
        let mut forward_shadowed: Vec<String> = Vec::new();
        for (name, (val, is_default)) in &forward_conf {
            if *is_default {
                // A downstream override wins over a `!default` forward entry —
                // but a `null` downstream value counts as "not configured", so
                // the forward default still applies.
                let downstream_overrides = passthrough
                    .get(name)
                    .is_some_and(|(v, _)| !matches!(v, Value::Null));
                if downstream_overrides {
                    forward_claimed.push(name.clone());
                } else {
                    combined.insert(name.clone(), (val.clone(), false));
                    forward_own.push(name.clone());
                }
            } else {
                if passthrough.contains_key(name) {
                    forward_shadowed.push(name.clone());
                }
                combined.insert(name.clone(), (val.clone(), false));
                forward_own.push(name.clone());
            }
        }

        // A forward with its own `with (...)` entries makes the configuration
        // explicit (already-loaded then errors); pure passthrough keeps the
        // caller's implicit/explicit status.
        let saved_implicit = self.config_is_implicit;
        if !forward_conf.is_empty() {
            self.config_is_implicit = false;
        }
        // A pure passthrough keeps the original configuration identity; a
        // forward with its own `with (...)` starts a new one.
        let combined_id = if forward_conf.is_empty() {
            self.pending_config_id
        } else {
            self.fresh_config_id()
        };
        let load_result = self.load_module(url, combined, combined_id, pos, parents, false, sink);
        self.config_is_implicit = saved_implicit;
        let (module, consumed) = load_result?;

        // A non-passthrough forward entry the module never consumed configured a
        // variable that isn't `!default` in the forwarded module.
        if forward_own.iter().any(|k| !consumed.contains(k)) {
            return Err(Error::at(
                "This variable was not declared with !default in the @used module.".to_string(),
                pos,
            ));
        }
        // Mark the downstream config keys this forward consumed (passthrough +
        // `!default`-claimed) as consumed in the enclosing module, so they are
        // not reported as unused. A key a non-`!default` forward entry shadowed
        // stays unconsumed (the downstream override is then an error). The
        // consumed keys are upstream-side; map them back to downstream names.
        for up in consumed.iter().chain(forward_claimed.iter()) {
            if forward_shadowed.contains(up) {
                continue;
            }
            if let Some(dk) = passthrough_origin.get(up) {
                if !self.consumed_config.contains(dk) {
                    self.consumed_config.push(dk.clone());
                }
            }
        }

        let show_vars = member_set(show, true);
        let show_names = member_set(show, false);
        let hide_vars = member_set(hide, true);
        let hide_names = member_set(hide, false);
        let has_show = show.is_some();

        // `show`/`hide` names are dash/underscore-insensitive, so compare the
        // canonical (dashed) form.
        let visible_var = |name: &str| -> bool {
            if is_private_member(name) {
                return false;
            }
            let n = normalize_var_name(name);
            if has_show {
                show_vars.as_ref().map(|s| s.contains(&n)).unwrap_or(false)
            } else {
                !hide_vars.as_ref().map(|s| s.contains(&n)).unwrap_or(false)
            }
        };
        let visible_name = |name: &str| -> bool {
            if is_private_member(name) {
                return false;
            }
            let n = normalize_var_name(name);
            if has_show {
                show_names.as_ref().map(|s| s.contains(&n)).unwrap_or(false)
            } else {
                !hide_names.as_ref().map(|s| s.contains(&n)).unwrap_or(false)
            }
        };

        // Two `@forward`s that bring the same member name from DIFFERENT modules
        // conflict — an error reported immediately, even when the member is
        // never used. Re-forwarding the SAME module is idempotent.
        // With a prefix, `show`/`hide` names match the PREFIXED member name.
        // Private members (by their ORIGINAL name) are never re-exported.
        let src: *const Module = Rc::as_ptr(&module);
        let pfx = prefix.unwrap_or("");
        let module_vars: Vec<(String, Value)> = module
            .vars
            .borrow()
            .iter()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect();
        for (name, val) in &module_vars {
            let key = format!("{pfx}{name}");
            if !is_private_member(name) && visible_var(&key) {
                // The member's true home: follow the module's own origin
                // entry (a re-forward stays bound to the defining module).
                let origin = module
                    .var_origin(name)
                    .unwrap_or_else(|| (Rc::clone(&module), name.clone()));
                // Conflict identity is that home module, so two forwards that
                // both re-export the SAME upstream member don't collide
                // (distributed configuration trees).
                let member_src: *const Module = Rc::as_ptr(&origin.0);
                if let Some(prev) = self.forwarded.var_src.get(&key) {
                    if *prev != member_src {
                        return Err(Error::at(
                            format!("Two forwarded modules both define a variable named ${key}."),
                            pos,
                        ));
                    }
                }
                self.forwarded.vars.insert(key.clone(), val.clone());
                self.forwarded.var_origins.insert(key.clone(), origin);
                self.forwarded.var_src.insert(key, member_src);
            }
        }
        for (name, f) in module.functions.borrow().iter() {
            let key = format!("{pfx}{name}");
            if !is_private_member(name) && visible_name(&key) {
                let f_src: *const Module = module.fn_origin(name).map(|m| Rc::as_ptr(&m)).unwrap_or(src);
                if let Some(prev) = self.forwarded.fn_src.get(&key) {
                    if *prev != f_src {
                        return Err(Error::at(
                            format!("Two forwarded modules both define a function named {key}."),
                            pos,
                        ));
                    }
                }
                let origin = module.fn_origin(name).unwrap_or_else(|| Rc::clone(&module));
                self.forwarded.functions.insert(key.clone(), Rc::clone(f));
                self.forwarded.fn_origins.insert(key.clone(), origin);
                self.forwarded.fn_src.insert(key, f_src);
            }
        }
        for (name, m) in module.mixins.borrow().iter() {
            let key = format!("{pfx}{name}");
            if !is_private_member(name) && visible_name(&key) {
                let m_src: *const Module = module.mixin_origin(name).map(|m| Rc::as_ptr(&m)).unwrap_or(src);
                if let Some(prev) = self.forwarded.mixin_src.get(&key) {
                    if *prev != m_src {
                        return Err(Error::at(
                            format!("Two forwarded modules both define a mixin named {key}."),
                            pos,
                        ));
                    }
                }
                let origin = module.mixin_origin(name).unwrap_or_else(|| Rc::clone(&module));
                self.forwarded.mixins.insert(key.clone(), Rc::clone(m));
                self.forwarded.mixin_origins.insert(key.clone(), origin);
                self.forwarded.mixin_src.insert(key, m_src);
            }
        }
        Ok(())
    }

    // ---- statements --------------------------------------------------

    /// Execute a block of statements, routing each into `sink`. One executor
    /// serves the top level (each statement is its own group), rule bodies
    /// (declarations join the block, nested rules bubble out), and every
    /// nested-block construct that reuses it.
    fn exec(&mut self, stmts: &[Stmt], parents: &[String], sink: &mut Sink<'_>) -> Result<(), Error> {
        for stmt in stmts {
            match stmt {
                Stmt::VarDecl(v) => self.apply_var(v)?,
                Stmt::Comment(c, lines) => {
                    let text = self.eval_template(c)?;
                    let lines = self.stamp(*lines);
                    sink.push_comment(text, lines);
                }
                Stmt::Decl(d) => {
                    if sink.is_top() {
                        return Err(Error::at("top-level declarations aren't allowed", d.pos));
                    }
                    if let Some(oi) = self.eval_decl(d)? {
                        sink.push_item(oi);
                    }
                }
                Stmt::PropertySet(ps) => {
                    if sink.is_top() {
                        return Err(Error::at("top-level declarations aren't allowed", ps.pos));
                    }
                    self.eval_property_set(ps, parents, sink)?;
                }
                Stmt::CustomDecl(d) => {
                    if sink.is_top() {
                        return Err(Error::at("top-level declarations aren't allowed", d.pos));
                    }
                    // A literal `--` name may never be nested inside a property
                    // set (dart-sass parse-time error).
                    if self.decl_prefix.is_some() {
                        return Err(Error::at(
                            "Declarations whose names begin with \"--\" may not be nested.",
                            d.pos,
                        ));
                    }
                    if let Some(oi) = self.eval_custom_decl(d)? {
                        sink.push_item(oi);
                    }
                }
                Stmt::Rule(r) => self.eval_style_rule(r, parents, sink)?,
                Stmt::If(branches) => {
                    // Evaluate conditions top to bottom; run the first match's
                    // body in a fresh semi-global scope so an assignment to an
                    // existing outer variable updates it (and can reach the
                    // global scope when every enclosing scope is semi-global),
                    // while a freshly declared variable stays local to the
                    // branch (dart-sass `visitIf`).
                    for branch in branches {
                        let take = match &branch.cond {
                            None => true,
                            Some(c) => self.eval_expr(c)?.is_truthy(),
                        };
                        if take {
                            self.push_scope(true);
                            let result = self.exec(&branch.body, parents, sink);
                            self.pop_scope();
                            result?;
                            break;
                        }
                    }
                }
                Stmt::For {
                    var,
                    from,
                    to,
                    inclusive,
                    body,
                } => {
                    let (start_i, end_i, unit) = self.for_bounds(from, to)?;
                    // The loop body runs in its own semi-global scope: the loop
                    // variable and any fresh assignments live there and vanish
                    // when the loop ends (dart-sass `visitForRule`).
                    self.push_scope(true);
                    let mut result = Ok(());
                    for i in for_indices(start_i, end_i, *inclusive) {
                        self.set_local(var, Value::Number(Number::with_unit(i as f64, unit.clone())));
                        result = self.exec(body, parents, sink);
                        if result.is_err() {
                            break;
                        }
                    }
                    self.pop_scope();
                    result?;
                }
                Stmt::Each { vars, list, body } => {
                    let items = self.eval_each_items(list)?;
                    self.push_scope(true);
                    let mut result = Ok(());
                    for item in items {
                        self.bind_each(vars, item);
                        result = self.exec(body, parents, sink);
                        if result.is_err() {
                            break;
                        }
                    }
                    self.pop_scope();
                    result?;
                }
                Stmt::While { cond, body } => {
                    self.push_scope(true);
                    let mut result = Ok(());
                    let mut guard = 0u32;
                    loop {
                        match self.eval_expr(cond) {
                            Ok(v) if v.is_truthy() => {}
                            Ok(_) => break,
                            Err(e) => {
                                result = Err(e);
                                break;
                            }
                        }
                        result = self.exec(body, parents, sink);
                        if result.is_err() {
                            break;
                        }
                        guard += 1;
                        if guard >= 100_000 {
                            result = Err(Error::unpositioned("@while exceeded 100000 iterations"));
                            break;
                        }
                    }
                    self.pop_scope();
                    result?;
                }
                Stmt::FunctionDef(callable) => {
                    let captured = self.capture_callable(callable);
                    self.define_function(&callable.name, captured);
                }
                Stmt::MixinDef(callable) => {
                    let captured = self.capture_callable(callable);
                    self.define_mixin(&callable.name, captured);
                }
                Stmt::Return(_) => {
                    return Err(Error::unpositioned("@return is only allowed inside a function."));
                }
                Stmt::Include {
                    name,
                    args,
                    content,
                    content_params,
                    module,
                    pos,
                    length,
                } => {
                    // Push a diagnostic call frame so an error/warning raised in
                    // the mixin body unwinds through this `@include` call site.
                    let saved = self.enter_call(*pos, *length, &mixin_frame_name(name, module));
                    let r = self.exec_include(
                        name,
                        args,
                        content.clone(),
                        content_params.clone(),
                        module.as_deref(),
                        *pos,
                        parents,
                        sink,
                    );
                    self.leave_call(saved);
                    r?;
                }
                Stmt::Use {
                    url,
                    namespace,
                    star,
                    config,
                    pos,
                } => self.exec_use(url, namespace.as_deref(), *star, config, *pos, parents, sink)?,
                Stmt::Forward {
                    url,
                    prefix,
                    show,
                    hide,
                    config,
                    pos,
                } => self.exec_forward(url, prefix.as_deref(), show, hide, config, *pos, parents, sink)?,
                Stmt::Content(content_args) => {
                    // The content block runs in the caller's context, so it is no
                    // longer "directly in a mixin" (dart-sass): a
                    // `meta.content-exists()` inside it is an error.
                    self.in_mixin.push(false);
                    let result = self.exec_content(content_args, parents, sink);
                    self.in_mixin.pop();
                    result?;
                }
                Stmt::Import(args) => self.eval_imports(args, parents, sink)?,
                Stmt::AtRule {
                    name,
                    prelude,
                    body,
                    lines,
                } => {
                    let lines = self.stamp(*lines);
                    self.eval_at_rule(name, prelude, body.as_deref(), lines, parents, sink)?;
                }
                Stmt::InterpAtRule { name, prelude, body } => {
                    // The name resolves at eval time; `@keyframes` is the one
                    // rule whose special handling happens here (frame stops).
                    let resolved = self.eval_template(name)?;
                    if is_keyframes_name(&resolved) && body.is_some() {
                        if let Some(b) = body {
                            self.eval_keyframes(&resolved, prelude, b, SrcLines::default(), sink)?;
                        }
                    } else {
                        self.eval_at_rule(
                            &resolved,
                            prelude,
                            body.as_deref(),
                            SrcLines::default(),
                            parents,
                            sink,
                        )?;
                    }
                }
                Stmt::CssCustomAtRule { name, prelude, body } => {
                    self.eval_css_custom_at_rule(name, prelude, body, sink)?;
                }
                Stmt::Media { query, body, lines } => {
                    let stamped = self.stamp(*lines);
                    self.eval_media(query, body, stamped, parents, sink)?;
                }
                Stmt::Supports { condition, body } => {
                    self.eval_supports(condition, body, parents, sink)?;
                }
                Stmt::AtRoot { query, body } => {
                    self.eval_at_root(query.as_deref(), body, parents, sink)?;
                }
                Stmt::Keyframes {
                    name,
                    prelude,
                    body,
                    lines,
                } => {
                    let lines = self.stamp(*lines);
                    self.eval_keyframes(name, prelude, body, lines, sink)?;
                }
                Stmt::Extend {
                    selector,
                    optional,
                    pos,
                } => self.register_extend(selector, *optional, *pos, parents)?,
                Stmt::Warn { value, pos } => self.emit_warn(value, *pos)?,
                Stmt::Debug { value, pos } => self.emit_debug(value, *pos)?,
                Stmt::Error { value, pos, length } => {
                    return Err(self.build_error(value, *pos, *length));
                }
            }
        }
        Ok(())
    }

    /// Evaluate a style rule: resolve its selector against `parents`, run its
    /// body into a fresh rule sink, then hand the produced block and the
    /// rules that bubbled out of it to the enclosing `sink`.
    fn eval_style_rule(&mut self, rule: &Rule, parents: &[String], sink: &mut Sink<'_>) -> Result<(), Error> {
        let (sel_str, interp_bounds) = self.eval_template_bounds(&rule.selector)?;
        // A selector that resolves to nothing (e.g. `#{&}` at the document root,
        // where `&` is null) is rejected by dart-sass with "expected selector".
        if sel_str.trim().is_empty() {
            return Err(Error::unpositioned("expected selector."));
        }
        validate_selector(&sel_str, !parents.is_empty())?;
        // A `@` has no legal position in a CSS selector: dart's selector
        // parser fails with "expected selector." — pointed at the source when
        // the offending character maps to literal text, or rendered as the
        // dual-span "error in interpolated output" diagnostic when it came
        // from an interpolation (todo_single_escape).
        if !self.in_keyframes {
            if let Some(at_idx) = find_unquoted_at(&sel_str) {
                return Err(self.interp_selector_error(rule, &sel_str, &interp_bounds, at_idx));
            }
        }
        // A selector starting with a digit is dart's "expected selector."
        // (`1a {}`, issue_2023) — except keyframe stops (`50%`, `13E2%`).
        if !self.in_keyframes {
            for part in split_commas(&sel_str) {
                if part.trim_start().starts_with(|c: char| c.is_ascii_digit()) {
                    return Err(Error::unpositioned("expected selector."));
                }
            }
        }
        // A keyframe selector list is stops (`from`, `to`, `13E+1%`), not CSS
        // selectors: no combinator normalization or parent resolution.
        let current = if self.in_keyframes {
            split_commas(&sel_str)
                .into_iter()
                .map(|p| p.trim().to_string())
                .filter(|p| !p.is_empty())
                .collect()
        } else {
            resolve_selectors_opt(&sel_str, parents, !self.at_root_excluding_style_rule)?
        };
        // Drop "bogus combinator" complex selectors from the emitted block;
        // dart-sass omits them from the generated CSS. A top-level TRAILING
        // combinator (`a >`) is bogus as a leaf (its own declaration block is
        // dropped) but valid for NESTING, so the full `current` list — including
        // such selectors — is still used for `&` resolution and as the `parents`
        // for nested rules (`a >` + `b` -> `a > b`). A nested rule that inherits
        // a genuinely bogus combinator (double, or leading/trailing in a pseudo)
        // is dropped in turn.
        // Per-complex source line-breaks (`a,\nb`). `current` is `parents ×
        // parts` (or just `parts` at the root), so complex `i` came from part
        // `i % parts.len()`; carry that part's "newline before" flag, filtered
        // in step with the dropped bogus selectors.
        // Fast path: no newline anywhere in the source list and no inherited
        // parent breaks means every flag is false — an EMPTY vec, which all
        // consumers (`.get(i)` fallbacks, the `parents.len()` match below for
        // nested rules) already read as all-false. Skips the split/scan and
        // three per-rule allocations on the overwhelmingly common shape.
        let full_lbs: Vec<bool> = if self.current_linebreaks.is_empty() && !sel_str.contains('\n') {
            Vec::new()
        } else {
            let part_lbs = comma_linebreaks(&sel_str, !parents.is_empty());
            let n = part_lbs.len().max(1);
            // A nested complex came from parent `i / n` (`current` is
            // parent-major `parents × parts`); it starts a fresh line when its
            // own part did OR its parent did.
            let parent_lbs: &[bool] = if self.current_linebreaks.len() == parents.len() {
                &self.current_linebreaks
            } else {
                &[]
            };
            (0..current.len())
                .map(|i| {
                    part_lbs.get(i % n).copied().unwrap_or(false)
                        || parent_lbs.get(i / n).copied().unwrap_or(false)
                })
                .collect()
        };
        let mut emit_selectors: Vec<String> = Vec::new();
        let mut emit_linebreaks: Vec<bool> = Vec::new();
        for (i, s) in current.iter().enumerate() {
            if complex_selector_block_is_bogus(s) {
                // The omitted selector still participates in @extend target
                // matching (dart keeps the rule in the extend graph and only
                // omits it from the emitted CSS).
                self.bogus_selectors.push(s.clone());
                continue;
            }
            // A placeholder rule stays an @extend target even when its body
            // produces nothing (`%bam { bam: null }` is "found", dart keeps
            // every rule in the extend graph; we prune empty rules from the
            // output tree, so record the selector with its module scope).
            if s.contains('%') {
                self.placeholder_rules
                    .push((self.current_module.clone(), s.clone()));
            }
            // A keyframe selector's percentage normalizes its exponent marker
            // to lowercase (`130E-1%` -> `130e-1%`), digits untouched.
            let s = if self.in_keyframes {
                normalize_keyframe_selector(s)
            } else {
                s.clone()
            };
            emit_selectors.push(s);
            if !full_lbs.is_empty() {
                emit_linebreaks.push(full_lbs.get(i).copied().unwrap_or(false));
            }
        }
        self.push_scope(false);
        let prev_selector = self.current_selector.replace(current.clone());
        let prev_linebreaks = std::mem::replace(&mut self.current_linebreaks, full_lbs);
        // Entering a style rule re-enables the implicit parent join for
        // anything nested below it (dart resets _atRootExcludingStyleRule).
        let prev_at_root = std::mem::replace(&mut self.at_root_excluding_style_rule, false);
        let rule_lines = self.stamp(SrcLines {
            file: 0,
            start: rule.brace_line,
            end: rule.end_line,
            col: 0,
        });
        let mut items: Vec<OutItem> = Vec::new();
        let mut nested: Vec<OutNode> = Vec::new();
        let mut flushed: Option<usize> = None;
        let at_depth = self.at_rule_ctx.len();
        // dart `addSelector` timing: how many `@extend`s were already registered
        // when this rule's selector was established (before its body runs and
        // registers any of its own). A rule registered AFTER all its applicable
        // `@extend`s is extended one-shot in dart's `paths` order; otherwise the
        // registration-order fold.
        let extend_base = self.extends.len();
        let result = {
            let mut child = Sink::Rule {
                selectors: &emit_selectors,
                linebreaks: &emit_linebreaks,
                lines: rule_lines,
                items: &mut items,
                nested: &mut nested,
                at_depth,
                flushed: &mut flushed,
                extend_base,
            };
            let r = self.exec(&rule.body, &current, &mut child);
            // Flush any declarations/loud comments that follow the last nested
            // rule, so they emit (in their own block) after the bubbled rules.
            if r.is_ok() {
                child.flush_rule_block();
            }
            r
        };
        self.current_selector = prev_selector;
        self.current_linebreaks = prev_linebreaks;
        self.at_root_excluding_style_rule = prev_at_root;
        self.pop_scope();
        result?;
        sink.emit_style_rule(nested);
        Ok(())
    }

    /// Evaluate a generic at-rule. The prelude template is resolved to a
    /// string; the body (when present) is executed so that nested rules carry
    /// the enclosing selectors INSIDE the at-rule, and the whole node hoists to
    /// the document root (bubbling).
    fn eval_at_rule(
        &mut self,
        name: &str,
        prelude: &[TplPiece],
        body: Option<&[Stmt]>,
        lines: SrcLines,
        parents: &[String],
        sink: &mut Sink<'_>,
    ) -> Result<(), Error> {
        let prelude = self.eval_template(prelude)?;
        let Some(stmts) = body else {
            // dart-sass strips a top-level (or bubbled-out) `@charset` entirely,
            // but keeps one that appears inside a style rule's block.
            if name == "charset" && !sink.is_rule() {
                return Ok(());
            }
            sink.push_childless_at_rule(name.to_string(), prelude, lines);
            return Ok(());
        };
        // `@font-face` (exactly, case-sensitively, unprefixed) holds plain
        // declarations: dart-sass does NOT carry the enclosing style-rule
        // selector into its body — `a { @font-face { d: e } }` emits a bare
        // `@font-face { d: e }`. Every other at-rule (including `@page`,
        // `@-moz-font-face`, and unknown directives) wraps its body in the
        // enclosing selector — UNLESS we're directly inside `@at-root`,
        // where there is no style rule to wrap with (dart's _styleRule is
        // null even though `&` still resolves).
        let body_parents: &[String] = if name == "font-face" || self.at_root_excluding_style_rule {
            &[]
        } else {
            parents
        };
        let out_body = self.eval_at_body(stmts, body_parents)?;
        sink.push_at_rule(OutNode::AtRule {
            name: name.to_string(),
            prelude,
            body: out_body,
            has_block: true,
            lines,
        });
        Ok(())
    }

    /// Evaluate a plain CSS custom `@function`/`@mixin`: resolve the prelude
    /// and each body declaration (verbatim values keep their literal text;
    /// interpolated-property declarations evaluate as SassScript), then emit the
    /// whole construct verbatim as a generic at-rule.
    fn eval_css_custom_at_rule(
        &mut self,
        name: &str,
        prelude: &[TplPiece],
        body: &[CssCustomItem],
        sink: &mut Sink<'_>,
    ) -> Result<(), Error> {
        let prelude = self.eval_template(prelude)?;
        let mut out_body: Vec<OutNode> = Vec::new();
        for item in body {
            let prop = self.eval_template(&item.property)?;
            match &item.value {
                CssCustomValue::Raw(tpl) => {
                    let raw = self.eval_template(tpl)?;
                    out_body.push(OutNode::Raw(format!("{prop}:{raw};")));
                }
                CssCustomValue::Script(expr) => {
                    let value = self.eval_expr(expr)?.to_css(self.compressed());
                    out_body.push(OutNode::Raw(format!("{prop}: {value};")));
                }
                // A nested property set on an interpolated property: each
                // child emits as `property-suffix: value`.
                CssCustomValue::Set(children) => {
                    for (suffix, expr) in children {
                        let sfx = self.eval_template(suffix)?;
                        let value = self.eval_expr(expr)?.to_css(self.compressed());
                        out_body.push(OutNode::Raw(format!("{prop}-{sfx}: {value};")));
                    }
                }
            }
        }
        sink.push_at_rule(OutNode::AtRule {
            name: name.to_string(),
            prelude,
            body: out_body,
            has_block: true,
            lines: SrcLines::default(),
        });
        Ok(())
    }

    /// Run an at-rule body, producing its output node list. When the at-rule
    /// is nested under a style rule, bare declarations are wrapped in the
    /// enclosing selectors; at the document root they emit directly.
    fn eval_at_body(&mut self, stmts: &[Stmt], parents: &[String]) -> Result<Vec<OutNode>, Error> {
        self.push_scope(false);
        let mut body: Vec<OutNode> = Vec::new();
        let result = if parents.is_empty() {
            let mut child = Sink::AtRoot(&mut body);
            self.exec(stmts, &[], &mut child)
        } else {
            let mut items: Vec<OutItem> = Vec::new();
            let mut nested: Vec<OutNode> = Vec::new();
            let mut flushed: Option<usize> = None;
            let at_depth = self.at_rule_ctx.len();
            let res = {
                let mut child = Sink::Rule {
                    selectors: parents,
                    linebreaks: &[],
                    // No source rule of its own (the wrap re-uses the enclosing
                    // selectors); the trailing-comment rule stays disabled.
                    lines: SrcLines::default(),
                    items: &mut items,
                    nested: &mut nested,
                    at_depth,
                    flushed: &mut flushed,
                    extend_base: usize::MAX,
                };
                let r = self.exec(stmts, parents, &mut child);
                if r.is_ok() {
                    child.flush_rule_block();
                }
                r
            };
            if res.is_ok() {
                body.extend(nested);
            }
            res
        };
        self.pop_scope();
        result?;
        Ok(body)
    }

    /// Evaluate `@media`: resolve the query list (SassScript inside feature
    /// values is evaluated), merge with any enclosing `@media`, run the body
    /// carrying enclosing selectors inside, then emit the at-rule (which bubbles
    /// to the document root). An empty body produces no output.
    fn eval_media(
        &mut self,
        query: &MediaQueryList,
        body: &[Stmt],
        lines: SrcLines,
        parents: &[String],
        sink: &mut Sink<'_>,
    ) -> Result<(), Error> {
        // Without an enclosing style rule, a bare declaration directly inside a
        // media block is invalid (dart-sass: "expected \"{\".") — only rules and
        // at-rules may appear there. With a style rule, declarations belong to
        // its selector and are allowed.
        if parents.is_empty() {
            for stmt in body {
                if matches!(stmt, Stmt::Decl(_)) {
                    return Err(Error::unpositioned("expected \"{\"."));
                }
            }
        }

        let queries = self.resolve_media_queries(query)?;

        // Inside a keyframe block an at-rule nests verbatim: the frame is not
        // a style rule in dart-sass, so there is no bubbling/wrapping.
        if self.in_keyframes && sink.is_rule() {
            let prelude = serialize_media_queries(&queries);
            let out_body = self.eval_at_body(body, &[])?;
            sink.push_item(OutItem::NestedAtRule {
                name: "media".to_string(),
                prelude,
                items: at_body_to_items(out_body),
            });
            return Ok(());
        }

        // Merge with the enclosing media context (dart-sass `_mergeMediaQueries`).
        let merged = if self.media_queries.is_empty() {
            None
        } else {
            match merge_media_query_lists(&self.media_queries, &queries) {
                // Mutually exclusive everywhere — emit nothing.
                Some(m) if m.is_empty() => return Ok(()),
                other => other,
            }
        };

        // Children see the merged queries when mergeable, else just our own.
        let child_queries = merged.clone().unwrap_or_else(|| queries.clone());
        // The emitted node carries the merged queries (when mergeable) and
        // bubbles past the enclosing media; otherwise it stays nested.
        let bubble_out = merged.is_some();
        let node_queries = if bubble_out { &child_queries } else { &queries };
        let prelude = serialize_media_queries(node_queries);

        let enclosing = !self.media_queries.is_empty();
        let saved = std::mem::replace(&mut self.media_queries, child_queries);
        let saved_hoist = std::mem::take(&mut self.media_hoist);
        let own_depth = self.at_rule_ctx.len();
        self.at_rule_ctx.push(AtCtx::Media {
            prelude: prelude.clone(),
        });
        let out_body = self.eval_at_body(body, parents);
        self.at_rule_ctx.pop();
        self.media_queries = saved;
        let mut hoisted = std::mem::replace(&mut self.media_hoist, saved_hoist);
        let out_body = out_body?;

        // Split the body at the hoist markers nested mergeable media rules
        // left behind: each marker interleaves the bubbled rule at its source
        // position, slicing this rule's own children into segments around it
        // (dart-sass#453 keeps source order).
        let mut result: Vec<OutNode> = Vec::new();
        let mut segment: Vec<OutNode> = Vec::new();
        let mut hoist_iter = hoisted.drain(..);
        let flush = |segment: &mut Vec<OutNode>, result: &mut Vec<OutNode>, prelude: &str| {
            if !segment.is_empty() {
                result.push(OutNode::AtRule {
                    name: "media".to_string(),
                    prelude: prelude.to_string(),
                    body: std::mem::take(segment),
                    has_block: true,
                    lines,
                });
            }
        };
        for n in out_body {
            let at_root_target = match &n {
                OutNode::Raw(s) => at_root_marker_target(s),
                _ => None,
            };
            if matches!(&n, OutNode::Raw(s) if s == MEDIA_HOIST_MARKER) {
                flush(&mut segment, &mut result, &prelude);
                if let Some(batch) = hoist_iter.next() {
                    result.extend(batch);
                }
            } else if let Some(t) = at_root_target {
                if t == own_depth + 1 {
                    // The batch grafts INTO this rule's own body (dart adds
                    // it to the existing node at its current end): it joins
                    // the current segment in place, splitting nothing.
                    if let Some(b) = self.at_root_hoist.pop_front() {
                        debug_assert_eq!(b.target, t);
                        segment.extend(b.nodes);
                    }
                } else if own_depth == 0 {
                    // A root-bound batch: split around it, placing it just
                    // after this rule's current segment at the root.
                    flush(&mut segment, &mut result, &prelude);
                    if let Some(b) = self.at_root_hoist.pop_front() {
                        debug_assert_eq!(b.target, t);
                        result.extend(b.nodes);
                        result.push(OutNode::Raw(
                            if b.group_end {
                                STYLE_GROUP_END
                            } else {
                                AT_ROOT_PACK_TIGHT
                            }
                            .to_string(),
                        ));
                    }
                } else {
                    // Bound further out: split and pass the marker outward.
                    flush(&mut segment, &mut result, &prelude);
                    result.push(n);
                }
            } else {
                segment.push(n);
            }
        }
        drop(hoist_iter);
        flush(&mut segment, &mut result, &prelude);
        if result.is_empty() {
            return Ok(());
        }

        // A mergeable rule nested in another media bubbles the whole batch
        // out through the enclosing rule (leaving a marker at this source
        // position); otherwise emit in place.
        if bubble_out && enclosing {
            sink.push_at_rule(OutNode::Raw(MEDIA_HOIST_MARKER.to_string()));
            self.media_hoist.push(result);
        } else {
            for n in result {
                sink.push_at_rule(n);
            }
        }
        Ok(())
    }

    /// Resolve a parsed media query list to its final string components,
    /// evaluating SassScript inside feature values.
    fn resolve_media_queries(&mut self, list: &MediaQueryList) -> Result<Vec<ResolvedQuery>, Error> {
        let mut out = Vec::with_capacity(list.queries.len());
        for q in &list.queries {
            out.push(self.resolve_media_query(q)?);
        }
        // dart-sass re-parses the RESOLVED prelude text (CssMediaQuery
        // .parseList), so interpolation may span query boundaries
        // (`scr#{"een, pri"}nt` splits into two queries). Only a prelude that
        // actually contained interpolation needs the round-trip.
        if list.queries.iter().any(media_query_has_interp) {
            let text = serialize_media_queries(&out);
            return css_media_parse_list(&text);
        }
        Ok(out)
    }

    fn resolve_media_query(&mut self, q: &MediaQuery) -> Result<ResolvedQuery, Error> {
        match q {
            MediaQuery::Type {
                modifier,
                mtype,
                conditions,
            } => {
                let mtype = self.eval_template(mtype)?;
                let modifier = match modifier {
                    Some(t) => Some(self.eval_template(t)?),
                    None => None,
                };
                let conditions = self.resolve_conditions(conditions)?;
                Ok(ResolvedQuery {
                    modifier,
                    mtype: Some(mtype),
                    conditions,
                    conjunction_and: true,
                })
            }
            MediaQuery::Condition {
                conditions,
                conjunction,
            } => Ok(ResolvedQuery {
                modifier: None,
                mtype: None,
                conditions: self.resolve_conditions(conditions)?,
                conjunction_and: matches!(conjunction, Conjunction::And),
            }),
        }
    }

    fn resolve_conditions(&mut self, conds: &[MediaInParens]) -> Result<Vec<String>, Error> {
        let mut out = Vec::with_capacity(conds.len());
        for c in conds {
            out.push(self.serialize_media_in_parens(c)?);
        }
        Ok(out)
    }

    fn serialize_media_in_parens(&mut self, c: &MediaInParens) -> Result<String, Error> {
        match c {
            MediaInParens::Feature(f) => {
                let inner = self.serialize_media_feature(f)?;
                Ok(format!("({inner})"))
            }
            MediaInParens::Not(inner) => Ok(format!("not {}", self.serialize_media_in_parens(inner)?)),
            MediaInParens::Group {
                conditions,
                conjunction,
            } => {
                let parts = self.resolve_conditions(conditions)?;
                let sep = if matches!(conjunction, Conjunction::And) {
                    " and "
                } else {
                    " or "
                };
                Ok(format!("({})", parts.join(sep)))
            }
            MediaInParens::Interp(e) => {
                let v = self.eval_expr(e)?;
                Ok(v.to_interp())
            }
        }
    }

    fn serialize_media_feature(&mut self, f: &MediaFeature) -> Result<String, Error> {
        match f {
            MediaFeature::Decl { name, value } => {
                // Media-feature names and values serialize in interpolation
                // context: a quoted string unquotes (`("min-width:#{$w}")`
                // emits `(min-width:20px)`), numbers are unchanged.
                let n = self.eval_expr(name)?.to_interp();
                match value {
                    Some(v) => {
                        let val = self.eval_expr(v)?.to_interp();
                        Ok(format!("{n}: {val}"))
                    }
                    None => Ok(n),
                }
            }
            MediaFeature::Range {
                first,
                op1,
                second,
                rest,
            } => {
                let a = self.eval_expr(first)?.to_css(self.compressed());
                let b = self.eval_expr(second)?.to_css(self.compressed());
                let mut s = format!("{a} {op1} {b}");
                if let Some((op2, third)) = rest {
                    let c = self.eval_expr(third)?.to_css(self.compressed());
                    s.push_str(&format!(" {op2} {c}"));
                }
                Ok(s)
            }
        }
    }

    /// Evaluate `@supports <condition> { body }`: serialize the structured
    /// condition canonically, run the body (bubbling like any at-rule), and emit
    /// the node — skipping emission entirely when the body produces nothing
    /// (dart-sass drops an empty/invisible `@supports`).
    fn eval_supports(
        &mut self,
        condition: &SupportsCondition,
        body: &[Stmt],
        parents: &[String],
        sink: &mut Sink<'_>,
    ) -> Result<(), Error> {
        let prelude = self.serialize_supports_condition(condition)?;
        let own_depth = self.at_rule_ctx.len();
        self.at_rule_ctx.push(AtCtx::Supports {
            prelude: prelude.clone(),
        });
        let out_body = self.eval_at_body(body, parents);
        self.at_rule_ctx.pop();
        let out_body = out_body?;
        if out_body.is_empty() {
            return Ok(());
        }
        // Split around any escaping @at-root batches (markers), wrapping each
        // segment in its own @supports copy like dart's tree rebuild.
        let mut result: Vec<OutNode> = Vec::new();
        let mut segment: Vec<OutNode> = Vec::new();
        let flush = |segment: &mut Vec<OutNode>, result: &mut Vec<OutNode>| {
            if !segment.is_empty() {
                result.push(OutNode::AtRule {
                    name: "supports".to_string(),
                    prelude: prelude.clone(),
                    body: std::mem::take(segment),
                    has_block: true,
                    lines: SrcLines::default(),
                });
            }
        };
        for n in out_body {
            let at_root_target = match &n {
                OutNode::Raw(s) => at_root_marker_target(s),
                _ => None,
            };
            if let Some(t) = at_root_target {
                if t == own_depth + 1 {
                    // Grafts INTO this rule's own body: joins the current
                    // segment in place (dart appends to the existing node).
                    if let Some(b) = self.at_root_hoist.pop_front() {
                        segment.extend(b.nodes);
                    }
                } else if own_depth == 0 {
                    flush(&mut segment, &mut result);
                    if let Some(b) = self.at_root_hoist.pop_front() {
                        result.extend(b.nodes);
                        result.push(OutNode::Raw(
                            if b.group_end {
                                STYLE_GROUP_END
                            } else {
                                AT_ROOT_PACK_TIGHT
                            }
                            .to_string(),
                        ));
                    }
                } else {
                    flush(&mut segment, &mut result);
                    result.push(n);
                }
            } else {
                segment.push(n);
            }
        }
        flush(&mut segment, &mut result);
        for n in result {
            sink.push_at_rule(n);
        }
        Ok(())
    }

    /// Serialize a `@supports` condition to its canonical CSS string
    /// (dart-sass `_visitSupportsCondition`).
    fn serialize_supports_condition(&mut self, condition: &SupportsCondition) -> Result<String, Error> {
        match condition {
            SupportsCondition::Operation { left, right, op } => {
                let l = self.parenthesize_supports(left, Some(*op))?;
                let r = self.parenthesize_supports(right, Some(*op))?;
                let word = if matches!(op, Conjunction::And) {
                    "and"
                } else {
                    "or"
                };
                Ok(format!("{l} {word} {r}"))
            }
            SupportsCondition::Negation(inner) => {
                Ok(format!("not {}", self.parenthesize_supports(inner, None)?))
            }
            SupportsCondition::Interpolation(expr) => Ok(self.eval_expr(expr)?.to_interp()),
            SupportsCondition::Declaration { name, value, custom } => {
                // dart-sass evaluates BOTH the name and the value with
                // `_inSupportsDeclaration` set, so a calc in the name
                // (`(calc(0): a)`) is also kept unsimplified.
                let saved = self.in_supports_declaration;
                self.in_supports_declaration = true;
                let result = (|| {
                    let n = self.eval_expr(name)?.to_css(self.compressed());
                    let v = match value.as_ref() {
                        SupportsValue::Expr(e) => self.eval_expr(e)?.to_css(self.compressed()),
                        // A custom-property value is an unquoted string: resolve
                        // its interpolation, then apply unquoted-string
                        // serialization (`\n` -> space, post-newline spaces
                        // dropped), matching dart-sass `_visitUnquotedString`.
                        SupportsValue::Raw(tpl) => unquoted_string_css(&self.eval_template(tpl)?),
                    };
                    Ok::<_, Error>((n, v))
                })();
                self.in_supports_declaration = saved;
                let (n, v) = result?;
                let sep = if *custom { "" } else { " " };
                Ok(format!("({n}:{sep}{v})"))
            }
            SupportsCondition::Function { name, arguments } => {
                let n = self.eval_template(name)?;
                let args = self.eval_template(arguments)?;
                Ok(format!("{n}({args})"))
            }
            SupportsCondition::Anything(contents) => {
                let inner = self.eval_template(contents)?;
                Ok(format!("({inner})"))
            }
        }
    }

    /// Serialize a plain-CSS `@import` argument: the URL template followed by
    /// its canonical modifiers. Raw identifier/function runs join with single
    /// spaces; a `supports(<query>)` re-serializes its parsed condition (a
    /// declaration's own parens double as the call parens); the terminal media
    /// query list joins with `, ` when it continued a bare-identifier query.
    fn serialize_css_import(
        &mut self,
        url: &[TplPiece],
        modifiers: &[ImportModifier],
    ) -> Result<String, Error> {
        let mut out = self.eval_template(url)?;
        for m in modifiers {
            match m {
                ImportModifier::Raw(tpl) => {
                    out.push(' ');
                    out.push_str(&self.eval_template(tpl)?);
                }
                ImportModifier::Supports {
                    condition,
                    declaration,
                } => {
                    out.push(' ');
                    // The condition is an *expression* part of the modifiers
                    // interpolation in dart-sass (a `SupportsExpression` whose
                    // value is an unquoted string), so its serialized text gets
                    // the unquoted-string newline collapse — unlike a Raw
                    // modifier, which is verbatim buffer text.
                    let inner = unquoted_string_css(&self.serialize_supports_condition(condition)?);
                    if *declaration {
                        out.push_str(&format!("supports{inner}"));
                    } else {
                        out.push_str(&format!("supports({inner})"));
                    }
                }
                ImportModifier::Media { list, comma_before } => {
                    out.push_str(if *comma_before { ", " } else { " " });
                    let queries = self.resolve_media_queries(list)?;
                    out.push_str(&serialize_media_queries(&queries));
                }
            }
        }
        Ok(out)
    }

    /// dart-sass `_parenthesize`: wrap a sub-condition in parentheses when it is
    /// a negation, or an operation whose operator differs from the surrounding
    /// one (or there is no surrounding operator).
    fn parenthesize_supports(
        &mut self,
        condition: &SupportsCondition,
        operator: Option<Conjunction>,
    ) -> Result<String, Error> {
        let needs_parens = match condition {
            SupportsCondition::Negation(_) => true,
            SupportsCondition::Operation { op, .. } => match operator {
                None => true,
                Some(outer) => outer != *op,
            },
            _ => false,
        };
        let inner = self.serialize_supports_condition(condition)?;
        if needs_parens {
            Ok(format!("({inner})"))
        } else {
            Ok(inner)
        }
    }

    /// Evaluate `@keyframes`. The frame selectors are keyframe selectors, not
    /// CSS selectors: no `&`/parent resolution. We run the body with the parent
    /// context reset to root (empty parents), so frame blocks emit verbatim.
    /// The whole node bubbles to the document root like any other at-rule.
    fn eval_keyframes(
        &mut self,
        name: &str,
        prelude: &[TplPiece],
        body: &[Stmt],
        lines: SrcLines,
        sink: &mut Sink<'_>,
    ) -> Result<(), Error> {
        // A style rule nested inside a keyframe block is invalid; each frame
        // (a top-level rule in the body) may only hold declarations.
        for stmt in body {
            if let Stmt::Rule(frame) = stmt {
                for inner in &frame.body {
                    if matches!(inner, Stmt::Rule(_)) {
                        return Err(Error::unpositioned(
                            "Style rules may not be used within keyframe blocks.",
                        ));
                    }
                }
            }
        }
        let prelude = self.eval_template(prelude)?;
        let saved_kf = std::mem::replace(&mut self.in_keyframes, true);
        let own_depth = self.at_rule_ctx.len();
        self.at_rule_ctx.push(AtCtx::Keyframes {
            name: name.to_string(),
            prelude: prelude.clone(),
        });
        let out_body = self.eval_at_body(body, &[]);
        self.at_rule_ctx.pop();
        self.in_keyframes = saved_kf;
        let out_body = out_body?;
        // Pull any escaping @at-root batches out (the keyframes shell stays,
        // even empty: `@keyframes a {}` + the hoisted rules after it).
        let mut shell: Vec<OutNode> = Vec::new();
        let mut after: Vec<OutNode> = Vec::new();
        for n in out_body {
            let at_root_target = match &n {
                OutNode::Raw(s) => at_root_marker_target(s),
                _ => None,
            };
            if let Some(t) = at_root_target {
                if t == own_depth + 1 {
                    if let Some(b) = self.at_root_hoist.pop_front() {
                        shell.extend(b.nodes);
                    }
                } else if own_depth == 0 {
                    if let Some(b) = self.at_root_hoist.pop_front() {
                        after.extend(b.nodes);
                        after.push(OutNode::Raw(
                            if b.group_end {
                                STYLE_GROUP_END
                            } else {
                                AT_ROOT_PACK_TIGHT
                            }
                            .to_string(),
                        ));
                    }
                } else {
                    after.push(n);
                }
            } else {
                shell.push(n);
            }
        }
        sink.push_at_rule(OutNode::AtRule {
            name: name.to_string(),
            prelude,
            body: shell,
            has_block: true,
            lines,
        });
        for n in after {
            sink.push_at_rule(n);
        }
        Ok(())
    }

    /// Evaluate `@at-root`: hoist the body's output to the document root. The
    /// parent-selector context is KEPT — dart resolves `&` against the
    /// enclosing rule but disables the implicit parent join
    /// (`implicitParent: !_atRootExcludingStyleRule`), so `@at-root & {…}`
    /// re-emits the parent at the root while `@at-root .x {…}` stays `.x`.
    /// The optional query is accepted but not yet honoured (the common
    /// no-query case is supported).
    fn eval_at_root(
        &mut self,
        query: Option<&[TplPiece]>,
        body: &[Stmt],
        parents: &[String],
        sink: &mut Sink<'_>,
    ) -> Result<(), Error> {
        let query_text = match query {
            Some(tpl) => Some(self.eval_template(tpl)?),
            None => None,
        };
        let q = AtRootQuery::parse(query_text.as_deref());
        // Which enclosing at-rule layers the query keeps vs excludes (dart
        // `AtRootQuery.excludes`). The topmost excluded layer is the graft
        // target (dart `_trimIncluded`): kept layers ABOVE it stay in place
        // (the batch re-enters inside the innermost of them), kept layers
        // BELOW it are copied around the hoisted body.
        let excluded: Vec<bool> = self
            .at_rule_ctx
            .iter()
            .map(|c| q.excludes_name(c.query_name()))
            .collect();
        let first_excluded = excluded.iter().position(|&e| e);
        let any_excluded_layer = first_excluded.is_some();
        // `(with: all)`-style queries that exclude nothing run in place.
        if !any_excluded_layer && !q.excludes_style_rules() {
            return self.exec(body, parents, sink);
        }

        self.push_scope(false);
        let saved = self.at_root_excluding_style_rule;
        self.at_root_excluding_style_rule = q.excludes_style_rules();
        // An excluded media layer also stops feeding the body's own @media
        // merging; an excluded keyframes layer drops the keyframe context.
        let saved_media = if q.excludes_name("media") {
            Some(std::mem::take(&mut self.media_queries))
        } else {
            None
        };
        let saved_kf = if q.excludes_name("keyframes") {
            Some(std::mem::replace(&mut self.in_keyframes, false))
        } else {
            None
        };
        let mut out: Vec<OutNode> = Vec::new();
        let res = {
            let mut child = Sink::AtRoot(&mut out);
            self.exec(body, parents, &mut child)
        };
        self.at_root_excluding_style_rule = saved;
        if let Some(m) = saved_media {
            self.media_queries = m;
        }
        if let Some(k) = saved_kf {
            self.in_keyframes = k;
        }
        self.pop_scope();
        res?;

        // A declaration inside `@at-root` that no style rule wraps lands at
        // the document root, which dart rejects ("Declarations may only be
        // used within style rules." — issue_1585's `@at-root { @content }`).
        if (q.excludes_style_rules() || parents.is_empty())
            && out.iter().any(|n| matches!(n, OutNode::AtDecl { .. }))
        {
            return Err(Error::unpositioned(
                "Declarations may only be used within style rules.",
            ));
        }

        // When the query KEEPS style rules, bare declarations re-wrap in the
        // enclosing selectors (dart's included CssStyleRule copy):
        // `a { @at-root (without: media) { b: c } }` emits `a { b: c }`.
        let out = if !q.excludes_style_rules() && !parents.is_empty() {
            let mut wrapped: Vec<OutNode> = Vec::new();
            let mut decls: Vec<OutItem> = Vec::new();
            let flush = |decls: &mut Vec<OutItem>, wrapped: &mut Vec<OutNode>| {
                if !decls.is_empty() {
                    wrapped.push(OutNode::Rule {
                        selectors: parents.to_vec(),
                        linebreaks: Vec::new(),
                        items: std::mem::take(decls),
                        lines: SrcLines::default(),
                        extend_base: usize::MAX,
                    });
                }
            };
            for n in out {
                match n {
                    OutNode::AtDecl {
                        prop,
                        value,
                        important,
                        custom,
                        lines,
                    } => decls.push(OutItem::Decl {
                        prop,
                        value,
                        important,
                        custom,
                        lines,
                    }),
                    other => {
                        flush(&mut decls, &mut wrapped);
                        wrapped.push(other);
                    }
                }
            }
            flush(&mut decls, &mut wrapped);
            wrapped
        } else {
            out
        };

        // Hoisted root-level nodes separate with a blank line only after a
        // completed style rule (dart's isGroupEnd: `#inc {…}` → blank →
        // `@supports`, but `@supports {…}` → `@foo` packs tight).
        let mut spaced: Vec<OutNode> = Vec::new();
        let mut prev_was_rule = false;
        for node in out {
            if prev_was_rule {
                spaced.push(OutNode::Blank);
            }
            prev_was_rule = matches!(node, OutNode::Rule { .. });
            spaced.push(node);
        }
        if spaced.is_empty() {
            return Ok(());
        }
        if let Some(te) = first_excluded {
            // Escape the excluded at-rules: re-wrap the body in the kept
            // layers BELOW the graft target (innermost-last) and leave a
            // marker; each enclosing layer below the target splits around it
            // and passes it outward until the target layer consumes it.
            let mut batch = spaced;
            for (i, layer) in self.at_rule_ctx.iter().enumerate().rev() {
                if i > te && !excluded[i] {
                    batch = vec![layer.wrap(batch)];
                }
            }
            self.at_root_hoist.push_back(AtRootBatch {
                target: te,
                group_end: parents.is_empty(),
                nodes: batch,
            });
            sink.push_at_rule(OutNode::Raw(format!("{AT_ROOT_HOIST_MARKER}{te}")));
        } else {
            // No layer escaped: the body stays inside the enclosing at-rules
            // (only the style-rule join was disabled), so emit in place.
            for node in spaced {
                sink.push_at_rule(node);
            }
        }
        Ok(())
    }

    fn eval_decl(&mut self, d: &Declaration) -> Result<Option<OutItem>, Error> {
        let name = self.eval_template(&d.property)?.trim().to_string();
        let prop = match &self.decl_prefix {
            Some(prefix) => format!("{prefix}-{name}"),
            None => name,
        };
        let value = self.eval_expr(&d.value)?;
        if matches!(value, Value::Null) {
            return Ok(None);
        }
        // A map is not a valid CSS value (even when nested inside a list).
        if let Some(m) = find_map(&value) {
            return Err(Error::at(
                format!("{} isn't a valid CSS value.", m.to_css(false)),
                d.pos,
            ));
        }
        // A first-class function reference is likewise not a valid CSS value.
        if let Value::Function(f) = &value {
            return Err(Error::at(
                format!("{} isn't a valid CSS value.", f.inspect()),
                d.pos,
            ));
        }
        // A first-class mixin reference is likewise not a valid CSS value.
        if let Value::Mixin(m) = &value {
            return Err(Error::at(
                format!("{} isn't a valid CSS value.", m.inspect()),
                d.pos,
            ));
        }
        // An empty unbracketed list (`()`, or e.g. `list.join((), ())`) cannot
        // serialize as a CSS value; a bracketed `[]` is fine, as is any list
        // with at least one element.
        if let Value::List(l) = &value {
            if l.items.is_empty() && !l.bracketed {
                return Err(Error::at("() isn't a valid CSS value.", d.pos));
            }
        }
        let vstr = value.to_css(self.compressed());
        // A value that serializes to nothing (an empty unquoted string, an
        // all-`null` list) drops the whole declaration, like a `null` value.
        if vstr.is_empty() {
            return Ok(None);
        }
        Ok(Some(OutItem::Decl {
            prop,
            value: vstr,
            important: d.important,
            custom: false,
            lines: self.stamp(SrcLines {
                file: 0,
                start: d.pos.line as u32,
                end: d.end_line,
                col: 0,
            }),
        }))
    }

    /// Evaluate a custom-property declaration: the name and verbatim value are
    /// templates whose `#{…}` interpolation resolves; the value is otherwise
    /// emitted exactly as written (no SassScript evaluation). An empty value
    /// (`--x: ;`) still emits.
    fn eval_custom_decl(&mut self, d: &CustomDecl) -> Result<Option<OutItem>, Error> {
        let prop = self.eval_template(&d.property)?.trim().to_string();
        let value = self.eval_template(&d.value)?;
        Ok(Some(OutItem::Decl {
            prop,
            value,
            important: false,
            custom: true,
            lines: self.stamp(SrcLines {
                file: 0,
                start: d.pos.line as u32,
                end: d.end_line,
                // The name's 0-based source column caps the re-indentation
                // strip for a multi-line value (dart _writeReindentedValue).
                col: d.pos.col.saturating_sub(1) as u32,
            }),
        }))
    }

    /// Evaluate a nested property set: resolve its (already prefixed) name,
    /// emit the optional leading value as a declaration, then run the body with
    /// that name installed as the child prefix so each child declaration is
    /// namespaced `<name>-<child>` and emitted in source order.
    fn eval_property_set(
        &mut self,
        ps: &PropertySet,
        parents: &[String],
        sink: &mut Sink<'_>,
    ) -> Result<(), Error> {
        // A nested property set whose own literal name begins with `--` is
        // rejected just like a plain `--` declaration would be when nested.
        if self.decl_prefix.is_some() && literal_name_is_custom_property(&ps.property) {
            return Err(Error::at(
                "Declarations whose names begin with \"--\" may not be nested.",
                ps.pos,
            ));
        }
        let name = self.eval_template(&ps.property)?.trim().to_string();
        let full = match &self.decl_prefix {
            Some(prefix) => format!("{prefix}-{name}"),
            None => name,
        };
        // The leading value (`b: c { … }`) emits `<full>: c;` before children.
        if let Some(value_expr) = &ps.value {
            let value = self.eval_expr(value_expr)?;
            if !matches!(value, Value::Null) {
                if let Some(m) = find_map(&value) {
                    return Err(Error::at(
                        format!("{} isn't a valid CSS value.", m.to_css(false)),
                        ps.pos,
                    ));
                }
                let vstr = value.to_css(self.compressed());
                sink.push_item(OutItem::Decl {
                    prop: full.clone(),
                    value: vstr,
                    important: ps.important,
                    custom: false,
                    // No usable end line of its own (the value precedes the
                    // `{…}` block); the trailing-comment rule stays disabled.
                    lines: SrcLines::default(),
                });
            }
        }
        let saved = self.decl_prefix.replace(full);
        let result = self.exec(&ps.body, parents, sink);
        self.decl_prefix = saved;
        result
    }

    /// Evaluate an `@import` statement into `sink`. Sass arguments are parsed
    /// and inlined under the current `parents` (so a nested `@import` bubbles
    /// like an inline block); plain CSS arguments are emitted verbatim as
    /// `@import …;` in source order.
    fn eval_imports(
        &mut self,
        args: &[ImportArg],
        parents: &[String],
        sink: &mut Sink<'_>,
    ) -> Result<(), Error> {
        let importer = self.options.importer;
        for arg in args {
            match arg {
                ImportArg::Css { url, modifiers } => {
                    let text = self.serialize_css_import(url, modifiers)?;
                    // Inside a style rule the plain-CSS @import stays in the
                    // rule's block (dart keeps it nested:
                    // `foo { @import url(...); }`); at the top level it is a
                    // Raw node subject to import hoisting.
                    if matches!(sink, Sink::Rule { .. }) {
                        sink.push_item(OutItem::ChildlessAtRule {
                            name: "import".to_string(),
                            prelude: text,
                            lines: SrcLines::default(),
                        });
                    } else {
                        sink.push_at_rule(OutNode::Raw(format!("@import {text};")));
                    }
                }
                ImportArg::Sass { path, pos, length } => {
                    if is_css_import(path) {
                        sink.push_at_rule(OutNode::Raw(format!("@import \"{path}\";")));
                        continue;
                    }
                    // Every Sass `@import` of a non-CSS file fires the `[import]`
                    // deprecation, pointing at the quoted URL token.
                    self.emit_deprecation(&crate::deprecation::Deprecation::import(), *pos, *length);
                    let base = self.current_file_dir.clone();
                    // Per-compile import cache (dart-sass ImportCache): the
                    // same URL imported from the same base directory shares
                    // one resolution + parse; the body still EXECUTES per
                    // import (Sass semantics). Misses and parse errors are
                    // not cached — they re-error identically.
                    let cache_key = (path.clone(), base.clone());
                    let entry = match self.import_cache.get(&cache_key) {
                        Some(e) => {
                            if self.loading.iter().any(|p| p == path) {
                                return Err(Error::unpositioned("This file is already being loaded."));
                            }
                            Some(e.clone())
                        }
                        None => {
                            // Run the caller's importer outside the arena scope
                            // so any state it caches (paths, sources) outlives
                            // this compile's arena reset; see the matching note
                            // in `load_module`.
                            let saved = crate::arena::pause();
                            let resolved =
                                importer.and_then(|imp| imp.resolve_import_with_path(path, base.as_deref()));
                            crate::arena::resume(saved);
                            match resolved {
                                Some((resolved_key, src, syntax)) => {
                                    if self.loading.iter().any(|p| p == path) {
                                        return Err(Error::unpositioned(
                                            "This file is already being loaded.",
                                        ));
                                    }
                                    let sheet = parse_with_syntax(&src, syntax)?;
                                    let e = std::rc::Rc::new((resolved_key, syntax, sheet));
                                    self.import_cache.insert(cache_key, e.clone());
                                    Some(e)
                                }
                                None => None,
                            }
                        }
                    };
                    match entry {
                        Some(entry) => {
                            let (resolved_key, syntax, sheet) = (&entry.0, entry.1, &entry.2);
                            // A plain-CSS file imports as plain CSS: nesting
                            // preserved, no Sass evaluation (same as `@use`).
                            if matches!(syntax, Syntax::Css) {
                                self.loading.push(path.clone());
                                let result = self.exec_css(&sheet.stmts, parents, sink);
                                self.loading.pop();
                                result?;
                                continue;
                            }
                            self.loading.push(path.clone());
                            // `@import` inlines the file's variables/functions/
                            // mixins into the current scope, but its module
                            // bindings (`@use`/`@forward`) stay local to the
                            // imported file and must not leak to the importer.
                            let saved_used = std::mem::take(&mut self.used_modules);
                            let saved_star = std::mem::take(&mut self.star_modules);
                            let saved_used_user = std::mem::take(&mut self.used_user_modules);
                            let saved_star_user = std::mem::take(&mut self.star_user_modules);
                            // Nested `$var: ... !global` declarations in the
                            // imported sheet register null slots in the
                            // importing module too (dart-sass: members are
                            // statically visible).
                            {
                                let mut slots: Vec<String> = Vec::new();
                                collect_global_var_decls(&sheet.stmts, &mut slots);
                                if let Some(g) = self.scopes.first() {
                                    let mut g = g.borrow_mut();
                                    for name in slots {
                                        g.entry(name).or_insert(Value::Null);
                                    }
                                }
                            }
                            // The imported file's own `@forward`s expose members
                            // as if defined in the importer; collect them
                            // separately, then merge into the current scope.
                            let saved_fwd = std::mem::take(&mut self.forwarded);
                            // dart-sass: when the imported file loads
                            // user-defined modules (it has top-level
                            // `@use`/`@forward`), its `@forward`s see every
                            // variable visible at the import — all scope
                            // levels, inner shadowing outer — as an implicit
                            // configuration (`toImplicitConfiguration`); a
                            // file without module loads keeps the current
                            // configuration (an enclosing `with (...)` still
                            // flows into its `!default`s). Unconsumed implicit
                            // entries are never an error.
                            let loads_modules = sheet
                                .stmts
                                .iter()
                                .any(|s| matches!(s, Stmt::Use { .. } | Stmt::Forward { .. }));
                            let saved_pending_consumed = if loads_modules {
                                let mut implicit_config: HashMap<String, (Value, bool)> = HashMap::default();
                                for scope in &self.scopes {
                                    for (k, v) in scope.borrow().iter() {
                                        implicit_config.insert(normalize_var_name(k), (v.clone(), false));
                                    }
                                }
                                Some((
                                    std::mem::replace(&mut self.pending_config, implicit_config),
                                    std::mem::take(&mut self.consumed_config),
                                    std::mem::replace(&mut self.config_is_implicit, true),
                                    std::mem::replace(&mut self.pending_config_id, 0),
                                ))
                            } else {
                                None
                            };
                            // Relative URLs inside the imported sheet resolve
                            // against ITS directory.
                            let saved_dir = if resolved_key.is_empty() {
                                self.current_file_dir.clone()
                            } else {
                                std::mem::replace(&mut self.current_file_dir, dirname_of(resolved_key))
                            };
                            let saved_clone = if loads_modules {
                                let n = self.copy_counter.get() + 1;
                                self.copy_counter.set(n);
                                self.import_clone
                                    .replace((format!("#import{n}"), std::collections::HashSet::new()))
                            } else {
                                self.import_clone.take()
                            };
                            // dart parses an imported file as a TOP-LEVEL
                            // stylesheet: a bare declaration there — even
                            // inside top-level control flow — is its parse
                            // error `expected "{".`, regardless of the
                            // @import sitting inside a rule (issue_2295).
                            fn has_top_decl(stmts: &[Stmt]) -> bool {
                                stmts.iter().any(|s| match s {
                                    Stmt::Decl(_) | Stmt::PropertySet(_) | Stmt::CustomDecl(_) => true,
                                    Stmt::If(branches) => branches.iter().any(|b| has_top_decl(&b.body)),
                                    Stmt::For { body, .. }
                                    | Stmt::Each { body, .. }
                                    | Stmt::While { body, .. } => has_top_decl(body),
                                    _ => false,
                                })
                            }
                            if has_top_decl(&sheet.stmts) {
                                return Err(Error::unpositioned("expected \"{\"."));
                            }
                            let result = self.exec(&sheet.stmts, parents, sink);
                            self.current_file_dir = saved_dir;
                            self.import_clone = saved_clone;
                            if let Some((p, c, i, id)) = saved_pending_consumed {
                                self.pending_config = p;
                                self.consumed_config = c;
                                self.config_is_implicit = i;
                                self.pending_config_id = id;
                            }
                            let imported_fwd = std::mem::replace(&mut self.forwarded, saved_fwd);
                            self.used_modules = saved_used;
                            self.star_modules = saved_star;
                            self.used_user_modules = saved_used_user;
                            self.star_user_modules = saved_star_user;
                            self.loading.pop();
                            result?;
                            // A `@forward`ed member from the imported file becomes
                            // an ordinary member of the importing scope: dart's
                            // @import is textual inclusion, so each forwarded
                            // callable rebinds to the IMPORT SITE's environment
                            // and lands in the innermost frame (a nested
                            // import's members stay scoped to the enclosing
                            // rule and pop with it).
                            if self.scopes.len() == 1 {
                                for (k, f) in imported_fwd.functions {
                                    let rebound = self.capture_callable(&f.def);
                                    self.define_function(&k, rebound);
                                }
                                for (k, m) in imported_fwd.mixins {
                                    let rebound = self.capture_callable(&m.def);
                                    self.define_mixin(&k, rebound);
                                }
                                if let Some(g) = self.scopes.first() {
                                    let mut g = g.borrow_mut();
                                    for (k, val) in imported_fwd.vars {
                                        // The forwarded module's assignments
                                        // behave as if written at the import:
                                        // they overwrite an existing
                                        // user-defined global (`$a: shadowed;
                                        // @import "fwd"` sees the forwarded
                                        // value afterwards) — but a global a
                                        // previous forward-merge created stays
                                        // bound to its module, so re-importing
                                        // the SAME module must not clobber an
                                        // intervening assignment, while a
                                        // forward from a DIFFERENT module
                                        // overrides it (sass/dart-sass#888).
                                        let src_ptr =
                                            imported_fwd.var_src.get(&k).map(|p| *p as usize).unwrap_or(0);
                                        match self.forwarded_globals.get(&k) {
                                            Some(prev) if *prev == src_ptr => {
                                                g.entry(k).or_insert(val);
                                            }
                                            _ => {
                                                self.forwarded_globals.insert(k.clone(), src_ptr);
                                                g.insert(k, val);
                                            }
                                        }
                                    }
                                }
                            } else {
                                // A nested `@import`'s forwarded variables join
                                // the enclosing rule's scope (so a following
                                // nested import's implicit configuration sees
                                // them, and a local assignment updates them);
                                // its forwarded functions/mixins land in the
                                // innermost frame, scoped to the enclosing
                                // rule (they pop with it, like dart).
                                if let Some(s) = self.scopes.last() {
                                    let mut s = s.borrow_mut();
                                    for (k, val) in imported_fwd.vars {
                                        s.insert(k, val);
                                    }
                                }
                                for (k, f) in imported_fwd.functions {
                                    let rebound = self.capture_callable(&f.def);
                                    self.define_function(&k, rebound);
                                }
                                for (k, m) in imported_fwd.mixins {
                                    let rebound = self.capture_callable(&m.def);
                                    self.define_mixin(&k, rebound);
                                }
                            }
                        }
                        None => {
                            return Err(Error::unpositioned(format!(
                                "Can't find stylesheet to import: {path}"
                            )));
                        }
                    }
                }
            }
        }
        Ok(())
    }

    // ---- templates & expressions ------------------------------------

    fn eval_template(&mut self, pieces: &[TplPiece]) -> Result<String, Error> {
        let mut s = String::new();
        for piece in pieces {
            match piece {
                TplPiece::Lit(t) => s.push_str(t),
                TplPiece::Interp(e) => {
                    let v = self.eval_expr(e)?;
                    s.push_str(&v.to_interp());
                }
            }
        }
        Ok(s)
    }

    /// Like [`Self::eval_template`], additionally returning each `Interp`
    /// piece's (char start, char length) range in the output — used to decide
    /// whether a resolved-selector error column falls inside interpolated
    /// text (the dual-span "error in interpolated output" diagnostic).
    fn eval_template_bounds(&mut self, pieces: &[TplPiece]) -> Result<(String, Vec<(usize, usize)>), Error> {
        let mut s = String::new();
        let mut chars = 0usize;
        let mut bounds = Vec::new();
        for piece in pieces {
            match piece {
                TplPiece::Lit(t) => {
                    s.push_str(t);
                    chars += t.chars().count();
                }
                TplPiece::Interp(e) => {
                    let v = self.eval_expr(e)?;
                    let out = v.to_interp();
                    let len = out.chars().count();
                    bounds.push((chars, len));
                    s.push_str(&out);
                    chars += len;
                }
            }
        }
        Ok((s, bounds))
    }

    /// The value of `&` in value position: the current resolved selector list
    /// as a comma-separated Sass list where each item is one complex selector
    /// (a space-separated list of compound-selector strings). At the document
    /// root (no enclosing style rule) this is `null`. This matches dart-sass,
    /// where `&` is always a comma list even for a single selector.
    fn parent_selector_value(&self) -> Value {
        let Some(selectors) = &self.current_selector else {
            return Value::Null;
        };
        if selectors.is_empty() {
            return Value::Null;
        }
        let items: Vec<Value> = selectors
            .iter()
            .map(|complex| {
                // Every complex selector is a SPACE LIST of compounds (dart:
                // `meta.type-of(list.nth(&, 1))` is `list` even for `.foo`).
                let compounds: Vec<Value> = complex
                    .split_whitespace()
                    .map(|c| {
                        Value::Str(SassStr {
                            text: c.to_string(),
                            quoted: false,
                        })
                    })
                    .collect();
                Value::List(List {
                    items: compounds,
                    sep: ListSep::Space,
                    bracketed: false,
                    keywords: None,
                })
            })
            .collect();
        Value::List(List {
            items,
            sep: ListSep::Comma,
            bracketed: false,
            keywords: None,
        })
    }

    fn eval_expr(&mut self, expr: &Expr) -> Result<Value, Error> {
        // Finalize any positioned error into a rendered diagnostic block here,
        // where `current_url`/`current_source`/`call_stack` still describe the
        // file and call context the error was raised in (cross-file safe).
        match self.eval_expr_inner(expr) {
            Ok(v) => Ok(v),
            Err(e) => Err(self.finalize_error(e)),
        }
    }

    fn eval_expr_inner(&mut self, expr: &Expr) -> Result<Value, Error> {
        match expr {
            Expr::Number(v, unit) => Ok(Value::Number(Number::with_unit(*v, unit.clone()))),
            Expr::Color(c) => Ok(Value::Color(c.clone())),
            Expr::Bool(b) => Ok(Value::Bool(*b)),
            Expr::Null => Ok(Value::Null),
            Expr::Parent => Ok(self.parent_selector_value()),
            // Reading a variable drops a bare slash-division's spelling
            // (dart-sass `withoutSlash`): `$x: 1/2; a {b: $x}` is `0.5`.
            // Slashes nested inside a stored list are preserved.
            Expr::Var { name, pos } => match self.lookup(name) {
                // `lookup` already returns an owned clone out of the scope;
                // `without_slash` consumes it, so a second clone is wasted.
                Some(v) => Ok(v.without_slash()),
                None => {
                    // A user module variable exposed unprefixed via `@use … as *`.
                    let star_hits: Vec<Value> = if is_private_member(name) {
                        Vec::new()
                    } else {
                        self.star_user_modules
                            .iter()
                            .filter_map(|m| m.var(name))
                            .collect()
                    };
                    if star_hits.len() > 1 {
                        return Err(Error::at(
                            "This variable is available from multiple global modules.",
                            *pos,
                        ));
                    }
                    if let Some(v) = star_hits.into_iter().next() {
                        return Ok(v.without_slash());
                    }
                    // A built-in module variable exposed unprefixed via
                    // `@use "sass:…" as *` (e.g. `$pi` from `sass:math`).
                    for m in &self.star_modules {
                        if let Ok(v) = crate::builtins::module_var(m, name, *pos) {
                            return Ok(v);
                        }
                    }
                    // The caret covers `$name` (the `$` plus the identifier).
                    Err(Error::at("Undefined variable.", *pos).with_length(1 + name.len()))
                }
            },
            Expr::NsVar { module, name } => self.eval_module_var(module, name, Pos { line: 1, col: 1 }),
            // A string expression (quoted/unquoted/lone-interpolation) resolves
            // its interpolation in a context where the `@supports`-declaration
            // no-simplify flag is OFF, so `(a: #{calc(1 + 2)})` -> `(a: 3)`
            // (the interpolated calc simplifies), matching dart-sass
            // `visitStringExpression`.
            Expr::QuotedString(pieces) => {
                let saved = std::mem::replace(&mut self.in_supports_declaration, false);
                let text = self.eval_template(pieces);
                self.in_supports_declaration = saved;
                Ok(Value::Str(SassStr {
                    text: text?,
                    quoted: true,
                }))
            }
            Expr::Ident(pieces) => {
                let saved = std::mem::replace(&mut self.in_supports_declaration, false);
                let text = self.eval_template(pieces);
                self.in_supports_declaration = saved;
                Ok(Value::Str(SassStr {
                    text: text?,
                    quoted: false,
                }))
            }
            Expr::Interp(inner) => {
                let saved = std::mem::replace(&mut self.in_supports_declaration, false);
                let v = self.eval_expr(inner);
                self.in_supports_declaration = saved;
                Ok(Value::Str(SassStr {
                    text: v?.to_interp(),
                    quoted: false,
                }))
            }
            Expr::ModernIf(clauses) => self.eval_modern_if(clauses),
            // Parentheses force the deprecated slash to perform real
            // division: `(1/2)` is `0.5`, not the slash value `1/2`.
            Expr::Paren(inner) => Ok(self.eval_expr(inner)?.without_slash()),
            Expr::List {
                items,
                sep,
                bracketed,
            } => {
                let mut vals = Vec::with_capacity(items.len());
                for it in items {
                    vals.push(self.eval_expr(it)?);
                }
                Ok(Value::List(List {
                    items: vals,
                    sep: *sep,
                    bracketed: *bracketed,
                    keywords: None,
                }))
            }
            Expr::Map(entries) => {
                let mut map = Map { entries: Vec::new() };
                for (k, v) in entries {
                    let key = self.eval_expr(k)?.without_slash();
                    let val = self.eval_expr(v)?;
                    // A duplicate literal key is an error in dart-sass.
                    if map.get(&key).is_some() {
                        return Err(Error::unpositioned("Duplicate key."));
                    }
                    map.insert(key, val);
                }
                Ok(Value::Map(map))
            }
            Expr::Unary { op, operand } => {
                let v = self.eval_expr(operand)?.without_slash();
                match op {
                    // Unary minus negates a number; on any other operand
                    // dart-sass produces an unquoted `-<value>` string
                    // (`- red` -> `-red`, `- "q"` -> `-"q"`). A calculation that
                    // could not reduce to a number has no negation operator, so
                    // dart-sass rejects it ("Undefined operation \"-calc(…)\".").
                    UnOp::Neg => match v {
                        Value::Number(n) => Ok(Value::Number(n.copy_units(-n.value))),
                        Value::Calc(_) => Err(Error::unpositioned(format!(
                            "Undefined operation \"-{}\".",
                            v.to_css(false)
                        ))),
                        other => Ok(Value::Str(SassStr {
                            text: format!("-{}", other.to_css(false)),
                            quoted: false,
                        })),
                    },
                    // Unary plus is numeric identity; on any other operand it
                    // prepends `+` as an unquoted string (`+foo` -> `+foo`). A
                    // residual calculation has no unary-plus operator and is
                    // rejected the same way.
                    UnOp::Plus => match v {
                        Value::Number(_) => Ok(v),
                        Value::Calc(_) => Err(Error::unpositioned(format!(
                            "Undefined operation \"+{}\".",
                            v.to_css(false)
                        ))),
                        other => Ok(Value::Str(SassStr {
                            text: format!("+{}", other.to_css(false)),
                            quoted: false,
                        })),
                    },
                    UnOp::Not => Ok(Value::Bool(!v.is_truthy())),
                }
            }
            Expr::Binary { op, lhs, rhs, pos } => {
                // `and`/`or` short-circuit and yield a value, so the
                // right operand is only evaluated when needed.
                let l = self.eval_expr(lhs)?;
                match op {
                    BinOp::And => {
                        if l.is_truthy() {
                            self.eval_expr(rhs)
                        } else {
                            Ok(l)
                        }
                    }
                    BinOp::Or => {
                        if l.is_truthy() {
                            Ok(l)
                        } else {
                            self.eval_expr(rhs)
                        }
                    }
                    _ => {
                        let r = self.eval_expr(rhs)?;
                        eval_binary(*op, l.without_slash(), r.without_slash(), *pos)
                    }
                }
            }
            Expr::Div {
                lhs, rhs, slash, pos, ..
            } => {
                let l = self.eval_expr(lhs)?;
                let r = self.eval_expr(rhs)?;
                eval_div(l, r, *slash, *pos)
            }
            Expr::Calc { inner, .. } => {
                // dart resolves user functions BEFORE calculation semantics: a
                // user-defined `@function calc(...)` shadows the CSS
                // calculation (issue_1706), receiving the argument evaluated
                // as an ordinary expression. Vendor-prefixed `-x-calc(` stays
                // a parse-time special function and can't be overridden.
                if !self.in_plain_css {
                    if let Some(callable) = self.lookup_function("calc") {
                        let arg = self.eval_expr(inner)?.without_slash();
                        let f = crate::value::SassFunction {
                            name: "calc".to_string(),
                            css: false,
                            user: Some(callable as Rc<dyn std::any::Any>),
                        };
                        return self
                            .invoke_function_ref(&f, vec![arg], Vec::new(), Pos { line: 0, col: 0 })
                            .map(Value::without_slash);
                    }
                }
                let node = self.eval_calc(inner)?;
                // Inside a `@supports` declaration the calculation is kept
                // unsimplified: the `calc()` wrapper is always preserved (even
                // around a single number), matching dart-sass `simplify: false`.
                if self.in_supports_declaration {
                    return Ok(Value::Calc(node));
                }
                // A calculation that reduces to a single finite number unwraps
                // to it; a non-finite result (infinity/NaN) stays a
                // calculation so it serializes as `calc(infinity)` etc., and
                // anything still containing an operation stays a calculation.
                match node {
                    // A calculation that reduces to a single number unwraps to
                    // it — including a non-finite result (dart-sass:
                    // `meta.type-of(calc(NaN)) == number`); the Number's own
                    // serialization restores the `calc(NaN)`/`calc(infinity *
                    // 1px)` spelling.
                    CalcNode::Number(n) => Ok(Value::Number(n)),
                    // `calc()` wrapping a single already-complete calculation
                    // (`calc(min(1%, 2px))`, `calc(clamp(…))`, etc.) is
                    // redundant: dart-sass drops the outer `calc()` and emits
                    // the inner calculation directly. (A non-calculation leaf
                    // such as `calc(var(--x))` keeps its wrapper.)
                    CalcNode::Str(s) if is_complete_calculation(&s) => Ok(Value::Str(SassStr {
                        text: s,
                        quoted: false,
                    })),
                    other => Ok(Value::Calc(other)),
                }
            }
            // An interpolated-name call is a *plain CSS* function (dart-sass
            // `PlainCssCallable`): the resolved name is never dispatched to a
            // built-in or user function; the arguments evaluate and the call
            // serializes verbatim. Keyword arguments are rejected.
            Expr::InterpFunc { name, args, pos } => {
                let fname = self.eval_template(name)?;
                if args.iter().any(|a| a.name.is_some()) {
                    return Err(Error::at(
                        "Plain CSS functions don't support keyword arguments.",
                        *pos,
                    ));
                }
                let mut parts: Vec<String> = Vec::with_capacity(args.len());
                for a in args {
                    let v = self.eval_expr(&a.value)?;
                    parts.push(v.to_css(self.compressed()));
                }
                Ok(Value::Str(SassStr {
                    text: format!("{fname}({})", parts.join(", ")),
                    quoted: false,
                }))
            }
            Expr::Func {
                name,
                args,
                pos,
                length,
                module,
            } => {
                // A namespaced call `ns.fn(...)` resolves only against the used
                // built-in module bound to `ns`.
                if let Some(ns) = module {
                    return self.eval_module_call(ns, name, args, *pos, *length);
                }
                // In a plain-CSS module no function is invoked (dart-sass
                // `plainCss` looks none up): the call re-serializes verbatim
                // with its arguments evaluated. CSS calculations (min/max/…)
                // still simplify through their normal paths below.
                if self.in_plain_css
                    && !is_supports_calc_function(name)
                    && !name.eq_ignore_ascii_case("calc")
                    && !args.iter().any(|a| a.splat || a.name.is_some())
                {
                    let mut parts: Vec<String> = Vec::with_capacity(args.len());
                    for a in args {
                        parts.push(self.eval_expr(&a.value)?.to_css(self.compressed()));
                    }
                    return Ok(Value::Str(SassStr {
                        text: format!("{name}({})", parts.join(", ")),
                        quoted: false,
                    }));
                }
                // Inside a `@supports` declaration, a CSS math function
                // (`min`/`max`/`clamp`/…) is kept unsimplified: its arguments
                // are resolved through the (non-folding) calc machinery and the
                // call is serialized verbatim, matching dart-sass
                // `simplify: false`. A user-defined function of the same name
                // still wins, so this only applies to builtins.
                if self.in_supports_declaration
                    && is_supports_calc_function(name)
                    && self.lookup_function(name).is_none()
                {
                    return self.eval_supports_calc_func(name, args, *pos);
                }
                // if() is lazy: only the selected branch is evaluated.
                if name == "if" {
                    return self.eval_if_function(args, *pos);
                }
                // User-defined @function takes precedence over builtins — but
                // a `--`-prefixed call is always plain CSS (dart reserves it
                // for custom functions), even though `@function __a`
                // normalizes to the same `--a` key.
                if !name.starts_with("--") {
                    if let Some(func) = self.lookup_function(name) {
                        return self.call_function(&func, args, Some((*pos, *length)));
                    }
                }
                // A user module function exposed unprefixed via `@use … as *`.
                if !self.star_user_modules.is_empty() && !is_private_member(name) {
                    let hits: Vec<(Rc<Module>, Rc<UserCallable>)> = self
                        .star_user_modules
                        .iter()
                        .filter_map(|m| m.function(name).map(|f| (Rc::clone(m), f)))
                        .collect();
                    if hits.len() > 1 {
                        return Err(Error::at(
                            "This function is available from multiple global modules.".to_string(),
                            *pos,
                        ));
                    }
                    if let Some((m, f)) = hits.into_iter().next() {
                        return self.call_user_module_function(&m, &f, args, Some((*pos, *length)));
                    }
                }
                // A bare `calc()` reaches here as a plain call (the parser only
                // treats `calc(<arg>)` as a calculation), so a user
                // `@function calc()` could have handled it above. With no user
                // override it is the CSS `calc()`, which requires an argument.
                if name.eq_ignore_ascii_case("calc") && args.is_empty() {
                    return Err(Error::at("Missing argument.", *pos));
                }
                // The pure CSS-calculation functions are parsed as
                // calculations, which cannot take a `...` rest argument.
                if is_calc_function(name) && args.iter().any(|a| a.splat) {
                    return Err(Error::at("Rest arguments can't be used with calculations.", *pos));
                }
                // The single-/double-argument math calculations (`sin`, `cos`,
                // `sqrt`, `pow`, `log`, `hypot`, …) parse their arguments as
                // calculation expressions, not ordinary SassScript. That means a
                // disallowed operator (`%`, comparison) inside an argument is
                // rejected ("This operation can't be used in a calculation."),
                // and an argument that does not reduce to a single number — it
                // still references a `var()`/interpolation/unknown ident — keeps
                // the whole call as a preserved calculation
                // (`sin(2px + var(--c))`) rather than erroring. When every
                // argument reduces to a plain number the normal builtin path
                // computes the result (and applies its unit checks), so this only
                // changes the two calc-specific behaviours above.
                if is_pure_calc_math_function(name)
                    && self.lookup_function(name).is_none()
                    && !args.iter().any(|a| a.splat || a.name.is_some())
                {
                    if let Some(v) = self.try_eval_calc_math_call(name, args, *pos)? {
                        return Ok(v);
                    }
                }
                // `calc-size()` is a two-argument calculation: a sizing keyword
                // (or `var()`/calculation) plus a calculation, always preserved.
                if name.eq_ignore_ascii_case("calc-size")
                    && self.lookup_function(name).is_none()
                    && !args.iter().any(|a| a.splat || a.name.is_some())
                {
                    return self.eval_calc_size(args, *pos);
                }
                // A three-argument `clamp()` evaluates its bounds and value as
                // calculations, so a `var()`/operation argument (`1% + 1px`)
                // keeps the call preserved instead of erroring as Sass
                // arithmetic. Other arities (a preserved single argument, or an
                // arity error) fall through to the builtin.
                if name.eq_ignore_ascii_case("clamp")
                    && self.lookup_function(name).is_none()
                    && args.len() == 3
                    && !args.iter().any(|a| a.splat || a.name.is_some())
                {
                    return self.try_eval_clamp(args, *pos);
                }
                // `abs()` is a legacy global function that also exists as the CSS
                // `abs()` calculation. When its single positional argument
                // references a `var()`/interpolation it is parsed as a
                // calculation and preserved with its numeric subtree folded
                // (`abs(1px + 2px - var(--c))` -> `abs(3px - var(--c))`).
                // Without such a substitution the argument resolves to a plain
                // number, so the deprecated `math.abs` global handles it as
                // before (`abs(1 + 1px)` -> `2px`, `abs(-3) -> 3`).
                if name.eq_ignore_ascii_case("abs")
                    && self.lookup_function(name).is_none()
                    && args.len() == 1
                    && args[0].name.is_none()
                    && !args[0].splat
                    && expr_contains_calc_substitution(&args[0].value)
                {
                    let node = self.eval_calc(&args[0].value)?;
                    return Ok(Value::Str(SassStr {
                        text: format!("abs({})", node.to_calc_css(self.compressed())),
                        quoted: false,
                    }));
                }
                // `round()` is likewise the CSS round() calculation: each
                // argument evaluates as a calculation (so `1.4px + var(--c)`
                // keeps its `+` with the numeric subtree folded, and
                // `1px + 4px` folds to `5px`). If every argument simplifies
                // (numbers, plus a leading strategy keyword), the normal
                // builtin computes the result; otherwise the call is
                // preserved. Calc-incompatible SassScript (`7 % 3`) falls back
                // to the legacy one-argument `math.round` (arity errors and
                // all).
                if name.eq_ignore_ascii_case("round")
                    && self.lookup_function(name).is_none()
                    && (1..=3).contains(&args.len())
                    && !args.iter().any(|a| a.splat || a.name.is_some())
                {
                    // A SassScript-only operator (`7 % 3`) makes the call a
                    // plain function, and the only plain `round` is the legacy
                    // one-argument `math.round` — multi-argument forms are an
                    // arity error (dart-sass).
                    if args.iter().any(|a| expr_has_non_calc_op(&a.value)) {
                        if args.len() > 1 {
                            return Err(Error::at(
                                format!("Only 1 argument allowed, but {} were passed.", args.len()),
                                *pos,
                            ));
                        }
                        // A single argument falls through to the legacy builtin.
                    } else if let Ok(nodes) =
                        args.iter()
                            .map(|a| self.eval_calc(&a.value))
                            .collect::<Result<Vec<CalcNode>, Error>>()
                    {
                        let simplified = |i: usize, n: &CalcNode| match n {
                            CalcNode::Number(_) => true,
                            // A leading strategy keyword participates as a
                            // keyword, not an operand.
                            CalcNode::Str(s) => {
                                i == 0
                                    && nodes.len() >= 2
                                    && matches!(
                                        s.to_ascii_lowercase().as_str(),
                                        "nearest" | "up" | "down" | "to-zero"
                                    )
                            }
                            _ => false,
                        };
                        if !nodes.iter().enumerate().all(|(i, n)| simplified(i, n)) {
                            // A preserved round is a first-class Calculation
                            // (`meta.calc-name`/`calc-args` see it).
                            return Ok(Value::Calc(CalcNode::Func {
                                name: "round".to_string(),
                                args: nodes,
                            }));
                        }
                        // Fall through to the normal builtin path below.
                    }
                }
                // `min`/`max` are likewise CSS calculations: their arguments
                // fold as calc expressions, and any unsimplifiable operand
                // (`1px + var(--c)`) preserves the call with the folded
                // subtrees spelled as calc (`max(5px, 1px + var(--c))`). When
                // every argument folds to a number the builtin computes as
                // before, and SassScript-only operators (`7 % 3`) keep the
                // whole call on the legacy path.
                if (name.eq_ignore_ascii_case("min") || name.eq_ignore_ascii_case("max"))
                    && self.lookup_function(name).is_none()
                    && !args.is_empty()
                    && !args.iter().any(|a| a.splat || a.name.is_some())
                    && !args.iter().any(|a| expr_has_non_calc_op(&a.value))
                {
                    if let Ok(nodes) = args
                        .iter()
                        .map(|a| self.eval_calc(&a.value))
                        .collect::<Result<Vec<CalcNode>, Error>>()
                    {
                        if !nodes.iter().all(|n| matches!(n, CalcNode::Number(_))) {
                            // A preserved min/max is a first-class Calculation
                            // (`meta.calc-name`/`calc-args` see it).
                            return Ok(Value::Calc(CalcNode::Func {
                                name: name.to_ascii_lowercase(),
                                args: nodes,
                            }));
                        }
                    }
                    // Fall through to the normal builtin path below.
                }
                // Evaluate args, expanding any `...` splat into positional /
                // keyword arguments.
                let (mut pos_args, mut named, _) = self.eval_call_args(args)?;
                // The global (deprecated) aliases of the `sass:meta` existence
                // predicates resolve against the evaluator state, not the
                // value-only builtin layer. A user-defined function of the same
                // name still wins (checked above).
                if matches!(
                    name.as_str(),
                    "variable-exists"
                        | "global-variable-exists"
                        | "mixin-exists"
                        | "function-exists"
                        | "content-exists"
                        | "get-function"
                        | "call"
                        | "keywords"
                ) {
                    for v in &mut pos_args {
                        *v = std::mem::replace(v, Value::Null).without_slash();
                    }
                    for (_, v) in &mut named {
                        *v = std::mem::replace(v, Value::Null).without_slash();
                    }
                    if let Some(r) = self.try_meta_eval_call(name, &pos_args, &named, *pos) {
                        return r;
                    }
                }
                // The proprietary Microsoft `alpha()` filter overload: when the
                // global `alpha()` is called with one or more unquoted-string
                // arguments that each contain a `=` (an IE `alpha(opacity=80)`
                // hack, produced by the single-`=` operator), dart-sass passes
                // the call through verbatim as a CSS function instead of
                // treating the argument as a color.
                if name == "alpha"
                    && named.is_empty()
                    && !pos_args.is_empty()
                    && pos_args
                        .iter()
                        .all(|v| matches!(v, Value::Str(s) if !s.quoted && s.text.contains('=')))
                {
                    let inner = pos_args
                        .iter()
                        .map(|v| v.to_css(false))
                        .collect::<Vec<_>>()
                        .join(", ");
                    return Ok(Value::Str(SassStr {
                        text: format!("alpha({inner})"),
                        quoted: false,
                    }));
                }
                // A member exposed unprefixed via `@use "sass:<mod>" as *`: when
                // the bare name is not already a global builtin, route it to the
                // first star module that owns it (e.g. `div` -> `math.div`,
                // `set` -> `map.set`). Global builtins keep their own behaviour.
                if !crate::builtins::is_builtin(name) {
                    for m in self.star_modules.clone() {
                        if crate::builtins::module_has_member(&m, name) {
                            for v in &mut pos_args {
                                *v = std::mem::replace(v, Value::Null).without_slash();
                            }
                            for (n, v) in &mut named {
                                *v = std::mem::replace(v, Value::Null).without_slash();
                                let _ = n;
                            }
                            return crate::builtins::call_module(&m, name, &pos_args, &named, *pos)
                                .map(Value::without_slash);
                        }
                    }
                }
                // A bare slash-division argument collapses to its number when
                // passed to a real Sass function (dart-sass `withoutSlash`);
                // plain CSS functions (`foo(1/2)`) keep the slash verbatim.
                if crate::builtins::is_builtin(name) {
                    for v in &mut pos_args {
                        *v = std::mem::replace(v, Value::Null).without_slash();
                    }
                    for (_, v) in &mut named {
                        *v = std::mem::replace(v, Value::Null).without_slash();
                    }
                }
                // A function call's RESULT is slash-free too (dart applies
                // `withoutSlash()` to every call result): `list.nth(3 1/2 4,
                // 2)` returns 0.5, not the slash form.
                crate::builtins::call(name, &pos_args, &named, *pos).map(Value::without_slash)
            }
        }
    }

    /// Dispatch a namespaced call `ns.member(args)`. Resolves a user module
    /// first, then a built-in module bound to `ns`.
    fn eval_module_call(
        &mut self,
        ns: &str,
        member: &str,
        args: &[CallArg],
        pos: Pos,
        length: usize,
    ) -> Result<Value, Error> {
        // A user module bound to this namespace.
        if let Some(module) = self.used_user_modules.get(ns).cloned() {
            if is_private_member(member) {
                return Err(Error::at(
                    "Private members can't be accessed from outside their modules.".to_string(),
                    pos,
                ));
            }
            if let Some(func) = module.function(member) {
                // A forwarded function executes in its DEFINING module's
                // environment (its body closes over that module's globals).
                let exec = module.fn_origin(member).unwrap_or(module);
                return self.call_user_module_function(&exec, &func, args, Some((pos, length)));
            }
            // Fall back to a built-in re-exported by this module via @forward.
            if let Some(v) = self.try_forwarded_builtin_call(&module, member, args, pos)? {
                return Ok(v);
            }
            return Err(Error::at("Undefined function.".to_string(), pos));
        }
        // A built-in module bound to this namespace.
        let module = match self.used_modules.get(ns) {
            Some(m) => m.clone(),
            None => {
                return Err(Error::at(
                    format!("There is no module with the namespace \"{ns}\"."),
                    pos,
                ));
            }
        };
        let (mut pos_args, mut named, _) = self.eval_call_args(args)?;
        for v in &mut pos_args {
            *v = std::mem::replace(v, Value::Null).without_slash();
        }
        for (_, v) in &mut named {
            *v = std::mem::replace(v, Value::Null).without_slash();
        }
        // The `sass:meta` introspection predicates need the evaluator's scopes /
        // definitions, which the value-only `call_module` cannot see.
        if module == "meta" {
            if let Some(r) = self.try_meta_eval_call(member, &pos_args, &named, pos) {
                return r;
            }
        }
        // Call results are slash-free (dart `withoutSlash()` on every call).
        crate::builtins::call_module(&module, member, &pos_args, &named, pos).map(Value::without_slash)
    }

    /// Handle a `sass:meta` member that depends on the evaluator's state
    /// (variable/function/mixin/content existence). Returns `None` for any
    /// member this layer does not own, so the caller falls back to the
    /// value-only `call_module`. The arguments are already evaluated.
    fn try_meta_eval_call(
        &mut self,
        member: &str,
        pos_args: &[Value],
        named: &[(String, Value)],
        pos: Pos,
    ) -> Option<Result<Value, Error>> {
        match member {
            "variable-exists" => Some(self.meta_variable_exists(pos_args, named, pos, false)),
            "global-variable-exists" => Some(self.meta_variable_exists(pos_args, named, pos, true)),
            "mixin-exists" => Some(self.meta_mixin_exists(pos_args, named, pos)),
            "function-exists" => Some(self.meta_function_exists(pos_args, named, pos)),
            "content-exists" => Some(self.meta_content_exists(pos_args, pos)),
            "get-function" => Some(self.meta_get_function(pos_args, named, pos)),
            "get-mixin" => Some(self.meta_get_mixin(pos_args, named, pos)),
            "call" => Some(self.meta_call(pos_args, named, pos)),
            "module-variables" => Some(self.meta_module_members(pos_args, named, pos, MemberKind::Variable)),
            "module-functions" => Some(self.meta_module_members(pos_args, named, pos, MemberKind::Function)),
            "module-mixins" => Some(self.meta_module_members(pos_args, named, pos, MemberKind::Mixin)),
            "accepts-content" => Some(self.meta_accepts_content(pos_args, named, pos)),
            "keywords" => Some(Self::meta_keywords(pos_args, named, pos)),
            _ => None,
        }
    }

    /// `meta.keywords($args)`: the keyword arguments captured by a `$args...`
    /// rest parameter, as a map from each name (hyphen-normalized, unquoted) to
    /// its value. The argument must be an argument list, not an ordinary value.
    fn meta_keywords(pos_args: &[Value], named: &[(String, Value)], pos: Pos) -> Result<Value, Error> {
        let v = pos_args
            .first()
            .or_else(|| named.iter().find(|(n, _)| n == "args").map(|(_, v)| v))
            .ok_or_else(|| Error::at("Missing argument $args.".to_string(), pos))?;
        match v {
            Value::List(l) if l.keywords.is_some() => Ok(Value::Map(Map {
                entries: l.keywords.clone().unwrap_or_default(),
            })),
            other => Err(Error::at(
                format!("$args: {} is not an argument list.", other.to_css(false)),
                pos,
            )),
        }
    }

    /// `meta.accepts-content($mixin)`: whether the mixin reference's body uses a
    /// `@content` block. The only built-in mixin that does is `meta.apply`.
    fn meta_accepts_content(
        &self,
        pos_args: &[Value],
        named: &[(String, Value)],
        pos: Pos,
    ) -> Result<Value, Error> {
        let v = pos_args
            .first()
            .or_else(|| named.iter().find(|(n, _)| n == "mixin").map(|(_, v)| v))
            .ok_or_else(|| Error::at("Missing argument $mixin.".to_string(), pos))?;
        let mixin = match v {
            Value::Mixin(m) => m,
            other => {
                return Err(Error::at(
                    format!("$mixin: {} is not a mixin reference.", other.to_css(false)),
                    pos,
                ))
            }
        };
        let accepts = match &mixin.user {
            Some(any) => Rc::clone(any)
                .downcast::<UserCallable>()
                .map(|c| body_uses_content(&c.def.body))
                .unwrap_or(false),
            None => mixin.name == "apply",
        };
        Ok(Value::Bool(accepts))
    }

    /// `meta.get-function($name, $css: false, $module: null)`: capture a
    /// reference to the named function. A `$module` argument needs the user
    /// module loader (unsupported here) and is reported as an error. A user
    /// `@function` is captured by identity; otherwise a built-in (or, with
    /// `$css: true`, a plain-CSS) reference is returned.
    fn meta_get_function(
        &self,
        pos_args: &[Value],
        named: &[(String, Value)],
        pos: Pos,
    ) -> Result<Value, Error> {
        let params = ["name", "css", "module"];
        if pos_args.len() > params.len() {
            return Err(Error::at(
                format!(
                    "Only {} arguments allowed, but {} were passed.",
                    params.len(),
                    pos_args.len()
                ),
                pos,
            ));
        }
        let arg = |i: usize| -> Option<&Value> {
            pos_args
                .get(i)
                .or_else(|| named.iter().find(|(n, _)| n == params[i]).map(|(_, v)| v))
        };
        let name = match arg(0) {
            Some(Value::Str(s)) => s.text.clone(),
            Some(other) => {
                return Err(Error::at(
                    format!("$name: {} is not a string.", other.to_css(false)),
                    pos,
                ))
            }
            None => return Err(Error::at("Missing argument $name.", pos)),
        };
        let css = matches!(arg(1), Some(v) if v.is_truthy());
        // A `$module` namespace resolves the function from that `@use`d module.
        if let Some(module_v) = arg(2) {
            match module_v {
                Value::Null => {}
                Value::Str(s) => return self.get_function_from_module(&name, &s.text, pos),
                other => {
                    return Err(Error::at(
                        format!("$module: {} is not a string.", other.to_css(false)),
                        pos,
                    ))
                }
            }
        }
        if css {
            return Ok(Value::Function(SassFunction {
                name,
                css: true,
                user: None,
            }));
        }
        // A user `@function` of that name (dash/underscore-insensitive) wins.
        let key = normalize_arg_name(&name);
        if let Some(f) = self.lookup_function_norm(&key) {
            return Ok(Value::Function(SassFunction {
                name,
                css: false,
                user: Some(f as Rc<dyn std::any::Any>),
            }));
        }
        // A function exposed unprefixed via `@use … as *` (or forwarded into one).
        if !is_private_member(&name) {
            for m in &self.star_user_modules {
                if let Some(f) = m.function(&name) {
                    return Ok(Value::Function(SassFunction {
                        name,
                        css: false,
                        user: Some(Rc::clone(&f) as Rc<dyn std::any::Any>),
                    }));
                }
            }
        }
        if crate::builtins::is_builtin(&name) {
            return Ok(Value::Function(SassFunction {
                name,
                css: false,
                user: None,
            }));
        }
        Err(Error::at(format!("Function not found: {name}"), pos))
    }

    /// `meta.get-mixin($name, $module: null)`: capture a reference to the named
    /// mixin. A user `@mixin` is captured by identity (so a later redefinition
    /// yields a distinct reference); the built-in `sass:meta` mixins
    /// (`load-css`, `apply`) are captured by name. A `$module` argument resolves
    /// the mixin from that `@use`d module's namespace.
    fn meta_get_mixin(
        &self,
        pos_args: &[Value],
        named: &[(String, Value)],
        pos: Pos,
    ) -> Result<Value, Error> {
        let params = ["name", "module"];
        if pos_args.len() > params.len() {
            return Err(Error::at(
                format!(
                    "Only {} arguments allowed, but {} were passed.",
                    params.len(),
                    pos_args.len()
                ),
                pos,
            ));
        }
        let arg = |i: usize| -> Option<&Value> {
            pos_args
                .get(i)
                .or_else(|| named.iter().find(|(n, _)| n == params[i]).map(|(_, v)| v))
        };
        let name = match arg(0) {
            Some(Value::Str(s)) => s.text.clone(),
            Some(other) => {
                return Err(Error::at(
                    format!("$name: {} is not a string.", other.to_css(false)),
                    pos,
                ))
            }
            None => return Err(Error::at("Missing argument $name.", pos)),
        };
        // A `$module` argument resolves the mixin from another module's scope.
        if let Some(module_val) = arg(1) {
            if !matches!(module_val, Value::Null) {
                let module_name = match module_val {
                    Value::Str(s) => s.text.clone(),
                    other => {
                        return Err(Error::at(
                            format!("$module: {} is not a string.", other.to_css(false)),
                            pos,
                        ))
                    }
                };
                return self.get_mixin_from_module(&name, &module_name, pos);
            }
        }
        // A user `@mixin` of that name (dash/underscore-insensitive) wins.
        let key = normalize_arg_name(&name);
        if let Some(m) = self.lookup_mixin_norm(&key) {
            return Ok(Value::Mixin(SassMixin {
                name,
                user: Some(m as Rc<dyn std::any::Any>),
                module: None,
            }));
        }
        // A mixin exposed unprefixed via `@use … as *`. Its body runs in the
        // owning module's environment, so capture that module too.
        if !self.star_user_modules.is_empty() && !is_private_member(&name) {
            let hits: Vec<&Rc<Module>> = self
                .star_user_modules
                .iter()
                .filter(|m| m.mixin(&name).is_some())
                .collect();
            if hits.len() > 1 {
                return Err(Error::at(
                    "This mixin is available from multiple global modules.",
                    pos,
                ));
            }
            if let Some(module) = hits.into_iter().next() {
                let m = module
                    .mixin(&name)
                    .ok_or_else(|| Error::at(format!("Mixin not found: {name}"), pos))?;
                return Ok(Value::Mixin(SassMixin {
                    name,
                    user: Some(Rc::clone(&m) as Rc<dyn std::any::Any>),
                    module: Some(Rc::clone(module) as Rc<dyn std::any::Any>),
                }));
            }
        }
        Err(Error::at(format!("Mixin not found: {name}"), pos))
    }

    /// Resolve a `$module`-qualified mixin reference for `meta.get-mixin`. The
    /// namespace must name a currently-`@use`d module; a built-in module's
    /// mixins (`meta.load-css`, `meta.apply`) resolve by name.
    /// `meta.get-function($name, $module: ns)`: capture a function reference from
    /// the module bound to `ns` — a user `@function` by identity, or a built-in
    /// member by name.
    fn get_function_from_module(&self, name: &str, module_name: &str, pos: Pos) -> Result<Value, Error> {
        if let Some(module) = self.used_user_modules.get(module_name) {
            if is_private_member(name) {
                return Err(Error::at(
                    "Private members can't be accessed from outside their modules.".to_string(),
                    pos,
                ));
            }
            if let Some(f) = module.function(name) {
                return Ok(Value::Function(SassFunction {
                    name: name.to_string(),
                    css: false,
                    user: Some(Rc::clone(&f) as Rc<dyn std::any::Any>),
                }));
            }
            return Err(Error::at(format!("Function not found: {name}"), pos));
        }
        if let Some(builtin) = self.used_modules.get(module_name) {
            if crate::builtins::module_has_member(builtin, name) {
                // The captured reference dispatches through the GLOBAL alias
                // (`color.scale` is the global `scale-color`), so a later
                // meta.call resolves the right builtin (issue_2818).
                let global = crate::builtins::module_member_to_global(builtin, name)
                    .unwrap_or(name)
                    .to_string();
                return Ok(Value::Function(SassFunction {
                    name: global,
                    css: false,
                    user: None,
                }));
            }
            return Err(Error::at(format!("Function not found: {name}"), pos));
        }
        Err(Error::at(
            format!("There is no module with the namespace \"{module_name}\"."),
            pos,
        ))
    }

    fn get_mixin_from_module(&self, name: &str, module_name: &str, pos: Pos) -> Result<Value, Error> {
        if let Some(module) = self.used_user_modules.get(module_name) {
            if is_private_member(name) {
                return Err(Error::at(
                    "Private members can't be accessed from outside their modules.".to_string(),
                    pos,
                ));
            }
            if let Some(m) = module.mixin(name) {
                return Ok(Value::Mixin(SassMixin {
                    name: name.to_string(),
                    user: Some(Rc::clone(&m) as Rc<dyn std::any::Any>),
                    module: Some(Rc::clone(module) as Rc<dyn std::any::Any>),
                }));
            }
            return Err(Error::at(format!("Mixin not found: {name}"), pos));
        }
        if self.used_modules.contains_key(module_name) {
            if is_builtin_mixin(module_name, name) {
                return Ok(Value::Mixin(SassMixin {
                    name: name.to_string(),
                    user: None,
                    module: None,
                }));
            }
            return Err(Error::at(format!("Mixin not found: {name}"), pos));
        }
        Err(Error::at(
            format!("There is no module with the namespace \"{module_name}\"."),
            pos,
        ))
    }

    /// `meta.call($function, $args...)`: invoke a function reference (or, when
    /// `$function` is a string, the named function). The trailing arguments were
    /// already splat-expanded by `eval_call_args`.
    fn meta_call(&mut self, pos_args: &[Value], named: &[(String, Value)], pos: Pos) -> Result<Value, Error> {
        // `$function` is the first positional argument, or the named `$function`.
        let (func_val, rest_pos): (Value, Vec<Value>) = if let Some(first) = pos_args.first() {
            (first.clone(), pos_args[1..].to_vec())
        } else if let Some((_, v)) = named.iter().find(|(n, _)| n == "function") {
            (v.clone(), Vec::new())
        } else {
            return Err(Error::at("Missing argument $function.", pos));
        };
        // The remaining named args (excluding `$function`) are call keywords.
        let rest_named: Vec<(String, Value)> =
            named.iter().filter(|(n, _)| n != "function").cloned().collect();

        match func_val {
            // A first-class function reference.
            Value::Function(f) => self.invoke_function_ref(&f, rest_pos, rest_named, pos),
            // The deprecated string form: look up by name.
            Value::Str(s) => {
                let f = SassFunction {
                    name: s.text.clone(),
                    css: false,
                    user: self
                        .lookup_function_norm(&normalize_arg_name(&s.text))
                        .map(|c| c as Rc<dyn std::any::Any>),
                };
                self.invoke_function_ref(&f, rest_pos, rest_named, pos)
            }
            other => Err(Error::at(
                format!("$function: {} is not a function reference.", other.to_css(false)),
                pos,
            )),
        }
    }

    /// Invoke a resolved function reference with already-evaluated arguments.
    fn invoke_function_ref(
        &mut self,
        f: &SassFunction,
        pos_args: Vec<Value>,
        named: Vec<(String, Value)>,
        pos: Pos,
    ) -> Result<Value, Error> {
        // A captured user `@function`: bind the evaluated args and run its
        // body in the callable's lexical closure. The payload is a
        // type-erased `Rc<UserCallable>` (cloning the `Rc` releases the
        // borrow on `f` before running the body).
        if let Some(any) = &f.user {
            if let Ok(callable) = Rc::clone(any).downcast::<UserCallable>() {
                let saved_scopes = std::mem::replace(&mut self.scopes, callable.env.clone());
                let saved_semi = std::mem::replace(&mut self.scope_semi_global, callable.env_semi.clone());
                let saved_fns = std::mem::replace(&mut self.functions, callable.env_fns.clone());
                let saved_mixins = std::mem::replace(&mut self.mixins, callable.env_mixins.clone());
                self.push_scope(false);
                let result = self
                    .bind_evaled_into_scope(
                        &callable.def.params,
                        (pos_args, named, ListSep::Comma),
                        &callable.def.name,
                    )
                    .and_then(|()| {
                        self.in_mixin.push(false);
                        let r = self.run_fn_body(&callable.def.body);
                        self.in_mixin.pop();
                        r
                    });
                self.pop_scope();
                self.scopes = saved_scopes;
                self.scope_semi_global = saved_semi;
                self.functions = saved_fns;
                self.mixins = saved_mixins;
                return match result? {
                    Some(v) => Ok(v.without_slash()),
                    None => Err(Error::unpositioned(format!(
                        "Function {}() did not @return a value.",
                        callable.def.name
                    ))),
                };
            }
        }
        // A plain-CSS reference is preserved verbatim as a CSS function call.
        if f.css {
            let mut parts: Vec<String> = pos_args.iter().map(|v| v.to_css(false)).collect();
            for (n, v) in &named {
                parts.push(format!("${n}: {}", v.to_css(false)));
            }
            return Ok(Value::Str(SassStr {
                text: format!("{}({})", f.name, parts.join(", ")),
                quoted: false,
            }));
        }
        // A built-in reference. The `sass:meta` introspection functions need
        // the evaluator's scopes/definitions; everything else dispatches
        // through the value-only builtin library.
        if let Some(r) = self.try_meta_eval_call(&f.name, &pos_args, &named, pos) {
            return r;
        }
        crate::builtins::call(&f.name, &pos_args, &named, pos).map(Value::without_slash)
    }

    /// Read the single string `$name` argument of an existence predicate,
    /// enforcing arity (1 positional, or `$name`) and the string type.
    /// Parse the `$name` (and optional `$module` namespace, when `allow_module`)
    /// arguments of an existence predicate. A `null` `$module` is treated as
    /// absent. Returns `(name, module)`.
    fn exists_name_module_args(
        &self,
        pos_args: &[Value],
        named: &[(String, Value)],
        fname: &str,
        pos: Pos,
        allow_module: bool,
    ) -> Result<(String, Option<String>), Error> {
        let max = if allow_module { 2 } else { 1 };
        if pos_args.len() > max {
            return Err(Error::at(
                format!(
                    "Only {max} argument{} allowed, but {} were passed.",
                    if max == 1 { "" } else { "s" },
                    pos_args.len()
                ),
                pos,
            ));
        }
        let name_v = pos_args
            .first()
            .or_else(|| named.iter().find(|(n, _)| n == "name").map(|(_, v)| v))
            .ok_or_else(|| Error::at(format!("Missing argument $name for {fname}()."), pos))?;
        let name = match name_v {
            Value::Str(s) => s.text.clone(),
            other => {
                return Err(Error::at(
                    format!("$name: {} is not a string.", other.to_css(false)),
                    pos,
                ))
            }
        };
        let module = if allow_module {
            let m = pos_args
                .get(1)
                .or_else(|| named.iter().find(|(n, _)| n == "module").map(|(_, v)| v));
            match m {
                None | Some(Value::Null) => None,
                Some(Value::Str(s)) => Some(s.text.clone()),
                Some(other) => {
                    return Err(Error::at(
                        format!("$module: {} is not a string.", other.to_css(false)),
                        pos,
                    ))
                }
            }
        } else {
            None
        };
        Ok((name, module))
    }

    /// Whether the module bound to namespace `ns` defines a member `name` of the
    /// given kind (function/mixin/variable). An unknown namespace is an error.
    fn module_member_exists(&self, ns: &str, name: &str, kind: MemberKind, pos: Pos) -> Result<bool, Error> {
        if let Some(m) = self.used_user_modules.get(ns) {
            return Ok(match kind {
                MemberKind::Function => m.function(name).is_some(),
                MemberKind::Mixin => m.mixin(name).is_some(),
                MemberKind::Variable => m.var(name).is_some(),
            });
        }
        if let Some(builtin) = self.used_modules.get(ns).cloned() {
            return Ok(match kind {
                MemberKind::Function => crate::builtins::module_has_member(&builtin, name),
                MemberKind::Mixin => builtin == "meta" && matches!(name, "load-css" | "apply"),
                MemberKind::Variable => crate::builtins::module_var(&builtin, name, pos).is_ok(),
            });
        }
        Err(Error::at(
            format!("There is no module with the namespace \"{ns}\"."),
            pos,
        ))
    }

    /// `meta.module-variables/-functions/-mixins($module)`: a map from each
    /// (non-private) member name of the `@use`d module bound to `$module` to its
    /// value (variables) or a first-class reference (functions/mixins). Members
    /// are ordered by name (dart-sass uses source order; every spec module
    /// defines them alphabetically, so this matches byte-for-byte).
    fn meta_module_members(
        &self,
        pos_args: &[Value],
        named: &[(String, Value)],
        pos: Pos,
        kind: MemberKind,
    ) -> Result<Value, Error> {
        let fname = match kind {
            MemberKind::Function => "module-functions",
            MemberKind::Mixin => "module-mixins",
            MemberKind::Variable => "module-variables",
        };
        if pos_args.len() > 1 {
            return Err(Error::at(
                format!("Only 1 argument allowed, but {} were passed.", pos_args.len()),
                pos,
            ));
        }
        let v = pos_args
            .first()
            .or_else(|| named.iter().find(|(n, _)| n == "module").map(|(_, v)| v))
            .ok_or_else(|| Error::at(format!("Missing argument $module for {fname}()."), pos))?;
        let ns = match v {
            Value::Str(s) => s.text.clone(),
            other => {
                return Err(Error::at(
                    format!("$module: {} is not a string.", other.to_css(false)),
                    pos,
                ))
            }
        };
        let Some(module) = self.used_user_modules.get(&ns).cloned() else {
            // A built-in module: `sass:meta` is modeled member-by-member
            // (the suite probes it); other built-ins have no variables and
            // their callables are dispatched, not enumerated, so report the
            // names we know.
            if let Some(builtin) = self.used_modules.get(&ns) {
                let names: Vec<&str> = match (builtin.as_str(), kind) {
                    ("meta", MemberKind::Function) => crate::builtins::META_FUNCTION_NAMES.to_vec(),
                    ("meta", MemberKind::Mixin) => crate::builtins::META_MIXIN_NAMES.to_vec(),
                    _ => Vec::new(),
                };
                let entries: Vec<(Value, Value)> = names
                    .into_iter()
                    .map(|name| {
                        let key = Value::Str(SassStr {
                            text: name.to_string(),
                            quoted: true,
                        });
                        let val = match kind {
                            MemberKind::Function => Value::Function(SassFunction {
                                name: name.to_string(),
                                css: false,
                                user: None,
                            }),
                            MemberKind::Mixin => Value::Mixin(SassMixin {
                                name: name.to_string(),
                                user: None,
                                module: None,
                            }),
                            MemberKind::Variable => Value::Null,
                        };
                        (key, val)
                    })
                    .collect();
                return Ok(Value::Map(Map { entries }));
            }
            return Err(Error::at(
                format!("There is no module with the namespace \"{ns}\"."),
                pos,
            ));
        };
        let mut names: Vec<String> = match kind {
            MemberKind::Variable => module.vars.borrow().keys().cloned().collect(),
            MemberKind::Function => module.functions.borrow().keys().cloned().collect(),
            MemberKind::Mixin => module.mixins.borrow().keys().cloned().collect(),
        };
        names.retain(|n| !is_private_member(n));
        names.sort();
        let entries: Vec<(Value, Value)> = names
            .into_iter()
            .map(|name| {
                // Member names are canonicalized to the dashed form for the map
                // key (dart-sass: `$e_f` is keyed `"e-f"`); the value keeps the
                // variable's own value verbatim.
                let key = Value::Str(SassStr {
                    text: name.replace('_', "-"),
                    quoted: true,
                });
                let val = match kind {
                    MemberKind::Variable => module.var(&name).unwrap_or(Value::Null),
                    MemberKind::Function => Value::Function(SassFunction {
                        name: name.clone(),
                        css: false,
                        user: module
                            .function(&name)
                            .map(|f| Rc::clone(&f) as Rc<dyn std::any::Any>),
                    }),
                    MemberKind::Mixin => Value::Mixin(SassMixin {
                        name: name.clone(),
                        user: module
                            .mixin(&name)
                            .map(|m| Rc::clone(&m) as Rc<dyn std::any::Any>),
                        module: Some(Rc::clone(&module) as Rc<dyn std::any::Any>),
                    }),
                };
                (key, val)
            })
            .collect();
        Ok(Value::Map(Map { entries }))
    }

    /// `meta.variable-exists($name)` / `meta.global-variable-exists($name)`:
    /// whether a variable of that name is in scope (globally only when
    /// `global`). Names are matched dash/underscore-insensitively.
    fn meta_variable_exists(
        &self,
        pos_args: &[Value],
        named: &[(String, Value)],
        pos: Pos,
        global: bool,
    ) -> Result<Value, Error> {
        let fname = if global {
            "global-variable-exists"
        } else {
            "variable-exists"
        };
        // Only `global-variable-exists` takes the optional `$module` namespace.
        let (name, module) = self.exists_name_module_args(pos_args, named, fname, pos, global)?;
        if let Some(ns) = module {
            return Ok(Value::Bool(self.module_member_exists(
                &ns,
                &name,
                MemberKind::Variable,
                pos,
            )?));
        }
        let key = normalize_arg_name(&name);
        let scopes: &[Scope] = if global { &self.scopes[..1] } else { &self.scopes };
        let found = scopes
            .iter()
            .any(|s| s.borrow().keys().any(|k| normalize_arg_name(k) == key));
        if found {
            return Ok(Value::Bool(true));
        }
        // A variable exposed unprefixed via `@use … as *` (or forwarded into
        // one). Exposure from more than one star module is ambiguous.
        let count = self.star_member_count(&name, MemberKind::Variable);
        if count > 1 {
            return Err(Error::at(
                "This variable is available from multiple global modules.",
                pos,
            ));
        }
        Ok(Value::Bool(count >= 1))
    }

    /// `meta.mixin-exists($name)`: whether a mixin of that name is defined.
    fn meta_mixin_exists(
        &self,
        pos_args: &[Value],
        named: &[(String, Value)],
        pos: Pos,
    ) -> Result<Value, Error> {
        let (name, module) = self.exists_name_module_args(pos_args, named, "mixin-exists", pos, true)?;
        if let Some(ns) = module {
            return Ok(Value::Bool(self.module_member_exists(
                &ns,
                &name,
                MemberKind::Mixin,
                pos,
            )?));
        }
        let key = normalize_arg_name(&name);
        let local = self.lookup_mixin_norm(&key).is_some();
        if local {
            return Ok(Value::Bool(true));
        }
        let count = self.star_member_count(&name, MemberKind::Mixin);
        if count > 1 {
            return Err(Error::at(
                "This mixin is available from multiple global modules.",
                pos,
            ));
        }
        Ok(Value::Bool(count >= 1))
    }

    /// `meta.function-exists($name)`: whether a user `@function` or a built-in
    /// of that name exists.
    fn meta_function_exists(
        &self,
        pos_args: &[Value],
        named: &[(String, Value)],
        pos: Pos,
    ) -> Result<Value, Error> {
        let (name, module) = self.exists_name_module_args(pos_args, named, "function-exists", pos, true)?;
        if let Some(ns) = module {
            return Ok(Value::Bool(self.module_member_exists(
                &ns,
                &name,
                MemberKind::Function,
                pos,
            )?));
        }
        let key = normalize_arg_name(&name);
        let user = self.lookup_function_norm(&key).is_some();
        if user {
            return Ok(Value::Bool(true));
        }
        // A function exposed unprefixed via `@use … as *` (or forwarded into a
        // module that is itself `@use`d as `*`). Exposure from more than one
        // star module is ambiguous.
        let count = self.star_member_count(&name, MemberKind::Function);
        if count > 1 {
            return Err(Error::at(
                "This function is available from multiple global modules.",
                pos,
            ));
        }
        Ok(Value::Bool(count >= 1 || crate::builtins::is_builtin(&name)))
    }

    /// Count how many `@use … as *` modules expose `name` as the given member
    /// kind; more than one means an unqualified reference is ambiguous.
    fn star_member_count(&self, name: &str, kind: MemberKind) -> usize {
        if is_private_member(name) {
            return 0;
        }
        self.star_user_modules
            .iter()
            .filter(|m| match kind {
                MemberKind::Variable => m.var(name).is_some(),
                MemberKind::Mixin => m.mixin(name).is_some(),
                MemberKind::Function => m.function(name).is_some(),
            })
            .count()
    }

    /// `meta.content-exists()`: whether the enclosing mixin was passed a
    /// `@content` block. It is an error to call this outside a mixin body.
    fn meta_content_exists(&self, pos_args: &[Value], pos: Pos) -> Result<Value, Error> {
        if !pos_args.is_empty() {
            return Err(Error::at(
                format!("Only 0 arguments allowed, but {} were passed.", pos_args.len()),
                pos,
            ));
        }
        if self.in_mixin.last().copied() != Some(true) {
            return Err(Error::at(
                "content-exists() may only be called within a mixin.",
                pos,
            ));
        }
        let has = matches!(self.content_stack.last(), Some(Some(_)));
        Ok(Value::Bool(has))
    }

    /// Try `member` against a built-in module re-exported by `module` via
    /// `@forward "sass:x"` (honouring an `as p-*` prefix).
    fn try_forwarded_builtin_call(
        &mut self,
        module: &Rc<Module>,
        member: &str,
        args: &[CallArg],
        pos: Pos,
    ) -> Result<Option<Value>, Error> {
        for fb in &module.forwarded_builtins {
            let bare = match &fb.prefix {
                Some(p) => match member.strip_prefix(p.as_str()) {
                    Some(rest) => rest,
                    None => continue,
                },
                None => member,
            };
            if fb.visible(bare) && crate::builtins::module_has_member(&fb.module, bare) {
                let (mut pos_args, mut named, _) = self.eval_call_args(args)?;
                for v in &mut pos_args {
                    *v = std::mem::replace(v, Value::Null).without_slash();
                }
                for (_, v) in &mut named {
                    *v = std::mem::replace(v, Value::Null).without_slash();
                }
                return Ok(Some(
                    crate::builtins::call_module(&fb.module, bare, &pos_args, &named, pos)?.without_slash(),
                ));
            }
        }
        Ok(None)
    }

    /// Call a user module's function in the module's own environment: bind the
    /// arguments in the caller's context, then swap in the module's globals/
    /// functions/mixins/used-modules so the body resolves against the module.
    fn call_user_module_function(
        &mut self,
        module: &Rc<Module>,
        func: &Rc<UserCallable>,
        args: &[CallArg],
        call: Option<(Pos, usize)>,
    ) -> Result<Value, Error> {
        let evaled = self.eval_call_args(args)?;
        let saved_member = call.map(|(pos, len)| self.enter_call(pos, len, &format!("{}()", func.def.name)));
        let saved = self.enter_module(module);
        let saved_file = self.enter_module_file(module);
        let saved_scopes = std::mem::replace(&mut self.scopes, func.env.clone());
        let saved_semi = std::mem::replace(&mut self.scope_semi_global, func.env_semi.clone());
        let saved_fns = std::mem::replace(&mut self.functions, func.env_fns.clone());
        let saved_mixins = std::mem::replace(&mut self.mixins, func.env_mixins.clone());
        self.push_scope(false);
        let result = self
            .bind_evaled_into_scope(&func.def.params, evaled, &func.def.name)
            .and_then(|()| self.run_fn_body(&func.def.body));
        self.pop_scope();
        self.scopes = saved_scopes;
        self.scope_semi_global = saved_semi;
        self.functions = saved_fns;
        self.mixins = saved_mixins;
        self.leave_module_file(saved_file);
        self.leave_module(saved);
        if let Some(saved_member) = saved_member {
            self.leave_call(saved_member);
        }
        match result? {
            Some(v) => Ok(v.without_slash()),
            None => Err(Error::unpositioned(format!(
                "Function {}() did not @return a value.",
                func.def.name
            ))),
        }
    }

    /// Swap in `module`'s source file for diagnostics during a cross-module
    /// member invocation. Returns the previous `(url, source)` to restore.
    fn enter_module_file(&mut self, module: &Rc<Module>) -> Option<(String, Rc<str>, Option<String>)> {
        if module.diag_url.is_empty() {
            return None;
        }
        let source = self.source_for(&module.diag_url);
        let dir = if module.file_dir.is_empty() {
            None
        } else {
            Some(module.file_dir.clone())
        };
        self.current_url_stamp = 0;
        Some((
            std::mem::replace(&mut self.current_url, module.diag_url.clone()),
            std::mem::replace(&mut self.current_source, source),
            std::mem::replace(&mut self.current_file_dir, dir),
        ))
    }

    /// Restore the file swapped out by [`Self::enter_module_file`].
    fn leave_module_file(&mut self, saved: Option<(String, Rc<str>, Option<String>)>) {
        if let Some((url, source, dir)) = saved {
            self.current_url = url;
            self.current_url_stamp = 0;
            self.current_source = source;
            self.current_file_dir = dir;
        }
    }

    /// The diagnostic display URL for a `@use`/`@import`ed module: the basename
    /// of the resolved key (dart-sass shows e.g. `_libchain.scss`), falling back
    /// to the `@use` url spelling when the key has no useful tail.
    fn module_diag_url(&self, url: &str, key: &str) -> String {
        let base = key.rsplit(['/', '\\']).next().unwrap_or(key);
        if base.is_empty() {
            url.to_string()
        } else {
            base.to_string()
        }
    }

    /// Install `module`'s environment for a cross-module member invocation,
    /// returning the previous environment to restore with [`leave_module`].
    fn enter_module(&mut self, module: &Rc<Module>) -> SavedModuleEnv {
        // The module's global scope is SHARED (the same Rc its callables
        // captured), so writes inside the module are immediately visible to
        // its closures and to later cross-module reads.
        let module_scope = std::rc::Rc::clone(&module.vars);
        SavedModuleEnv {
            scopes: std::mem::replace(&mut self.scopes, vec![module_scope]),
            scope_semi_global: std::mem::replace(&mut self.scope_semi_global, vec![true]),
            functions: std::mem::replace(&mut self.functions, vec![std::rc::Rc::clone(&module.functions)]),
            mixins: std::mem::replace(&mut self.mixins, vec![std::rc::Rc::clone(&module.mixins)]),
            used_modules: std::mem::replace(&mut self.used_modules, module.used_builtin_modules.clone()),
            star_modules: std::mem::replace(&mut self.star_modules, module.star_builtin_modules.clone()),
            used_user_modules: std::mem::replace(
                &mut self.used_user_modules,
                module.used_user_modules.clone(),
            ),
            star_user_modules: std::mem::replace(
                &mut self.star_user_modules,
                module.star_user_modules.clone(),
            ),
            write_back: Some(Rc::clone(module)),
        }
    }

    /// Restore the environment captured by [`enter_module`]. If the saved env
    /// recorded a module, its (possibly mutated) global scope is written back so
    /// a `!global` assignment inside the module persists.
    fn leave_module(&mut self, saved: SavedModuleEnv) {
        // The module scope is shared by Rc; writes already land in
        // module.vars without an explicit copy-back.
        let _ = &saved.write_back;
        self.scopes = saved.scopes;
        self.scope_semi_global = saved.scope_semi_global;
        self.functions = saved.functions;
        self.mixins = saved.mixins;
        self.used_modules = saved.used_modules;
        self.star_modules = saved.star_modules;
        self.used_user_modules = saved.used_user_modules;
        self.star_user_modules = saved.star_user_modules;
    }

    /// Resolve a namespaced module variable `ns.$name`. Resolves a user module
    /// first, then a built-in module bound to `ns`.
    fn eval_module_var(&self, ns: &str, name: &str, pos: Pos) -> Result<Value, Error> {
        if let Some(module) = self.used_user_modules.get(ns) {
            if is_private_member(name) {
                return Err(Error::at(
                    "Private members can't be accessed from outside their modules.".to_string(),
                    pos,
                ));
            }
            return match module.var(name) {
                Some(v) => Ok(v.without_slash()),
                None => Err(Error::at("Undefined variable.".to_string(), pos)),
            };
        }
        match self.used_modules.get(ns) {
            Some(module) => crate::builtins::module_var(module, name, pos),
            None => Err(Error::at(
                format!("There is no module with the namespace \"{ns}\"."),
                pos,
            )),
        }
    }

    /// The lazy `if($condition, $if-true, $if-false)` function: evaluates
    /// the condition, then only the selected branch.
    fn eval_if_function(&mut self, args: &[CallArg], pos: Pos) -> Result<Value, Error> {
        // An argument is lazy (an unevaluated branch expression) unless it
        // came from a `...` splat: dart's macro-argument handling evaluates
        // the splat eagerly and reconstitutes its elements (and an argument
        // list's keywords) as already-evaluated arguments.
        enum IfArg<'a> {
            Lazy(&'a Expr),
            Eager(Value),
        }
        fn slot_index(name: &str) -> Option<usize> {
            match name {
                "condition" => Some(0),
                "if-true" => Some(1),
                "if-false" => Some(2),
                _ => None,
            }
        }
        let mut by_pos: Vec<IfArg<'_>> = Vec::new();
        // $condition / $if-true / $if-false by name.
        let mut named: [Option<IfArg<'_>>; 3] = [None, None, None];
        for a in args {
            if a.splat {
                match self.eval_expr(&a.value)? {
                    Value::List(l) => {
                        if let Some(kw) = &l.keywords {
                            for (k, v) in kw {
                                if let Value::Str(s) = k {
                                    match slot_index(&s.text) {
                                        Some(i) => named[i] = Some(IfArg::Eager(v.clone())),
                                        None => {
                                            return Err(Error::at(
                                                format!("if() has no argument named ${}.", s.text),
                                                pos,
                                            ))
                                        }
                                    }
                                }
                            }
                        }
                        for item in l.items {
                            by_pos.push(IfArg::Eager(item));
                        }
                    }
                    Value::Map(m) => {
                        for (k, v) in m.entries {
                            let name = match k {
                                Value::Str(s) => s.text,
                                other => {
                                    return Err(Error::at(
                                        format!(
                                            "Variable keyword argument map must have string keys.\n{} is not a string.",
                                            other.to_css(false)
                                        ),
                                        pos,
                                    ))
                                }
                            };
                            match slot_index(&name) {
                                Some(i) => named[i] = Some(IfArg::Eager(v)),
                                None => {
                                    return Err(Error::at(
                                        format!("if() has no argument named ${name}."),
                                        pos,
                                    ))
                                }
                            }
                        }
                    }
                    other => by_pos.push(IfArg::Eager(other)),
                }
                continue;
            }
            match a.name.as_deref() {
                Some(name) => match slot_index(name) {
                    Some(i) => named[i] = Some(IfArg::Lazy(&a.value)),
                    None => {
                        return Err(Error::at(format!("if() has no argument named ${name}."), pos));
                    }
                },
                None => by_pos.push(IfArg::Lazy(&a.value)),
            }
        }
        let [cond, t_val, f_val] = named;
        let mut pos_iter = by_pos.into_iter();
        let cond = cond.or_else(|| pos_iter.next());
        let t_val = t_val.or_else(|| pos_iter.next());
        let f_val = f_val.or_else(|| pos_iter.next());
        match (cond, t_val, f_val) {
            (Some(c), Some(t), Some(f)) => {
                let truthy = match c {
                    IfArg::Lazy(e) => self.eval_expr(e)?.is_truthy(),
                    IfArg::Eager(v) => v.is_truthy(),
                };
                // if() is a function boundary: a bare slash-division branch
                // collapses to its number (dart-sass `withoutSlash`).
                let branch = if truthy { t } else { f };
                match branch {
                    IfArg::Lazy(e) => Ok(self.eval_expr(e)?.without_slash()),
                    IfArg::Eager(v) => Ok(v.without_slash()),
                }
            }
            _ => Err(Error::at(
                "if() requires arguments $condition, $if-true, $if-false.",
                pos,
            )),
        }
    }

    /// Evaluate a modern CSS `if()`: a `;`-separated list of clauses, each
    /// `<condition>: <value>` (or `else: <value>`). Conditions mix evaluated
    /// `sass(<expr>)` with non-evaluable `css(...)` / arbitrary substitution
    /// pieces. If every reachable condition resolves statically, the matching
    /// value is returned; otherwise the whole `if()` is re-serialized
    /// verbatim (with statically-true/false conditions folded away) as an
    /// unquoted string.
    fn eval_modern_if(&mut self, clauses: &[IfClause]) -> Result<Value, Error> {
        let mut verbatim: Option<Vec<String>> = None;
        for clause in clauses {
            // The `else` clause has no condition: it always matches.
            let result = match &clause.condition {
                None => CondEval::Bool(true),
                Some(cond) => self.eval_if_cond(cond)?,
            };
            match (&mut verbatim, result) {
                // Not yet verbatim: a static-true (or `else`) clause wins.
                (None, CondEval::Bool(true)) => {
                    return Ok(self.eval_expr(&clause.value)?.without_slash());
                }
                // Not yet verbatim: a static-false clause is skipped.
                (None, CondEval::Bool(false)) => {}
                // First non-evaluable condition: enter verbatim mode.
                (None, CondEval::Css(rc)) => {
                    let value = self.eval_if_value(&clause.value)?;
                    verbatim = Some(vec![format!("{}: {}", rc.to_css(), value)]);
                }
                // Already verbatim: fold each remaining clause.
                (Some(out), CondEval::Bool(true)) => {
                    let value = self.eval_if_value(&clause.value)?;
                    out.push(format!("else: {value}"));
                }
                (Some(_), CondEval::Bool(false)) => {}
                (Some(out), CondEval::Css(rc)) => {
                    let value = self.eval_if_value(&clause.value)?;
                    out.push(format!("{}: {}", rc.to_css(), value));
                }
            }
        }
        match verbatim {
            Some(parts) => Ok(Value::Str(SassStr {
                text: format!("if({})", parts.join("; ")),
                quoted: false,
            })),
            // No clause matched and no `else`: the modern `if()` is null.
            None => Ok(Value::Null),
        }
    }

    /// Evaluate an `if()` clause value. dart-sass serializes the value in a
    /// parenthesized-expression context, so lists are wrapped in parens and
    /// a bare slash-division collapses to its number.
    fn eval_if_value(&mut self, expr: &Expr) -> Result<String, Error> {
        let v = self.eval_expr(expr)?.without_slash();
        Ok(serialize_if_value(&v))
    }

    /// Evaluate a modern `if()` condition into a tri-state result: a static
    /// boolean (from `sass(...)` atoms) or a residual non-evaluable CSS
    /// condition that must be re-serialized verbatim.
    fn eval_if_cond(&mut self, cond: &IfCond) -> Result<CondEval, Error> {
        match cond {
            IfCond::Sass(expr) => Ok(CondEval::Bool(self.eval_expr(expr)?.is_truthy())),
            IfCond::Raw { pieces, .. } => {
                let text = self.eval_template(pieces)?;
                // dart re-serializes the raw token run with collapsed
                // whitespace and no space inside empty parens
                // (`css(\n)` is `css()`).
                let mut collapsed = String::with_capacity(text.len());
                let mut prev_ws = false;
                for c in text.chars() {
                    if c.is_whitespace() {
                        prev_ws = true;
                        continue;
                    }
                    if prev_ws && !collapsed.is_empty() && c != ')' {
                        collapsed.push(' ');
                    }
                    prev_ws = false;
                    collapsed.push(c);
                }
                let collapsed = collapsed.replace("( ", "(");
                Ok(CondEval::Css(RCond::Css(collapsed)))
            }
            IfCond::Not(inner) => match self.eval_if_cond(inner)? {
                CondEval::Bool(b) => Ok(CondEval::Bool(!b)),
                CondEval::Css(rc) => Ok(CondEval::Css(RCond::Not(Box::new(rc)))),
            },
            IfCond::Paren(inner) => match self.eval_if_cond(inner)? {
                CondEval::Bool(b) => Ok(CondEval::Bool(b)),
                CondEval::Css(rc) => Ok(CondEval::Css(RCond::Paren(Box::new(rc)))),
            },
            IfCond::And(items) => {
                let mut residuals: Vec<RCond> = Vec::new();
                for item in items {
                    match self.eval_if_cond(item)? {
                        // A statically-false operand makes the whole `and`
                        // false and short-circuits the rest.
                        CondEval::Bool(false) => return Ok(CondEval::Bool(false)),
                        // A statically-true operand drops out of the `and`.
                        CondEval::Bool(true) => {}
                        CondEval::Css(rc) => residuals.push(rc),
                    }
                }
                Ok(combine_residuals(residuals, true))
            }
            IfCond::Or(items) => {
                let mut residuals: Vec<RCond> = Vec::new();
                for item in items {
                    match self.eval_if_cond(item)? {
                        // A statically-true operand makes the whole `or`
                        // true and short-circuits the rest.
                        CondEval::Bool(true) => return Ok(CondEval::Bool(true)),
                        // A statically-false operand drops out of the `or`.
                        CondEval::Bool(false) => {}
                        CondEval::Css(rc) => residuals.push(rc),
                    }
                }
                Ok(combine_residuals(residuals, false))
            }
        }
    }

    /// Serialize a CSS math function (`min`/`max`/`clamp`/…) verbatim inside a
    /// `@supports` declaration: each argument is resolved through the
    /// (non-folding) calc machinery and joined with `, `. Used only when
    /// `in_supports_declaration` is set.
    fn eval_supports_calc_func(&mut self, name: &str, args: &[CallArg], pos: Pos) -> Result<Value, Error> {
        if args.iter().any(|a| a.splat) {
            return Err(Error::at("Rest arguments can't be used with calculations.", pos));
        }
        let mut parts = Vec::with_capacity(args.len());
        for a in args {
            let inner = self.eval_calc(&a.value)?.to_calc_css(self.compressed());
            // A named argument (`min($a: 1)`) is not valid in a calculation, but
            // we preserve any name verbatim to mirror the surface syntax.
            match &a.name {
                Some(n) => parts.push(format!("${n}: {inner}")),
                None => parts.push(inner),
            }
        }
        Ok(Value::Str(SassStr {
            text: format!("{name}({})", parts.join(", ")),
            quoted: false,
        }))
    }

    /// Try to evaluate a single-/double-argument math calculation (`sin`,
    /// `sqrt`, `pow`, `log`, `hypot`, …) as a calculation. Each argument is
    /// evaluated through the calc machinery, which rejects disallowed operators
    /// (`%`, comparisons) the way dart-sass does.
    ///
    /// - When *every* argument folds to a single number, returns `Ok(None)`:
    ///   the caller falls through to the ordinary builtin, which computes the
    ///   result and applies its unit checks (so `sqrt(2)`, `sin(1deg)`,
    ///   `sin(1px)`-the-error all behave exactly as before).
    /// - When an argument still carries an opaque operand — a `var()`,
    ///   interpolation, or unknown identifier — the whole call is preserved as a
    ///   calculation string (`sin(2px + var(--c))`).
    /// - When an argument reduces to a numeric operation we cannot collapse to a
    ///   single number (compound/inverse units), returns `Ok(None)` so the
    ///   builtin re-evaluates and reports its own error, rather than silently
    ///   preserving a value dart-sass would reject.
    fn try_eval_calc_math_call(
        &mut self,
        name: &str,
        args: &[CallArg],
        _pos: Pos,
    ) -> Result<Option<Value>, Error> {
        let mut nodes = Vec::with_capacity(args.len());
        for a in args {
            nodes.push(self.eval_calc(&a.value)?);
        }
        // Every argument is a plain number: let the builtin compute.
        if nodes.iter().all(|n| matches!(n, CalcNode::Number(_))) {
            return Ok(None);
        }
        // No opaque operand anywhere: the calculation is purely numeric but did
        // not collapse (compound/inverse units). Defer to the builtin so it can
        // raise the dart-sass error instead of us preserving an invalid value.
        if !nodes.iter().any(calc_node_has_opaque) {
            return Ok(None);
        }
        let lname = name.to_ascii_lowercase();
        let parts: Vec<String> = nodes.iter().map(|n| n.to_calc_css(self.compressed())).collect();
        Ok(Some(Value::Str(SassStr {
            text: format!("{lname}({})", parts.join(", ")),
            quoted: false,
        })))
    }

    /// Evaluate a three-argument `clamp(min, value, max)` calculation. Each
    /// argument is evaluated through the calc machinery (rejecting `%` and other
    /// non-calculation operators). When every argument folds to a single number,
    /// the builtin clamps/unit-checks them as before; when an argument keeps a
    /// `var()`/calculation operand the call is preserved
    /// (`clamp(1% + 1px, 2px, 3px)`). A resolved operand with complex units is
    /// rejected like dart-sass.
    fn try_eval_clamp(&mut self, args: &[CallArg], pos: Pos) -> Result<Value, Error> {
        let mut nodes = Vec::with_capacity(args.len());
        for a in args {
            let node = self.eval_calc(&a.value)?;
            if let Some(complex) = calc_complex_unit_operand(&node) {
                return Err(Error::at(
                    format!(
                        "Number calc({}) isn't compatible with CSS calculations.",
                        complex.to_calc_css(false)
                    ),
                    pos,
                ));
            }
            nodes.push(node);
        }
        // Every argument is a plain number: let the builtin clamp them (and run
        // its incompatible-unit and complex-unit checks).
        if nodes.iter().all(|n| matches!(n, CalcNode::Number(_))) {
            let values: Vec<Value> = nodes
                .into_iter()
                .map(|n| match n {
                    CalcNode::Number(num) => Value::Number(num),
                    // Unreachable: guarded by the `all` check above.
                    other => Value::Calc(other),
                })
                .collect();
            return crate::builtins::call("clamp", &values, &[], pos);
        }
        let parts: Vec<String> = nodes.iter().map(|n| n.to_calc_css(self.compressed())).collect();
        Ok(Value::Str(SassStr {
            text: format!("clamp({})", parts.join(", ")),
            quoted: false,
        }))
    }

    /// Evaluate a `calc-size(target, value)` calculation. The target (`auto`,
    /// `none`, `size`, a `var()`, or a nested calculation) and the optional
    /// value are each evaluated through the calc machinery and the call is kept
    /// preserved (`calc-size()` never reduces to a number). Exactly one or two
    /// arguments are accepted.
    fn eval_calc_size(&mut self, args: &[CallArg], pos: Pos) -> Result<Value, Error> {
        if args.is_empty() {
            return Err(Error::at("Missing argument.", pos));
        }
        if args.len() > 2 {
            return Err(Error::at(
                format!("Only 2 arguments allowed, but {} were passed.", args.len()),
                pos,
            ));
        }
        let mut parts = Vec::with_capacity(args.len());
        for a in args {
            parts.push(self.eval_calc(&a.value)?.to_calc_css(self.compressed()));
        }
        Ok(Value::Str(SassStr {
            text: format!("calc-size({})", parts.join(", ")),
            quoted: false,
        }))
    }

    /// Evaluate the interior of a `calc()` into a simplified node tree.
    /// Numeric `number <op> number` subtrees with compatible units fold;
    /// everything else (variables, interpolations, incompatible units) is
    /// preserved for canonical serialization, mirroring dart-sass's
    /// "only simplify number+number" rule.
    fn eval_calc(&mut self, expr: &Expr) -> Result<CalcNode, Error> {
        match expr {
            Expr::Binary { op, lhs, rhs, pos } => {
                let calc_op = match op {
                    BinOp::Add => CalcOp::Add,
                    BinOp::Sub => CalcOp::Sub,
                    BinOp::Mul => CalcOp::Mul,
                    // Modulo, comparisons, and `and`/`or` are not arithmetic;
                    // dart-sass rejects them inside a calculation rather than
                    // evaluating them (`calc(1px % 2px)`, `calc(1 > 2)`).
                    _ => return Err(Error::at("This operation can't be used in a calculation.", *pos)),
                };
                let l = self.eval_calc(lhs)?;
                let r = self.eval_calc(rhs)?;
                if self.in_supports_declaration {
                    return Ok(CalcNode::Op {
                        op: calc_op,
                        left: Box::new(l),
                        right: Box::new(r),
                    });
                }
                fold_calc(calc_op, l, r, *pos)
            }
            Expr::Div { lhs, rhs, pos, .. } => {
                let l = self.eval_calc(lhs)?;
                let r = self.eval_calc(rhs)?;
                if self.in_supports_declaration {
                    return Ok(CalcNode::Op {
                        op: CalcOp::Div,
                        left: Box::new(l),
                        right: Box::new(r),
                    });
                }
                fold_calc(CalcOp::Div, l, r, *pos)
            }
            Expr::Unary {
                op: UnOp::Neg,
                operand,
            } => {
                let node = self.eval_calc(operand)?;
                match node {
                    CalcNode::Number(n) => Ok(CalcNode::Number(n.copy_units(-n.value))),
                    other => Ok(CalcNode::Op {
                        op: CalcOp::Mul,
                        left: Box::new(CalcNode::Number(Number::unitless(-1.0))),
                        right: Box::new(other),
                    }),
                }
            }
            // Parentheses around a single opaque operand (a `var()`,
            // identifier, or interpolation) are preserved verbatim; around a
            // number or an operation they are redundant and dropped (operator
            // precedence reintroduces them where needed).
            Expr::Paren(inner) => {
                let node = self.eval_calc(inner)?;
                match node {
                    CalcNode::Str(s) => Ok(CalcNode::Str(format!("({s})"))),
                    other => Ok(other),
                }
            }
            // A nested calc() flattens into the surrounding calculation —
            // except inside a `@supports` declaration, where dart-sass keeps the
            // calculation unsimplified, so the inner `calc(...)` stays wrapped.
            // Otherwise an unresolved single-string operand (an interpolation or
            // a `var()` substitution that is not a clean operand) is
            // parenthesized: dart-sass writes `calc(calc(#{"c*"}))` as
            // `calc((c*))` and `calc(1 + calc(var(--c)))` as `calc(1 +
            // (var(--c)))`. A clean identifier, number, operation, or complete
            // sub-calculation flattens without extra parens.
            Expr::Calc { inner, .. } => {
                if self.in_supports_declaration {
                    let s = self.eval_calc(inner)?.to_calc_css(self.compressed());
                    return Ok(CalcNode::Str(format!("calc({s})")));
                }
                let node = self.eval_calc(inner)?;
                match node {
                    CalcNode::Str(s) if nested_calc_needs_parens(&s) => Ok(CalcNode::Str(format!("({s})"))),
                    other => Ok(other),
                }
            }
            // A space-separated list written directly in the calc interior is
            // an "unparsed" run: it is only valid when it contains a `var()`/
            // `env()` substitution, an interpolation, or a variable holding an
            // unquoted string — all of which dart-sass splices verbatim
            // (`calc(var(--c) 1)`, `calc(#{"1 +"} 2)` -> `calc(1 + 2)`,
            // `calc(1 $c)` with `$c: unquote("+ 2")` -> `calc(1 + 2)`). A
            // space-list of ordinary operands (`calc(1 2)`, `calc(c 1 2)`) or
            // of number-valued variables (`calc(1 $n)`) has no operator
            // between adjacent terms: "Missing math operator.".
            Expr::List {
                items,
                sep: ListSep::Space,
                bracketed: false,
            } => {
                let has_subst = items.iter().any(expr_has_substitution);
                if !has_subst
                    && !items
                        .iter()
                        .any(|e| matches!(e, Expr::Var { .. } | Expr::NsVar { .. }))
                {
                    return Err(Error::unpositioned("Missing math operator."));
                }
                let mut parts = Vec::with_capacity(items.len());
                let mut any_str = false;
                for it in items {
                    let node = self.eval_calc(it)?;
                    if matches!(node, CalcNode::Str(_)) {
                        any_str = true;
                    }
                    parts.push(node.to_calc_css(false));
                }
                // Variables alone only justify the splice when at least one
                // resolved to raw text.
                if !has_subst && !any_str {
                    return Err(Error::unpositioned("Missing math operator."));
                }
                Ok(CalcNode::Str(parts.join(" ")))
            }
            // Any leaf (number, var(), interpolation, ident) evaluates to a
            // value and becomes a calc operand.
            other => {
                let v = self.eval_expr(other)?;
                // The calc constants `pi`/`e`/`infinity`/`-infinity`/`nan`
                // (case-insensitive) resolve to their numeric values inside a
                // calculation, so `calc(infinity * 2)` folds to `calc(infinity)`
                // and `calc(NaN)` canonicalizes its spelling.
                if let Value::Str(s) = &v {
                    if !s.quoted {
                        if let Some(value) = calc_constant(&s.text) {
                            return Ok(CalcNode::Number(Number::unitless(value)));
                        }
                    }
                }
                // Only a number, a nested calculation, or an unquoted string
                // (a `var()`, interpolation, ident, or other special CSS value)
                // is a legal calculation operand. A null, bool, color, list,
                // map, or quoted string evaluated into the calc — typically via
                // a `$variable` or function call — is rejected the way
                // dart-sass does ("Value … can't be used in a calculation.").
                match &v {
                    Value::Number(_) | Value::Calc(_) | Value::Slash(_, _) => {}
                    Value::Str(s) if !s.quoted => {}
                    other => {
                        return Err(Error::unpositioned(format!(
                            "Value {} can't be used in a calculation.",
                            calc_value_repr(other)
                        )));
                    }
                }
                Ok(value_to_calc_node(v))
            }
        }
    }
}

/// Whether a calc space-list item is a substitution that makes the unparsed
/// run legal: a `#{…}` interpolation, or a `var()`/`env()` reference (which
/// the parser lowers to an [`Expr::Ident`] whose text begins with `var(`/
/// `env(`, possibly after a vendor prefix). A plain ident, number, nested
/// calc, or variable is NOT a substitution.
/// Whether a property-name template begins, *literally*, with `--` (a custom
/// property). A name whose first piece is `#{…}` interpolation is not literal,
/// so `#{--b}` is allowed to namespace inside a property set while a written
/// `--b` is not.
fn literal_name_is_custom_property(property: &[TplPiece]) -> bool {
    match property.first() {
        Some(TplPiece::Lit(s)) => s.trim_start().starts_with("--"),
        _ => false,
    }
}

fn expr_has_substitution(e: &Expr) -> bool {
    match e {
        Expr::Interp(_) => true,
        // `var()`/`env()` are parsed as plain function calls; inside a calc
        // space-list they are legal substitutions (`calc(var(--c) 1)`).
        Expr::Func { name, .. } => name.eq_ignore_ascii_case("var") || name.eq_ignore_ascii_case("env"),
        Expr::Ident(pieces) => pieces.iter().any(|p| match p {
            TplPiece::Interp(_) => true,
            TplPiece::Lit(s) => {
                let lower = s.trim_start().to_ascii_lowercase();
                lower.starts_with("var(") || lower.starts_with("env(")
            }
        }),
        _ => false,
    }
}

/// Whether an expression tree contains a calculation substitution — a
/// `var()`/`env()` reference or an interpolation — anywhere within it
/// (recursing through operations, parentheses, nested calculations, and
/// lists). Used to decide whether a legacy global math function such as `abs()`
/// is being used as a CSS calculation (so its argument is preserved) rather
/// than as the deprecated Sass global.
fn expr_contains_calc_substitution(e: &Expr) -> bool {
    if expr_has_substitution(e) {
        return true;
    }
    match e {
        Expr::Binary { lhs, rhs, .. } => {
            expr_contains_calc_substitution(lhs) || expr_contains_calc_substitution(rhs)
        }
        Expr::Div { lhs, rhs, .. } => {
            expr_contains_calc_substitution(lhs) || expr_contains_calc_substitution(rhs)
        }
        Expr::Unary { operand, .. } => expr_contains_calc_substitution(operand),
        Expr::Paren(inner) => expr_contains_calc_substitution(inner),
        Expr::Calc { inner } => expr_contains_calc_substitution(inner),
        Expr::List { items, .. } => items.iter().any(expr_contains_calc_substitution),
        _ => false,
    }
}

/// Collect the names of every `$var: ... !global` declaration nested inside
/// block statements (rules, conditionals, loops, mixins are NOT entered —
/// dart-sass registers slots for statically visible nested globals in rules
/// and control flow). Top-level declarations register themselves on
/// evaluation.
fn collect_global_var_decls(stmts: &[Stmt], out: &mut Vec<String>) {
    for stmt in stmts {
        match stmt {
            Stmt::VarDecl(v) if v.is_global && v.namespace.is_none() => out.push(v.name.clone()),
            Stmt::Rule(r) => collect_global_var_decls(&r.body, out),
            Stmt::If(branches) => {
                for b in branches {
                    collect_global_var_decls(&b.body, out);
                }
            }
            Stmt::For { body, .. }
            | Stmt::Each { body, .. }
            | Stmt::While { body, .. }
            | Stmt::Media { body, .. }
            | Stmt::Supports { body, .. }
            | Stmt::AtRoot { body, .. }
            | Stmt::Keyframes { body, .. } => collect_global_var_decls(body, out),
            Stmt::AtRule { body: Some(b), .. } => collect_global_var_decls(b, out),
            _ => {}
        }
    }
}

/// Nest module CSS under the style rule enclosing an `@import` (descendant
/// join on every top-level rule, recursing into at-rule bodies). dart-sass
/// clones the module's CSS into the current parent; a top-level import
/// (`parents` empty) passes through unchanged.
fn reparent_nodes(nodes: Vec<OutNode>, parents: &[String]) -> Vec<OutNode> {
    if parents.is_empty() {
        return nodes;
    }
    // A rule whose selector contains a parent reference `&` keeps native
    // CSS-nesting semantics: it nests VERBATIM inside one leading
    // parent-selector shell instead of the descendant join (dart `nestWithin`
    // with `preserveParentSelectors` — through_load_css:top_level_parent).
    let mut preserved: Vec<OutItem> = Vec::new();
    let mut rest: Vec<OutNode> = Vec::new();
    for n in nodes {
        match n {
            OutNode::Rule {
                selectors,
                linebreaks: _,
                items,
                lines,
                extend_base,
            } => {
                if selectors.iter().any(|s| part_has_parent_ref(s)) {
                    preserved.push(OutItem::NestedRule { selectors, items });
                } else {
                    rest.push(OutNode::Rule {
                        selectors: parents
                            .iter()
                            .flat_map(|p| selectors.iter().map(move |s| format!("{p} {s}")))
                            .collect(),
                        linebreaks: Vec::new(),
                        items,
                        lines,
                        extend_base,
                    });
                }
            }
            OutNode::AtRule {
                name,
                prelude,
                body,
                has_block,
                lines,
            } => rest.push(OutNode::AtRule {
                name,
                prelude,
                body: reparent_nodes(body, parents),
                has_block,
                lines,
            }),
            other => rest.push(other),
        }
    }
    let mut out = Vec::new();
    if !preserved.is_empty() {
        out.push(OutNode::Rule {
            selectors: parents.to_vec(),
            linebreaks: Vec::new(),
            items: preserved,
            lines: SrcLines::default(),
            extend_base: usize::MAX,
        });
    }
    out.extend(rest);
    out
}

/// Whether an expression contains a SassScript-only operator (`%`, a
/// comparison, boolean logic) that can never appear in a CSS calculation.
/// dart-sass's parser then treats the whole call as a plain function rather
/// than a calculation (`round(7 % 3, 1)` is the legacy one-argument
/// `math.round` — an arity error).
fn expr_has_non_calc_op(e: &Expr) -> bool {
    match e {
        Expr::Binary { op, lhs, rhs, .. } => {
            matches!(
                op,
                BinOp::Mod
                    | BinOp::Eq
                    | BinOp::Neq
                    | BinOp::Lt
                    | BinOp::Gt
                    | BinOp::Le
                    | BinOp::Ge
                    | BinOp::And
                    | BinOp::Or
                    | BinOp::SingleEq
            ) || expr_has_non_calc_op(lhs)
                || expr_has_non_calc_op(rhs)
        }
        Expr::Div { lhs, rhs, .. } => expr_has_non_calc_op(lhs) || expr_has_non_calc_op(rhs),
        Expr::Unary { operand, .. } => expr_has_non_calc_op(operand),
        Expr::Paren(inner) => expr_has_non_calc_op(inner),
        Expr::List { items, .. } => items.iter().any(expr_has_non_calc_op),
        _ => false,
    }
}

/// The inspect-style spelling of a value rejected from a calculation, for
/// dart-sass's "Value … can't be used in a calculation." error. `null`
/// spells out as `null`, a list is parenthesized (`(1 2 3)`, `(1, 2)`); every
/// other type matches its plain CSS form (`true`, `blue`, `"foo"`, `(b: c)`).
fn calc_value_repr(v: &Value) -> String {
    match v {
        Value::Null => "null".to_string(),
        Value::List(_) => format!("({})", v.to_css(false)),
        other => other.to_css(false),
    }
}

/// Resolve a calc() numeric constant from its (unquoted) ident spelling,
/// case-insensitively: `pi`, `e`, `infinity`/`-infinity`, and `nan`. Returns
/// `None` for any other identifier, which is then kept verbatim.
fn calc_constant(text: &str) -> Option<f64> {
    match text.to_ascii_lowercase().as_str() {
        "pi" => Some(std::f64::consts::PI),
        "e" => Some(std::f64::consts::E),
        "infinity" => Some(f64::INFINITY),
        "-infinity" => Some(f64::NEG_INFINITY),
        "nan" => Some(f64::NAN),
        _ => None,
    }
}

/// Whether `s` is exactly one complete CSS-calculation function call —
/// `name(...)` for a recognized calculation function, with the closing paren
/// at the very end (balanced, nothing trailing). Used so that a `calc()`
/// wrapping a single already-complete calculation (`calc(min(1%, 2px))`)
/// drops its redundant outer `calc()`, matching dart-sass. A non-calculation
/// leaf (`var(--x)`, an unknown function) keeps its wrapper.
/// Whether a single-string operand produced by a *nested* `calc()` must be
/// wrapped in parentheses when spliced into the surrounding calculation.
///
/// dart-sass keeps a nested calc's unresolved interpolation/`var()` operand
/// grouped (`calc(calc(#{"c*"}))` -> `calc((c*))`, `calc(1 + calc(var(--c)))`
/// -> `calc(1 + (var(--c)))`), but a clean single token flattens bare
/// (`calc(calc(c))` -> `calc(c)`, `calc(calc(c-d))` -> `calc(c-d)`). The
/// operand needs grouping when it is not already a complete sub-calculation
/// (`min(…)`, `clamp(…)`, …) and either contains a character that would be
/// ambiguous unparenthesized — whitespace, `*`, `/`, or `\` — or is a `var()`
/// substitution (which dart-sass always treats as an opaque group).
fn nested_calc_needs_parens(s: &str) -> bool {
    if is_complete_calculation(s) {
        return false;
    }
    let trimmed = s.trim_start();
    let is_var = trimmed.len() >= 4 && trimmed[..4].eq_ignore_ascii_case("var(");
    is_var
        || s.chars()
            .any(|c| c.is_whitespace() || matches!(c, '*' | '/' | '\\'))
}

fn is_complete_calculation(s: &str) -> bool {
    let s = s.trim();
    let Some(open) = s.find('(') else { return false };
    if !s.ends_with(')') {
        return false;
    }
    let name = s[..open].trim().to_ascii_lowercase();
    let is_calc_name = matches!(
        name.as_str(),
        "calc"
            | "min"
            | "max"
            | "clamp"
            | "round"
            | "mod"
            | "rem"
            | "sin"
            | "cos"
            | "tan"
            | "asin"
            | "acos"
            | "atan"
            | "atan2"
            | "pow"
            | "sqrt"
            | "exp"
            | "log"
            | "hypot"
            | "abs"
            | "sign"
            | "calc-size"
    );
    if !is_calc_name {
        return false;
    }
    // The opening paren must match the final paren (one balanced call that
    // spans the whole string), so `min(1%, 2px)` qualifies but
    // `min(1%, 2px) + min(…)` (extra trailing content) does not.
    let mut depth = 0u32;
    for (i, c) in s.char_indices() {
        match c {
            '(' => depth += 1,
            ')' => {
                depth -= 1;
                if depth == 0 {
                    return i == s.len() - 1;
                }
            }
            _ => {}
        }
    }
    false
}

/// Convert an evaluated value into a calc operand node. Numbers stay numeric
/// (and can fold); everything else becomes an opaque string token preserved
/// verbatim.
fn value_to_calc_node(v: Value) -> CalcNode {
    match v.without_slash() {
        Value::Number(n) => CalcNode::Number(n),
        Value::Calc(node) => node,
        other => CalcNode::Str(other.to_css(false)),
    }
}

/// Fold a calc operation: combine two compatible numbers into one; raise
/// dart-sass's incompatible-units error for two known-but-cross-dimension
/// operands of `+`/`-`; otherwise keep the operation for canonical
/// serialization. Only the immediate numeric operands are considered, like
/// dart-sass's limited simplification.
fn fold_calc(op: CalcOp, left: CalcNode, right: CalcNode, pos: Pos) -> Result<CalcNode, Error> {
    if let (CalcNode::Number(a), CalcNode::Number(b)) = (&left, &right) {
        if let Some(n) = fold_numbers(op, a, b, pos)? {
            return Ok(CalcNode::Number(n));
        }
    }
    // An addition/subtraction operand that is a purely-numeric multiplication of
    // two unit operands (a compound unit like `1px * 1px`) or a division by a
    // unit operand (an inverse unit like `1 / 1px`) is a number with complex
    // units, which CSS calculations cannot mix into a sum. dart-sass rejects it
    // ("Number calc(1px * 1px) isn't compatible with CSS calculations."). A
    // standalone `calc(1px * 1px)` is fine — only the `+`/`-` context checks.
    if matches!(op, CalcOp::Add | CalcOp::Sub) {
        for operand in [&left, &right] {
            if let Some(node) = calc_complex_unit_operand(operand) {
                return Err(Error::at(
                    format!(
                        "Number calc({}) isn't compatible with CSS calculations.",
                        node.to_calc_css(false)
                    ),
                    pos,
                ));
            }
        }
    }
    Ok(CalcNode::Op {
        op,
        left: Box::new(left),
        right: Box::new(right),
    })
}

/// If `node` is a purely-numeric calc operation that produces a number with
/// complex units — a multiplication of two unit-bearing numeric operands
/// (`1px * 1px`), or a division whose denominator carries a unit (`1 / 1px`) —
/// return the offending node. An operation involving a `var()`/interpolation
/// (opaque) operand is not a resolved number and is left preserved, so it never
/// triggers this check.
fn calc_complex_unit_operand(node: &CalcNode) -> Option<&CalcNode> {
    match node {
        CalcNode::Op {
            op: CalcOp::Mul,
            left,
            right,
        } if calc_node_carries_unit(left) && calc_node_carries_unit(right) => Some(node),
        CalcNode::Op {
            op: CalcOp::Div,
            right,
            ..
        } if calc_node_carries_unit(right) => Some(node),
        _ => None,
    }
}

/// Whether a resolved (no opaque operand) calc node carries a real unit: a
/// unit-bearing number, or a `*`/`/` chain of such numbers. A node containing a
/// `var()`/interpolation is opaque (unknown unit) and reported as not carrying
/// a unit, so it does not count toward a compound/inverse unit.
fn calc_node_carries_unit(node: &CalcNode) -> bool {
    match node {
        CalcNode::Number(n) => !n.is_unitless(),
        CalcNode::Str(_) => false,
        CalcNode::Op {
            op: CalcOp::Mul | CalcOp::Div,
            left,
            right,
        } => calc_node_carries_unit(left) || calc_node_carries_unit(right),
        CalcNode::Op { .. } => false,
        // A nested calculation function has no single determinable unit here.
        CalcNode::Func { .. } => false,
    }
}

/// Try to combine two numbers under a calc operator.
///
/// `Ok(Some(n))` folds them; `Ok(None)` preserves the operation verbatim;
/// `Err` is dart-sass's "<a> and <b> are incompatible." rejection.
///
/// For `+`/`-` dart-sass folds equal units and convertible units (converting
/// the right into the left), but — unlike Sass arithmetic — treats a unitless
/// operand mixed with any real unit as an error, and rejects two known
/// absolute units of different dimensions (`1px + 1s`). Two distinct units
/// where at least one is relative/unknown (`1px + 1vw`, `100% - 10px`) or
/// that share a class but are not convertible (`1khz + 1hz`) are preserved.
///
/// `*`/`/` always fold, with dart-sass unit cancellation: a compound result
/// (`6px * 1s` -> `6px*s`) is a single multi-unit number whose calc
/// serialization spells the units back out as operands.
fn fold_numbers(op: CalcOp, a: &Number, b: &Number, pos: Pos) -> Result<Option<Number>, Error> {
    match op {
        CalcOp::Add | CalcOp::Sub => {
            let apply = |x: f64, y: f64| if op == CalcOp::Add { x + y } else { x - y };
            // A multi-unit operand folds against convertible unit lists;
            // anything else is dart-sass's "isn't compatible with CSS
            // calculations." rejection (quoting the first complex operand).
            if a.has_complex_units() || b.has_complex_units() {
                if let Some(factor) = crate::value::unit_lists_factor(
                    (b.numer_units(), b.denom_units()),
                    (a.numer_units(), a.denom_units()),
                ) {
                    return Ok(Some(a.copy_units(apply(a.value, b.value * factor))));
                }
                let complex = if a.has_complex_units() { a } else { b };
                return Err(Error::at(
                    format!(
                        "Number {} isn't compatible with CSS calculations.",
                        complex.to_css(false)
                    ),
                    pos,
                ));
            }
            // Identical units (incl. `%`, relative units, both unitless)
            // fold; dart compares unit names exactly (`PX` != `px`).
            if a.unit() == b.unit() {
                return Ok(Some(a.copy_units(apply(a.value, b.value))));
            }
            // A unitless operand mixed with a real unit is an error in calc.
            if a.is_unitless() || b.is_unitless() {
                return Err(calc_incompatible(a, b, pos));
            }
            // Two distinct real units: convert when in the same convertible
            // group; error when both are known but cross-dimension; otherwise
            // preserve (a relative/unknown unit is involved).
            if let Some(factor) = crate::value::convert_factor(b.unit(), a.unit()) {
                Ok(Some(a.copy_units(apply(a.value, b.value * factor))))
            } else if crate::value::calc_units_incompatible(a.unit(), b.unit()) {
                Err(calc_incompatible(a, b, pos))
            } else {
                Ok(None)
            }
        }
        CalcOp::Mul => Ok(Some(a.mul(b))),
        CalcOp::Div => Ok(Some(a.div(b))),
    }
}

/// dart-sass's `calc()` incompatible-units error (note: "are incompatible.",
/// distinct from the arithmetic "have incompatible units." wording).
fn calc_incompatible(a: &Number, b: &Number, pos: Pos) -> Error {
    Error::at(
        format!("{} and {} are incompatible.", a.to_css(false), b.to_css(false)),
        pos,
    )
}

/// Evaluate the `/` operator. When `slash` is set and both operands are
/// numbers, produce a slash-separated value that serializes as `a/b` but
/// behaves numerically as the quotient; otherwise perform real division.
pub(crate) fn eval_div(l: Value, r: Value, slash: bool, pos: Pos) -> Result<Value, Error> {
    if let Some(e) = callable_value_error(&l, &r, pos) {
        return Err(e);
    }
    // The parser only sets `slash` when both operands are numeric literals
    // (or themselves slash divisions), so they are always numbers here. The
    // slash-separated value keeps the authored `a/b` spelling; the carried
    // numeric quotient — used if the slash is later forced into arithmetic —
    // is the real division with full unit cancellation (`1/1px` carries
    // `1px^-1`, so `math.unit(1/1px)` reports `"px^-1"`).
    // Fast path: plain `number / number` (the overwhelmingly common case) —
    // no slash carry, no clone. `without_slash` is a no-op on a plain Number,
    // so this is behavior-identical to the first match arm below.
    if !slash {
        if let (Value::Number(a), Value::Number(b)) = (&l, &r) {
            return divide_numbers(a, b, pos);
        }
    }
    // The clones below are only reached for the slash-carry and non-number
    // cases; guarding on `slash` keeps the common path from building the
    // tuple's clones eagerly.
    if slash {
        if let (Value::Number(a), Value::Number(b)) = (l.clone().without_slash(), r.clone().without_slash()) {
            let repr = format!("{}/{}", slash_repr(&l), slash_repr(&r));
            return Ok(Value::Slash(a.div(&b), repr));
        }
    }
    match (l.clone().without_slash(), r.clone().without_slash()) {
        (Value::Number(a), Value::Number(b)) => divide_numbers(&a, &b, pos),
        // dart-sass: `SassColor.dividedBy` throws "Undefined operation" when
        // the right side is a number or another color; any other right side
        // (a string, `var()`, …) falls back to the slash join below
        // (`#AAA/#{itpl}` → `#AAA/itpl`).
        (lv @ Value::Color(_), rv @ (Value::Number(_) | Value::Color(_))) => {
            Err(undefined_op(&lv, "/", &rv, pos))
        }
        // Every other left/right pair (a calculation, `var()`, unquoted
        // string, list, `true`/`null`, or a number divided by a non-number)
        // forms a slash-separated unquoted string `left/right`, mirroring
        // dart-sass's default `Value.dividedBy`. This is what lets a `/` next
        // to a `calc()`/`var()` special value survive (and what carries the
        // alpha slash through `rgb(1 2 var(--x) / 0.4)`). A slash-division
        // operand keeps its chained spelling (`1/2/foo()`, not `0.5/foo()`).
        _ => Ok(Value::Str(SassStr {
            text: format!("{}/{}", slash_repr(&l), slash_repr(&r)),
            quoted: false,
        })),
    }
}

/// Real division of two numbers with dart-sass unit semantics: division never
/// errors on units — convertible units cancel (scaling the value), and
/// whatever remains becomes the quotient's numerator/denominator lists
/// (`math.div(1, 1px)` -> `1px^-1`, `math.div(1px, 1s)` -> `1px/s`).
fn divide_numbers(a: &Number, b: &Number, _pos: Pos) -> Result<Value, Error> {
    Ok(Value::Number(a.div(b)))
}

/// The slash-spelling text of an operand: a slash value keeps its chained
/// `a/b` text; any other value uses its plain CSS form.
fn slash_repr(v: &Value) -> String {
    match v {
        Value::Slash(_, repr) => repr.clone(),
        other => other.to_css(false),
    }
}

fn eval_binary(op: BinOp, l: Value, r: Value, pos: Pos) -> Result<Value, Error> {
    match op {
        BinOp::Add => binary_add(l, r, pos),
        BinOp::Sub => binary_sub(l, r, pos),
        BinOp::Mod => num_binop(l, r, pos, "%", sass_modulo),
        BinOp::Mul => binary_mul(l, r, pos),
        BinOp::Eq => Ok(Value::Bool(l.sass_eq(&r))),
        BinOp::Neq => Ok(Value::Bool(!l.sass_eq(&r))),
        BinOp::Lt => num_compare(l, r, pos, "<", |a, b| a < b),
        BinOp::Gt => num_compare(l, r, pos, ">", |a, b| a > b),
        BinOp::Le => num_compare(l, r, pos, "<=", |a, b| a <= b),
        BinOp::Ge => num_compare(l, r, pos, ">=", |a, b| a >= b),
        BinOp::And | BinOp::Or => Err(Error::unpositioned(
            "internal: and/or are short-circuited in eval_expr",
        )),
        // The single-`=` Microsoft-filter operator joins both evaluated sides
        // with `=` (no surrounding whitespace) into an unquoted string,
        // matching dart-sass (`alpha(opacity=80)` -> `alpha(opacity=80)`).
        BinOp::SingleEq => Ok(Value::Str(SassStr {
            text: format!("{}={}", l.to_css(false), r.to_css(false)),
            quoted: false,
        })),
    }
}

fn num_compare(
    l: Value,
    r: Value,
    pos: Pos,
    sym: &str,
    f: impl Fn(f64, f64) -> bool,
) -> Result<Value, Error> {
    match (l, r) {
        (Value::Number(a), Value::Number(b)) => {
            let (av, bv, _) = coerce_pair(&a, &b, pos)?;
            Ok(Value::Bool(f(av, bv)))
        }
        (l, r) => Err(undefined_op(&l, sym, &r, pos)),
    }
}

fn binary_add(l: Value, r: Value, pos: Pos) -> Result<Value, Error> {
    if let (Value::Number(a), Value::Number(b)) = (&l, &r) {
        let (av, bv, proto) = coerce_pair(a, b, pos)?;
        return Ok(Value::Number(proto.copy_units(av + bv)));
    }
    // dart-sass removed color arithmetic: `color + color`/`color + number`
    // (either order) is "Undefined operation", not string concatenation.
    if color_arith_undefined(&l, &r) {
        return Err(undefined_op(&l, "+", &r, pos));
    }
    if let Some(e) = callable_value_error(&l, &r, pos) {
        return Err(e);
    }
    // A calculation can only be `+`-concatenated with a string; against any
    // other operand (number, color, bool, list, another calculation) dart-sass
    // raises "Undefined operation" rather than string-concatenating.
    let calc_with_nonstring = (matches!(&l, Value::Calc(_)) && !matches!(&r, Value::Str(_)))
        || (matches!(&r, Value::Calc(_)) && !matches!(&l, Value::Str(_)));
    if calc_with_nonstring {
        return Err(undefined_op(&l, "+", &r, pos));
    }
    // A map cannot be serialized for string concatenation, so `map + x`
    // errors like dart-sass with "(…) isn't a valid CSS value.".
    if let Some(m) = find_map(&l).or_else(|| find_map(&r)) {
        return Err(Error::at(
            format!("{} isn't a valid CSS value.", m.to_css(false)),
            pos,
        ));
    }
    // String concatenation. When the left operand is a string the result keeps
    // the left string's quotedness; for any other left operand dart-sass's
    // default `Value.plus` quotes the result iff the right operand is a quoted
    // string (`1 + "x"` -> `"1x"`, `red + "x"` -> `"redx"`).
    let quoted = match &l {
        Value::Str(s) => s.quoted,
        _ => matches!(&r, Value::Str(s) if s.quoted),
    };
    let text = format!("{}{}", concat_str(&l), concat_str(&r));
    Ok(Value::Str(SassStr { text, quoted }))
}

/// The `-` (minus) operator. Two numbers subtract numerically (coercing to a
/// common unit); for any other operand pair dart-sass falls back to its
/// default `Value.minus`, an *unquoted* string join `<left>-<right>` where each
/// side keeps its own serialization (so quoted strings keep their quotes:
/// `"q" - 1` -> `"q"-1`). A `calc()` value has no `minus` overload and errors,
/// and a map cannot serialize as a CSS value.
fn binary_sub(l: Value, r: Value, pos: Pos) -> Result<Value, Error> {
    if let (Value::Number(a), Value::Number(b)) = (&l, &r) {
        let (av, bv, proto) = coerce_pair(a, b, pos)?;
        return Ok(Value::Number(proto.copy_units(av - bv)));
    }
    // Removed color arithmetic: `color - color`/`color - number` (either
    // order) is "Undefined operation", not a string join.
    if color_arith_undefined(&l, &r) {
        return Err(undefined_op(&l, "-", &r, pos));
    }
    if let Some(e) = callable_value_error(&l, &r, pos) {
        return Err(e);
    }
    if matches!(&l, Value::Calc(_)) || matches!(&r, Value::Calc(_)) {
        return Err(undefined_op(&l, "-", &r, pos));
    }
    if let Some(m) = find_map(&l).or_else(|| find_map(&r)) {
        return Err(Error::at(
            format!("{} isn't a valid CSS value.", m.to_css(false)),
            pos,
        ));
    }
    let text = format!("{}-{}", l.to_css(false), r.to_css(false));
    Ok(Value::Str(SassStr { text, quoted: false }))
}

fn binary_mul(l: Value, r: Value, pos: Pos) -> Result<Value, Error> {
    match (l, r) {
        // Units multiply per dart-sass: convertible numerator/denominator
        // pairs cancel, the rest concatenate (`1px * 1em` -> `1px*em`,
        // serialized as `calc(1px * 1em)`).
        (Value::Number(a), Value::Number(b)) => Ok(Value::Number(a.mul(&b))),
        (l, r) => Err(undefined_op(&l, "*", &r, pos)),
    }
}

/// Sass modulo (dart `moduloLikeSass`): a floored modulo whose result takes
/// the divisor's sign. `1.2 % -4.7 == -3.5`, `-1.2 % 4.7 == 3.5`. An
/// infinite dividend (or a zero divisor) yields NaN; an infinite DIVISOR
/// returns the dividend when their signs agree (`1px % infinity*1px == 1px`,
/// signed zeros included) and NaN otherwise.
fn sass_modulo(a: f64, b: f64) -> f64 {
    if a.is_infinite() {
        return f64::NAN;
    }
    if b.is_infinite() {
        // dart compares signIncludingZero, so `-0.0 % -infinity` is `-0.0`.
        return if a.is_sign_negative() == b.is_sign_negative() {
            a
        } else {
            f64::NAN
        };
    }
    if b == 0.0 {
        return f64::NAN;
    }
    a - b * (a / b).floor()
}

fn num_binop(l: Value, r: Value, pos: Pos, sym: &str, f: impl Fn(f64, f64) -> f64) -> Result<Value, Error> {
    match (l, r) {
        (Value::Number(a), Value::Number(b)) => {
            let (av, bv, proto) = coerce_pair(&a, &b, pos)?;
            Ok(Value::Number(proto.copy_units(f(av, bv))))
        }
        (l, r) => Err(undefined_op(&l, sym, &r, pos)),
    }
}

/// Coerce two numbers onto common units for `+`, `-`, `%`, and comparison.
/// The result keeps the LEFT operand's units; the right operand is converted
/// into them (`1in + 1cm` → both in inches, result `in`). When exactly one
/// operand is unitless the other's units are adopted with no rescaling
/// (`5 + 1px` → `6px`). Incompatible units error, matching dart-sass's
/// `<a> and <b> have incompatible units.` (a multi-unit operand prints in its
/// calc form there).
///
/// Returns `(left_value, right_value, prototype)` with both values expressed
/// in the prototype's units (build the result via `prototype.copy_units(..)`).
fn coerce_pair(a: &Number, b: &Number, pos: Pos) -> Result<(f64, f64, Number), Error> {
    let incompatible = || {
        Err(Error::at(
            format!(
                "{} and {} have incompatible units.",
                a.to_css(false),
                b.to_css(false)
            ),
            pos,
        ))
    };
    // A multi-unit operand coerces via full unit-list matching.
    if a.has_complex_units() || b.has_complex_units() {
        if b.is_unitless() {
            return Ok((a.value, b.value, a.clone()));
        }
        if a.is_unitless() {
            return Ok((a.value, b.value, b.clone()));
        }
        return match crate::value::unit_lists_factor(
            (b.numer_units(), b.denom_units()),
            (a.numer_units(), a.denom_units()),
        ) {
            Some(factor) => Ok((a.value, b.value * factor, a.clone())),
            None => incompatible(),
        };
    }
    // Identical units (exact strings, like dart) or a unitless operand never
    // need a numeric conversion.
    if a.unit() == b.unit() || b.is_unitless() {
        return Ok((a.value, b.value, a.clone()));
    }
    if a.is_unitless() {
        return Ok((a.value, b.value, b.clone()));
    }
    // Two distinct real units: convert the right into the left's unit.
    match crate::value::convert_factor(b.unit(), a.unit()) {
        Some(factor) => Ok((a.value, b.value * factor, a.clone())),
        None => incompatible(),
    }
}

fn concat_str(v: &Value) -> String {
    match v {
        Value::Str(s) => s.text.clone(),
        other => other.to_css(false),
    }
}

/// The declaration scope a statement is nested in, for validating that
/// `@function`/`@mixin` declarations appear only where dart-sass allows them.
#[derive(Clone, Copy, PartialEq)]
enum DeclScope {
    /// Top level, a style rule, or a plain at-rule (`@media`): declarations OK.
    Allowed,
    /// Inside `@if`/`@each`/`@for`/`@while` (propagates through style rules).
    Control,
    /// Inside a `@function` body.
    Function,
    /// Inside a `@mixin` body.
    Mixin,
}

/// Reject `@function`/`@mixin` declarations nested where dart-sass forbids
/// them: inside control directives, function bodies, or mixin bodies. Runs once
/// after parsing, so an unexecuted `@while (false) { @function … }` still
/// errors (it is a compile-time, not run-time, restriction).
pub(crate) fn validate_declarations(sheet: &Stylesheet) -> Result<(), Error> {
    validate_decl_scope(&sheet.stmts, DeclScope::Allowed)
}

fn validate_decl_scope(stmts: &[Stmt], scope: DeclScope) -> Result<(), Error> {
    for stmt in stmts {
        match stmt {
            Stmt::FunctionDef(c) => {
                if let Some(msg) = decl_error(scope, "function") {
                    return Err(Error::unpositioned(msg));
                }
                validate_decl_scope(&c.body, DeclScope::Function)?;
            }
            Stmt::MixinDef(c) => {
                if let Some(msg) = decl_error(scope, "mixin") {
                    return Err(Error::unpositioned(msg));
                }
                validate_decl_scope(&c.body, DeclScope::Mixin)?;
            }
            // Control directives establish (or keep) the control/function/mixin
            // scope; a `@function`/`@mixin` body's scope sticks through them.
            Stmt::If(branches) => {
                let inner = enter_control(scope);
                for b in branches {
                    validate_decl_scope(&b.body, inner)?;
                }
            }
            Stmt::For { body, .. } | Stmt::Each { body, .. } | Stmt::While { body, .. } => {
                validate_decl_scope(body, enter_control(scope))?;
            }
            // Style rules and plain at-rules preserve the current scope.
            Stmt::Rule(r) => validate_decl_scope(&r.body, scope)?,
            Stmt::AtRule { body: Some(body), .. }
            | Stmt::Media { body, .. }
            | Stmt::Supports { body, .. }
            | Stmt::AtRoot { body, .. }
            | Stmt::Keyframes { body, .. } => validate_decl_scope(body, scope)?,
            Stmt::Include {
                content: Some(content),
                ..
            } => validate_decl_scope(content, scope)?,
            // A Sass `@import` (one that inlines a partial) is forbidden inside
            // a control directive or a function/mixin body; a plain-CSS
            // `@import` is always allowed (passed through verbatim).
            Stmt::Import(args)
                if scope != DeclScope::Allowed
                    && args.iter().any(|a| matches!(a, ImportArg::Sass { .. })) =>
            {
                return Err(Error::unpositioned(
                    "This at-rule is not allowed here.".to_string(),
                ));
            }
            _ => {}
        }
    }
    Ok(())
}

/// Entering a control directive: a `@function`/`@mixin` body keeps its own
/// scope (declarations inside still get the function/mixin message); otherwise
/// control flow establishes the `Control` scope.
fn enter_control(scope: DeclScope) -> DeclScope {
    match scope {
        DeclScope::Function | DeclScope::Mixin => scope,
        _ => DeclScope::Control,
    }
}

fn decl_error(scope: DeclScope, kind: &str) -> Option<String> {
    match scope {
        DeclScope::Allowed => None,
        DeclScope::Control => Some(format!(
            "{} may not be declared in control directives.",
            if kind == "function" { "Functions" } else { "Mixins" }
        )),
        DeclScope::Function => Some("This at-rule is not allowed here.".to_string()),
        DeclScope::Mixin => Some(format!("Mixins may not contain {kind} declarations.")),
    }
}

/// Whether a `+`/`-` operation is the removed color arithmetic that dart-sass
/// rejects with "Undefined operation": a color combined with another color or a
/// number. A color with a string (or other type) still string-concatenates via
/// the default `Value.plus`/`Value.minus`.
fn color_arith_undefined(l: &Value, r: &Value) -> bool {
    let numeric = |v: &Value| matches!(v, Value::Color(_) | Value::Number(_));
    (matches!(l, Value::Color(_)) && numeric(r)) || (matches!(r, Value::Color(_)) && numeric(l))
}

/// A first-class function or mixin reference is not a valid CSS value, so it
/// cannot appear in arithmetic or a slash: dart-sass errors "<inspect> isn't a
/// valid CSS value." for the first such operand (left before right).
fn callable_value_error(l: &Value, r: &Value, pos: Pos) -> Option<Error> {
    for v in [l, r] {
        let inspect = match v {
            Value::Function(f) => Some(f.inspect()),
            Value::Mixin(m) => Some(m.inspect()),
            _ => None,
        };
        if let Some(s) = inspect {
            return Some(Error::at(format!("{s} isn't a valid CSS value."), pos));
        }
    }
    None
}

fn undefined_op(l: &Value, sym: &str, r: &Value, pos: Pos) -> Error {
    Error::at(
        format!(
            "Undefined operation \"{} {} {}\".",
            l.to_css(false),
            sym,
            r.to_css(false)
        ),
        pos,
    )
}

fn is_css_import(arg: &str) -> bool {
    arg.ends_with(".css")
        || arg.starts_with("http://")
        || arg.starts_with("https://")
        || arg.starts_with("//")
}

/// Append a top-level group's output, prefixing a blank-line separator
/// when there is already prior output (and the group is non-empty).
/// dart-sass omits the blank line after an at-rule, so two adjacent at-rules
/// (or an at-rule followed by a style rule) pack together with no gap.
/// Move every top-level plain-CSS `@import` (a `Raw` node) to the front of the
/// document, preserving their relative order — dart-sass requires CSS `@import`
/// rules to precede all style rules. Imports nested in `@media`/rules are not
/// `Raw` top-level nodes and are unaffected. A no-op when there is at most one
/// import or no rules precede any import.
fn hoist_css_imports(out: &mut Vec<OutNode>) {
    fn is_import(n: &OutNode) -> bool {
        matches!(n, OutNode::Raw(s) if s.starts_with("@import"))
    }
    // Hoisting only kicks in when a CSS `@import` follows a *style-producing*
    // node (a rule/at-rule/declaration). Imports interleaved only with comments
    // and blanks keep their source order (dart-sass preserves comment context).
    // ModuleScope wrappers are transparent for both detection and extraction.
    fn scan(nodes: &[OutNode], seen_css: &mut bool) -> bool {
        for n in nodes {
            match n {
                OutNode::ModuleScope { nodes, .. } => {
                    if scan(nodes, seen_css) {
                        return true;
                    }
                }
                n if is_import(n) => {
                    if *seen_css {
                        return true;
                    }
                }
                OutNode::Blank | OutNode::Comment(..) => {}
                _ => *seen_css = true,
            }
        }
        false
    }
    let mut seen_css = false;
    if !scan(out, &mut seen_css) {
        return;
    }
    // Stage 1 — dart's per-module `_endOfImports`/`_outOfOrderImports`: a
    // root-level plain-CSS import that appears AFTER other css re-inserts at
    // the end of the module's leading import run (comments before any css
    // extend the run; a ModuleScope is transparent but keeps its position).
    // A load-css / import-clone copy scope is dart's `clone: true` splice:
    // the cloned CSS joins the SURROUNDING module's own statements with no
    // module boundary, so its imports take part in the surrounding module's
    // out-of-order handling and leading-run split.
    fn is_clone_scope(key: &str) -> bool {
        key.contains("#copy") || key.contains("#import")
    }
    fn normalize_out_of_order(nodes: Vec<OutNode>) -> Vec<OutNode> {
        let mut queue: std::collections::VecDeque<OutNode> = nodes.into();
        let mut result: Vec<OutNode> = Vec::new();
        let mut out_of_order: Vec<OutNode> = Vec::new();
        let mut frozen = false;
        let mut insert_at = 0usize;
        while let Some(n) = queue.pop_front() {
            match n {
                OutNode::ModuleScope { key, nodes: inner } if is_clone_scope(&key) => {
                    for x in inner.into_iter().rev() {
                        queue.push_front(x);
                    }
                }
                OutNode::ModuleScope { key, nodes: inner } => {
                    result.push(OutNode::ModuleScope {
                        key,
                        nodes: normalize_out_of_order(inner),
                    });
                    if !frozen {
                        insert_at = result.len();
                    }
                }
                n if is_import(&n) => {
                    if frozen {
                        out_of_order.push(n);
                    } else {
                        result.push(n);
                        insert_at = result.len();
                    }
                }
                OutNode::Comment(..) | OutNode::Blank => {
                    result.push(n);
                    if !frozen {
                        insert_at = result.len();
                    }
                }
                other => {
                    frozen = true;
                    result.push(other);
                }
            }
        }
        if !out_of_order.is_empty() {
            result.splice(insert_at..insert_at, out_of_order);
        }
        result
    }
    // Stage 2 — dart `_combineCss`'s visitModule: two buckets. Each module
    // contributes its leading run (comments + plain-CSS @imports up to the
    // LAST import — `_indexAfterImports`) to the `imports` bucket and
    // everything after to the `css` flow. Comments written before a `@use`
    // (sitting before a ModuleScope here) are that module's
    // preModuleComments: they go to the imports bucket while the css flow is
    // still empty, and stay in place afterwards. The css flow keeps its
    // ModuleScope structure.
    fn visit(nodes: Vec<OutNode>, imports: &mut Vec<OutNode>, css_seen: &mut bool) -> Vec<OutNode> {
        let mut rest: Vec<OutNode> = Vec::new();
        let mut iter = nodes.into_iter().peekable();
        // Phase 1: pre-module comment runs and embedded upstream modules.
        let mut pending: Vec<OutNode> = Vec::new();
        loop {
            match iter.peek() {
                Some(OutNode::Comment(..)) | Some(OutNode::Blank) => {
                    pending.push(iter.next().unwrap());
                }
                Some(OutNode::ModuleScope { .. }) => {
                    let Some(OutNode::ModuleScope { key, nodes: inner }) = iter.next() else {
                        unreachable!()
                    };
                    // preModuleComments: into the imports bucket only while
                    // no css flowed yet (dart `css.isEmpty ? imports : css`).
                    if !*css_seen {
                        imports.extend(pending.drain(..).filter(|n| !matches!(n, OutNode::Blank)));
                    } else {
                        rest.append(&mut pending);
                    }
                    let inner_rest = visit(inner, imports, css_seen);
                    if !inner_rest.is_empty() {
                        *css_seen = true;
                        // Re-group the module's remaining flow: pulling its
                        // leading imports out makes previously-separated
                        // top-level neighbors adjacent, so the blank-line
                        // separators are recomputed like dart's serializer.
                        let mut regrouped: Vec<OutNode> = Vec::new();
                        for n in inner_rest {
                            match n {
                                OutNode::Blank => {}
                                other => push_group(&mut regrouped, vec![other]),
                            }
                        }
                        rest.push(OutNode::ModuleScope {
                            key,
                            nodes: regrouped,
                        });
                    }
                }
                _ => break,
            }
        }
        // Phase 2: the module's own statements — `_indexAfterImports` over
        // the remaining sequence (pending comments are its leading run).
        let mut own: Vec<OutNode> = pending;
        own.extend(iter);
        let mut last_import: Option<usize> = None;
        for (i, n) in own.iter().enumerate() {
            if is_import(n) {
                last_import = Some(i);
            } else if !matches!(n, OutNode::Comment(..) | OutNode::Blank) {
                break;
            }
        }
        if let Some(li) = last_import {
            let tail = own.split_off(li + 1);
            imports.extend(own.into_iter().filter(|n| !matches!(n, OutNode::Blank)));
            own = tail;
        }
        if own.iter().any(|n| !matches!(n, OutNode::Blank)) {
            *css_seen = true;
        }
        rest.extend(own);
        rest
    }
    let original = normalize_out_of_order(std::mem::take(out));
    let mut imports = Vec::new();
    let mut css_seen = false;
    let rest = visit(original, &mut imports, &mut css_seen);
    out.extend(imports);
    // Regroup the css flow, dropping stale top-level blanks.
    for node in rest {
        match node {
            OutNode::Blank => {}
            other => push_group(out, vec![other]),
        }
    }
}

/// Splice an already-grouped node sequence (a module's captured CSS) into a
/// sink. Into a top-level sink the whole sequence is ONE group — its internal
/// `Blank` separators are preserved and exactly one separator is added before
/// it — instead of per-node `push_group` calls that would double the blanks.
fn splice_nodes(sink: &mut Sink<'_>, nodes: Vec<OutNode>) {
    match sink {
        Sink::Top(out) => push_group(out, nodes),
        _ => {
            for n in nodes {
                if !matches!(n, OutNode::Blank) {
                    sink.push_at_rule(n);
                }
            }
        }
    }
}

/// Drop leading blank separators (an unwrapped module-scope boundary can
/// leave one at the head of a cloned subtree).
fn trim_leading_blanks(nodes: &mut Vec<OutNode>) {
    while matches!(nodes.first(), Some(OutNode::Blank)) {
        nodes.remove(0);
    }
}

/// Sentinel marking the end of a completed top-level style rule's output
/// group (dart-sass `isGroupEnd`): the next group gets a blank line even when
/// the group ended in a bubbled at-rule. Consumed by the next `push_group`;
/// any survivor is skipped by the emitters.
const STYLE_GROUP_END: &str = "\u{0}STYLE_GROUP_END\u{0}";

fn push_group(out: &mut Vec<OutNode>, mut group: Vec<OutNode>) {
    if group.is_empty() {
        return;
    }
    // A pack-tight or group-end sentinel attaches to the previous group
    // verbatim — no separator logic now; the NEXT group packs tight against
    // a pack-tight sentinel and blank-separates after a group-end one.
    if group.len() == 1
        && matches!(&group[0], OutNode::Raw(s) if s == AT_ROOT_PACK_TIGHT || s == STYLE_GROUP_END)
    {
        out.append(&mut group);
        return;
    }
    // The last EFFECTIVE node before this group: module-scope wrappers are
    // judged by their last non-blank child (a module's captured CSS may end
    // in a style-group-end sentinel from its own evaluation).
    fn last_effective(n: &OutNode) -> &OutNode {
        if let OutNode::ModuleScope { nodes, .. } = n {
            if let Some(l) = nodes.iter().rev().find(|x| !matches!(x, OutNode::Blank)) {
                return last_effective(l);
            }
        }
        n
    }
    // A completed style rule always separates from the next group (dart
    // isGroupEnd); a top-level sentinel is consumed here, one inside a
    // wrapper just informs the decision (the emitters skip it).
    let top_marker = matches!(out.last(), Some(OutNode::Raw(s)) if s == STYLE_GROUP_END);
    if top_marker {
        out.pop();
    }
    let last_eff = out.last().map(last_effective);
    let prev_group_end = top_marker || matches!(last_eff, Some(OutNode::Raw(s)) if s == STYLE_GROUP_END);
    // dart-sass never prefixes a blank line after an at-rule, a passed-through
    // CSS `@import` (a `Raw` at-rule), or a loud comment: the next group packs
    // tight against them. A blank line is only inserted after a style rule (or
    // top-level declaration) that already emitted CSS.
    let prev_packs_tight = match last_eff {
        Some(OutNode::AtRule { .. } | OutNode::Comment(..)) => true,
        Some(OutNode::Raw(s)) => s != STYLE_GROUP_END,
        _ => false,
    };
    // A consumed group-end sentinel forces the separator even when popping it
    // emptied `out` (a stripped sourceMappingURL comment leading the document:
    // dart still writes a leading blank before the first emitted node).
    if (top_marker || !out.is_empty()) && (prev_group_end || !prev_packs_tight) {
        out.push(OutNode::Blank);
    }
    out.append(&mut group);
}

/// The integer indices a `@for` iterates: ascending or descending, with the
/// end included (`through`) or excluded (`to`).
/// Normalize a Sass argument/parameter name: hyphens and underscores are
/// interchangeable, so `$b-c` and `$b_c` refer to the same parameter. A name
/// containing CSS escapes is decoded first, so the raw definition spelling
/// `foo\func` and a call site's canonical `foo\f unc` agree (issue_553) —
/// dart decodes escapes into the identifier text at parse time.
fn normalize_arg_name(name: &str) -> String {
    if name.contains('\\') {
        return decode_ident_escapes(name).replace('_', "-");
    }
    name.replace('_', "-")
}

/// Decode CSS escapes (`\66 ` / `\func` / `\\`) to their code points: up to
/// six hex digits terminated by one optional whitespace, or a literal next
/// character. NUL decodes to U+FFFD like CSS.
fn decode_ident_escapes(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut it = s.chars().peekable();
    while let Some(c) = it.next() {
        if c != '\\' {
            out.push(c);
            continue;
        }
        let mut hex = String::new();
        while hex.len() < 6 && it.peek().is_some_and(|h| h.is_ascii_hexdigit()) {
            hex.push(it.next().unwrap());
        }
        if hex.is_empty() {
            match it.next() {
                Some(l) => out.push(l),
                None => out.push('\\'),
            }
        } else {
            let cp = u32::from_str_radix(&hex, 16).unwrap_or(0xFFFD);
            out.push(match char::from_u32(cp) {
                Some('\0') | None => '\u{FFFD}',
                Some(ch) => ch,
            });
            if matches!(it.peek(), Some(' ' | '\t' | '\n')) {
                it.next();
            }
        }
    }
    out
}

/// Whether `name` is a global CSS-calculation function that dart-sass parses
/// as a calculation expression, and so cannot accept a `...` rest argument
/// (`clamp`, `hypot`, the exponent/trig functions). `min`/`max` are excluded:
/// they are variadic Sass functions that also accept a splat.
fn is_calc_function(name: &str) -> bool {
    matches!(name, "clamp" | "hypot" | "atan2" | "log" | "pow")
}

/// Whether `name` is a fixed-arity math calculation (`sin`, `cos`, `sqrt`,
/// `pow`, `log`, `hypot`, …) that dart-sass parses as a calculation rather than
/// an ordinary SassScript function. Matched case-insensitively. The legacy
/// global functions `abs`/`round`/`min`/`max`/`ceil`/`floor` are deliberately
/// excluded: they fall back to the Sass math builtin (with a deprecation
/// warning) instead of rejecting non-calculation operands, and `clamp`/`min`/
/// `max` keep their dedicated builtin preservation.
fn is_pure_calc_math_function(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    matches!(
        lower.as_str(),
        "sin"
            | "cos"
            | "tan"
            | "asin"
            | "acos"
            | "atan"
            | "atan2"
            | "exp"
            | "log"
            | "pow"
            | "hypot"
            | "sqrt"
            | "sign"
            | "mod"
            | "rem"
    )
}

/// Whether a calc node carries an opaque operand — a `var()`, interpolation, or
/// unknown identifier preserved verbatim — anywhere in its tree. Such a node
/// cannot reduce to a single number, so a math calculation containing it stays
/// preserved (`sin(2px + var(--c))`).
fn calc_node_has_opaque(node: &CalcNode) -> bool {
    match node {
        CalcNode::Number(_) => false,
        CalcNode::Str(_) => true,
        CalcNode::Op { left, right, .. } => calc_node_has_opaque(left) || calc_node_has_opaque(right),
        // A nested calculation function is already preserved, so a calc holding
        // it cannot reduce to a single number.
        CalcNode::Func { .. } => true,
    }
}

/// Serialize an unquoted string as dart-sass `_visitUnquotedString` does: each
/// newline becomes a single space, and any whitespace immediately following a
/// newline is dropped. Used for `@supports` custom-property values.
fn unquoted_string_css(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut after_newline = false;
    for ch in s.chars() {
        match ch {
            '\n' => {
                out.push(' ');
                after_newline = true;
            }
            ' ' => {
                if !after_newline {
                    out.push(' ');
                }
            }
            other => {
                after_newline = false;
                out.push(other);
            }
        }
    }
    out
}

/// Whether `name` is a CSS math function that dart-sass parses as a calculation
/// (and so keeps unsimplified inside a `@supports` declaration). Matched
/// case-insensitively, mirroring dart-sass's calculation-function set.
fn is_supports_calc_function(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    matches!(
        lower.as_str(),
        "min"
            | "max"
            | "clamp"
            | "round"
            | "mod"
            | "rem"
            | "abs"
            | "sign"
            | "sin"
            | "cos"
            | "tan"
            | "asin"
            | "acos"
            | "atan"
            | "atan2"
            | "exp"
            | "sqrt"
            | "pow"
            | "log"
            | "hypot"
    )
}

/// Find a map anywhere in a value (including nested in a list), returning a
/// reference to the first one. Used to reject maps in CSS output positions,
/// where dart-sass errors with "(…) isn't a valid CSS value.".
fn find_map(v: &Value) -> Option<&Map> {
    match v {
        Value::Map(m) => Some(m),
        Value::List(l) => l.items.iter().find_map(find_map),
        _ => None,
    }
}

fn for_indices(start: i64, end: i64, inclusive: bool) -> Vec<i64> {
    let mut out = Vec::new();
    if start <= end {
        let last = if inclusive { end } else { end - 1 };
        let mut i = start;
        while i <= last {
            out.push(i);
            i += 1;
        }
    } else {
        let last = if inclusive { end } else { end + 1 };
        let mut i = start;
        while i >= last {
            out.push(i);
            i -= 1;
        }
    }
    out
}

/// The diagnostic stack-frame name for an `@include`: dart-sass prints the bare
/// mixin name with empty parens (`name()`), without the `ns.` namespace.
fn mixin_frame_name(name: &str, _module: &Option<String>) -> String {
    format!("{name}()")
}

/// Whether a mixin body contains a reachable `@content`. dart-sass scans the
/// whole body tree — control flow, at-rules, nested style rules, and nested
/// `@include` content blocks all count (nested mixin/function definitions are
/// disallowed by the grammar, so there is no separate scope to exclude).
fn body_uses_content(body: &[Stmt]) -> bool {
    body.iter().any(stmt_uses_content)
}

fn stmt_uses_content(stmt: &Stmt) -> bool {
    match stmt {
        Stmt::Content(_) => true,
        Stmt::Rule(r) => body_uses_content(&r.body),
        Stmt::If(branches) => branches.iter().any(|b| body_uses_content(&b.body)),
        Stmt::For { body, .. }
        | Stmt::Each { body, .. }
        | Stmt::While { body, .. }
        | Stmt::Media { body, .. }
        | Stmt::AtRoot { body, .. }
        | Stmt::Keyframes { body, .. } => body_uses_content(body),
        Stmt::AtRule { body: Some(body), .. } => body_uses_content(body),
        Stmt::Include {
            content: Some(content),
            ..
        } => body_uses_content(content),
        _ => false,
    }
}

/// Validate a (post-interpolation) selector string against the subset of
/// dart-sass's parser rules this build can safely enforce:
///   * `&` may appear only at the beginning of a compound selector (so `b&`,
///     `[x]&`, `.y&` are all errors). A `&` followed directly by an
///     identifier-name character (`a`, `-`, `_`, digit, `\`) is a "suffix":
///     at the document root (no parent) that is an error, but inside a style
///     rule it concatenates onto the parent.
///   * A `%` placeholder must be followed directly by an identifier name-start
///     character; a bare `%` (or `%` before `.`, a digit, whitespace, …) is
///     "Expected identifier.". A `%` right after a digit is a percentage
///     keyframe selector (`10%`), not a placeholder.
///   * An `[…]` attribute selector's modifier must be a single ASCII letter
///     immediately before the closing `]`.
///
/// Quoted strings (with `\` escapes) and the contents of nested `[…]`/`(…)`
/// groups are skipped so combinators/`&`/`%` inside them are not misread.
/// Reject the selector forms plain CSS forbids in one comma-part: a placeholder
/// (`%x`), a parent reference with a suffix (`&x`), a top-level leading
/// combinator (`> a`), and a trailing combinator (`a >`). The text is the
/// already-resolved selector (no interpolation left).
/// The parent directory of a resolved file key, for relative URL resolution
/// (`None` when the key has no directory component or is not a path).
fn dirname_of(key: &str) -> Option<String> {
    let p = std::path::Path::new(key);
    p.parent()
        .filter(|d| !d.as_os_str().is_empty())
        .map(|d| d.to_string_lossy().into_owned())
}

/// Sentinel left in an enclosing `@media` body where a merged nested media
/// rule bubbled out; the outer rule splits its own children around it.
const MEDIA_HOIST_MARKER: &str = "\u{0}MEDIA_HOIST\u{0}";

/// Sentinel left where an `@at-root` hoisted a batch out of one or more
/// enclosing at-rules, suffixed with the batch's graft target (the index of
/// the topmost EXCLUDED at-rule layer — dart `_trimIncluded`). Each enclosing
/// layer below the target splits around the marker and passes it outward; the
/// layer whose body sits at the target depth consumes it — target 0 means the
/// batch re-enters at the document root, between the outermost layer's
/// segments, while a deeper target grafts INTO that layer's own body.
const AT_ROOT_HOIST_MARKER: &str = "\u{0}AT_ROOT_HOIST\u{0}";

/// Trailing sentinel after a placed at-root batch: the next top-level group
/// packs tight against it (no blank line), and the emitters skip it.
const AT_ROOT_PACK_TIGHT: &str = "\u{0}ATR_TIGHT\u{0}";

/// An `@at-root` batch awaiting its graft point (paired with a hoist marker).
struct AtRootBatch {
    /// Index of the topmost excluded at-rule layer = the depth the batch
    /// re-enters the tree at (0 = document root).
    target: usize,
    /// Whether the `@at-root` ran with no enclosing style rule: dart then
    /// marks the batch's last node as a group end (the next root-level node
    /// gets a blank line) instead of packing tight.
    group_end: bool,
    nodes: Vec<OutNode>,
}

/// Parse an `@at-root` hoist marker's encoded graft target.
fn at_root_marker_target(s: &str) -> Option<usize> {
    s.strip_prefix(AT_ROOT_HOIST_MARKER).and_then(|t| t.parse().ok())
}

/// Whether `n` is a hoist marker whose batch escapes a body at `depth`:
/// media hoists always escape; an at-root batch escapes when its graft
/// target lies outside this body. Escaping markers are transparent to
/// block anchoring (the batch is not a sibling inside this node).
fn is_escaping_marker(n: &OutNode, depth: usize) -> bool {
    match n {
        OutNode::Raw(s) => s == MEDIA_HOIST_MARKER || at_root_marker_target(s).is_some_and(|t| t < depth),
        _ => false,
    }
}

/// One enclosing at-rule layer recorded for `@at-root` queries: the data
/// needed to re-wrap a hoisted body in that layer (dart's "included" copies).
#[derive(Clone)]
enum AtCtx {
    Media { prelude: String },
    Supports { prelude: String },
    Keyframes { name: String, prelude: String },
}

impl AtCtx {
    /// The query name this layer matches (dart `AtRootQuery.excludes`).
    fn query_name(&self) -> &'static str {
        match self {
            AtCtx::Media { .. } => "media",
            AtCtx::Supports { .. } => "supports",
            AtCtx::Keyframes { .. } => "keyframes",
        }
    }

    /// Wrap `body` in this layer's at-rule node.
    fn wrap(&self, body: Vec<OutNode>) -> OutNode {
        match self {
            AtCtx::Media { prelude } => OutNode::AtRule {
                name: "media".to_string(),
                prelude: prelude.clone(),
                body,
                has_block: true,
                lines: SrcLines::default(),
            },
            AtCtx::Supports { prelude } => OutNode::AtRule {
                name: "supports".to_string(),
                prelude: prelude.clone(),
                body,
                has_block: true,
                lines: SrcLines::default(),
            },
            AtCtx::Keyframes { name, prelude } => OutNode::AtRule {
                name: name.clone(),
                prelude: prelude.clone(),
                body,
                has_block: true,
                lines: SrcLines::default(),
            },
        }
    }
}

/// A parsed `@at-root` query (dart `AtRootQuery`): `(with: …)` keeps only
/// the named layers, `(without: …)` drops them, `all` matches every layer,
/// and the default (no query) is `(without: rule)`.
struct AtRootQuery {
    include: bool,
    names: Vec<String>,
    all: bool,
    rule: bool,
}

impl AtRootQuery {
    fn parse(text: Option<&str>) -> AtRootQuery {
        let Some(text) = text else {
            return AtRootQuery {
                include: false,
                names: vec!["rule".to_string()],
                all: false,
                rule: true,
            };
        };
        let inner = text.trim().trim_start_matches('(').trim_end_matches(')');
        let (include, list) = match inner.split_once(':') {
            Some((k, v)) if k.trim().eq_ignore_ascii_case("with") => (true, v),
            Some((_, v)) => (false, v),
            None => (false, inner),
        };
        let names: Vec<String> = list
            .split_whitespace()
            .map(|s| s.trim_matches('"').trim_matches('\'').to_ascii_lowercase())
            .collect();
        let all = names.iter().any(|n| n == "all");
        let rule = names.iter().any(|n| n == "rule");
        AtRootQuery {
            include,
            names,
            all,
            rule,
        }
    }

    /// Whether the query excludes style rules (dart `excludesStyleRules`).
    fn excludes_style_rules(&self) -> bool {
        (self.all || self.rule) != self.include
    }

    /// Whether the query excludes the layer named `name`.
    fn excludes_name(&self, name: &str) -> bool {
        if self.all {
            return !self.include;
        }
        self.names.iter().any(|n| n == name) != self.include
    }
}

/// Normalize a keyframe selector: a percentage stop's scientific-notation
/// marker is lowercased (`130E-1%` -> `130e-1%`); everything else (including
/// the digits and `from`/`to`) is left verbatim.
fn normalize_keyframe_selector(s: &str) -> String {
    if !s.contains('E') {
        return s.to_string();
    }
    let t = s.trim();
    let is_pct = t.ends_with('%')
        && t[..t.len() - 1]
            .chars()
            .all(|c| c.is_ascii_digit() || matches!(c, '.' | '+' | '-' | 'e' | 'E'));
    if is_pct {
        s.replace('E', "e")
    } else {
        s.to_string()
    }
}

/// Convert an at-rule-body node list (as produced by `eval_at_body` with no
/// parents) into rule items, for at-rules nested verbatim inside keyframe
/// blocks.
fn at_body_to_items(nodes: Vec<OutNode>) -> Vec<OutItem> {
    let mut items = Vec::new();
    for n in nodes {
        match n {
            OutNode::AtDecl {
                prop,
                value,
                important,
                custom,
                lines,
            } => items.push(OutItem::Decl {
                prop,
                value,
                important,
                custom,
                lines,
            }),
            OutNode::Comment(t, lines) => items.push(OutItem::Comment(t, lines)),
            OutNode::Rule {
                selectors, items: ri, ..
            } => items.push(OutItem::NestedRule { selectors, items: ri }),
            OutNode::AtRule {
                name,
                prelude,
                body,
                has_block,
                lines,
            } => {
                if has_block {
                    items.push(OutItem::NestedAtRule {
                        name,
                        prelude,
                        items: at_body_to_items(body),
                    });
                } else {
                    items.push(OutItem::ChildlessAtRule { name, prelude, lines });
                }
            }
            OutNode::ModuleScope { nodes, .. } => items.extend(at_body_to_items(nodes)),
            OutNode::Raw(_) | OutNode::Blank => {}
        }
    }
    items
}

fn validate_plain_css_selector(part: &str, top_level: bool) -> Result<(), Error> {
    let trimmed = part.trim();
    let chars: Vec<char> = trimmed.chars().collect();
    // A leading combinator is allowed when *nested* (it joins onto the parent),
    // but not at the top level.
    if top_level && matches!(chars.first(), Some('>' | '+' | '~')) {
        return Err(Error::unpositioned(
            "Top-level leading combinators aren't allowed in plain CSS.",
        ));
    }
    // A trailing combinator never has a selector to bind to.
    if matches!(chars.last(), Some('>' | '+' | '~')) {
        return Err(Error::unpositioned("expected selector."));
    }
    let mut i = 0;
    // True at the start of each compound (start, or after a combinator/space).
    let mut at_compound_start = true;
    let mut depth = 0i32; // inside `[...]`/`(...)`
    while i < chars.len() {
        let c = chars[i];
        match c {
            '\\' => {
                i += 2;
                at_compound_start = false;
                continue;
            }
            '[' | '(' => depth += 1,
            ']' | ')' => depth -= 1,
            _ if depth > 0 => {}
            ' ' | '\t' | '\n' | '\r' | '>' | '+' | '~' => at_compound_start = true,
            '%' if at_compound_start => {
                return Err(Error::unpositioned(
                    "Placeholder selectors aren't allowed in plain CSS.",
                ));
            }
            '&' => {
                let next = chars.get(i + 1).copied();
                if matches!(next, Some(n) if n.is_ascii_alphanumeric() || n == '-' || n == '_' || n == '\\') {
                    return Err(Error::unpositioned(
                        "Parent selectors can't have suffixes in plain CSS.",
                    ));
                }
                at_compound_start = false;
            }
            _ => at_compound_start = false,
        }
        i += 1;
    }
    Ok(())
}

/// Whether the `(` at `chars[open]` directly follows a pseudo-class/element
/// name: a non-empty run of identifier characters whose preceding character is
/// a `:` (`:not(`, `::-webkit-any(`).
fn paren_follows_pseudo(chars: &[char], open: usize) -> bool {
    let mut j = open;
    while j > 0 {
        let p = chars[j - 1];
        if p.is_ascii_alphanumeric() || p == '-' || p == '_' || (p as u32) >= 0x80 {
            j -= 1;
        } else {
            break;
        }
    }
    j < open && j > 0 && chars[j - 1] == ':'
}

fn validate_selector(sel: &str, has_parent: bool) -> Result<(), Error> {
    // A selector list whose FIRST comma part is empty is dart-sass's
    // "expected selector." (`,b`); later empty parts (`a,,b`, trailing `a,`)
    // are tolerated and skipped.
    if sel.trim_start().starts_with(',') {
        return Err(Error::unpositioned("expected selector."));
    }
    // Parens and brackets must nest properly: `a:b([c)]` is dart's
    // `expected "]".` (a `)` closing while a `[` is still open). A selector
    // without any bracket/quote/escape byte cannot mis-nest — skip the scan.
    if sel
        .bytes()
        .any(|c| matches!(c, b'(' | b'[' | b')' | b']' | b'"' | b'\'' | b'\\'))
    {
        let mut stack: Vec<char> = Vec::new();
        let mut quote: Option<char> = None;
        let mut prev_escape = false;
        for c in sel.chars() {
            if prev_escape {
                prev_escape = false;
                continue;
            }
            match c {
                '\\' => prev_escape = true,
                q @ ('"' | '\'') => match quote {
                    Some(open) if open == q => quote = None,
                    Some(_) => {}
                    None => quote = Some(q),
                },
                _ if quote.is_some() => {}
                '(' | '[' => stack.push(c),
                ')' | ']' => {
                    let open = stack.pop();
                    if c == ')' && open == Some('[') {
                        return Err(Error::unpositioned("expected \"]\"."));
                    }
                    if c == ']' && open == Some('(') {
                        return Err(Error::unpositioned("expected \")\"."));
                    }
                }
                _ => {}
            }
        }
    }
    // The `:nth-*` pseudos require an An+B argument: `:nth-child()` is
    // dart's selector-parse error `Expected "n".` (issue_2175). Gated on a
    // zero-alloc case-insensitive ":nth-" byte scan — the lowercase copy and
    // four substring searches below cost real allocations per selector.
    if sel.as_bytes().windows(5).any(|w| {
        w[0] == b':'
            && (w[1] | 0x20) == b'n'
            && (w[2] | 0x20) == b't'
            && (w[3] | 0x20) == b'h'
            && w[4] == b'-'
    }) {
        let lower = sel.to_ascii_lowercase();
        for pat in [
            ":nth-child(",
            ":nth-last-child(",
            ":nth-of-type(",
            ":nth-last-of-type(",
        ] {
            let mut from = 0;
            while let Some(p) = lower[from..].find(pat) {
                let start = from + p + pat.len();
                if lower[start..].trim_start().starts_with(')') {
                    return Err(Error::unpositioned("Expected \"n\"."));
                }
                from = start;
            }
        }
    }
    // One byte pre-scan classifies the rest of the validation: most resolved
    // selectors are plain (idents/classes/combinators/spaces) and need at
    // most the sigil ident-start check — no char-vector materialization, no
    // comma split. Every rejection or recursion in the full walk below is
    // triggered by one of the "slow" bytes, except the `#`/`.` ident-start
    // rule, which the byte-only light path reproduces exactly (UTF-8
    // continuation bytes are >= 0x80, so byte lookarounds match char ones).
    let mut needs_slow = false;
    let mut has_sigil = false;
    for &b in sel.as_bytes() {
        match b {
            b'\\' | b'"' | b'\'' | b'[' | b'(' | b')' | b']' | b'&' | b'%' | b'/' => needs_slow = true,
            b'#' | b'.' => has_sigil = true,
            _ => {}
        }
    }
    // Equivalence of the light/skip paths against the full walk was proven
    // by a check build asserting identical Results on every call across the
    // full sass-spec suite.
    if needs_slow {
        validate_selector_tail(sel, has_parent)
    } else if has_sigil {
        validate_plain_sigils(sel)
    } else {
        Ok(())
    }
}

/// The `#`/`.` ident-start rule on a selector with no escape, quote,
/// bracket, paren, `&`, `%`, or `/` byte: every sigil is top-level, and its
/// next character must start an identifier (a `.` right after a digit is a
/// keyframe decimal point and is skipped; `#` gets no such exemption).
fn validate_plain_sigils(sel: &str) -> Result<(), Error> {
    let b = sel.as_bytes();
    for i in 0..b.len() {
        let c = b[i];
        if c != b'#' && c != b'.' {
            continue;
        }
        if c == b'.' && i > 0 && b[i - 1].is_ascii_digit() {
            continue;
        }
        let starts_ident = match b.get(i + 1) {
            Some(&n) => n.is_ascii_alphabetic() || n == b'-' || n == b'_' || n >= 0x80,
            None => false,
        };
        if !starts_ident {
            return Err(Error::unpositioned("Expected identifier."));
        }
    }
    Ok(())
}

/// The full per-part validation walk (slow path).
fn validate_selector_tail(sel: &str, has_parent: bool) -> Result<(), Error> {
    for part in split_commas(sel) {
        let chars: Vec<char> = part.chars().collect();
        let mut i = 0;
        // True at the start of each compound selector (start of the part and
        // immediately after any combinator or whitespace).
        let mut at_compound_start = true;
        let mut depth = 0i32; // inside `[...]` or `(...)`
        while i < chars.len() {
            let c = chars[i];
            match c {
                '\\' => {
                    // An escape consumes the following character verbatim.
                    i += 2;
                    at_compound_start = false;
                    continue;
                }
                '"' | '\'' => {
                    i = skip_string(&chars, i);
                    at_compound_start = false;
                    continue;
                }
                '[' if depth == 0 => {
                    let end = matching_bracket(&chars, i);
                    validate_attribute(&chars[i + 1..end])?;
                    i = end + 1;
                    at_compound_start = false;
                    continue;
                }
                // A top-level `(` is only valid as a pseudo-class/element
                // argument list (`:not(…)`, `::part(…)`): the run of identifier
                // characters directly before it must follow a `:`. Anywhere
                // else — compound start, after a plain identifier, after `]` —
                // dart-sass reports "expected selector." (`a(b)`, `a (b)`).
                '(' if depth == 0 => {
                    if !paren_follows_pseudo(&chars, i) {
                        return Err(Error::unpositioned("expected selector."));
                    }
                    depth += 1;
                    at_compound_start = false;
                }
                // A stray top-level closer never matches an open bracket.
                ')' if depth == 0 => {
                    return Err(Error::unpositioned("Unexpected \")\"."));
                }
                '[' | '(' => {
                    depth += 1;
                    at_compound_start = false;
                }
                ']' | ')' => {
                    depth -= 1;
                    at_compound_start = false;
                }
                _ if depth > 0 => {}
                ' ' | '\t' | '\n' | '\r' => at_compound_start = true,
                '>' | '+' | '~' => at_compound_start = true,
                '&' => {
                    if !at_compound_start {
                        return Err(Error::unpositioned(
                            "\"&\" may only used at the beginning of a compound selector.",
                        ));
                    }
                    let next = chars.get(i + 1).copied();
                    let is_suffix = matches!(next, Some(n) if n.is_ascii_alphanumeric() || n == '-' || n == '_' || n == '\\');
                    if is_suffix && !has_parent {
                        return Err(Error::unpositioned(
                            "A top-level selector may not contain a parent selector with a suffix.",
                        ));
                    }
                    at_compound_start = false;
                }
                '%' => {
                    let prev_is_digit = i > 0 && chars[i - 1].is_ascii_digit();
                    if !prev_is_digit {
                        let next = chars.get(i + 1).copied();
                        let starts_ident = matches!(next, Some(n) if n.is_ascii_alphabetic() || n == '-' || n == '_' || n == '\\');
                        if !starts_ident {
                            return Err(Error::unpositioned("Expected identifier."));
                        }
                    }
                    at_compound_start = false;
                }
                // A `#`/`.` (id/class) must be followed by an identifier name
                // start; `#2b` / `.3c` are "Expected identifier." (a `-`, `_`,
                // letter, escape, or non-ASCII char is fine). A `.` right after a
                // digit is a decimal point (a keyframe stop like `50.5%`), not a
                // class, so it is skipped. A bare digit *type* selector (`1a`) is
                // also left alone: `50%` keyframe stops reach this same validator.
                '#' | '.' if !(c == '.' && i > 0 && chars[i - 1].is_ascii_digit()) => {
                    let next = chars.get(i + 1).copied();
                    let starts_ident = matches!(next, Some(n) if n.is_ascii_alphabetic() || n == '-' || n == '_' || n == '\\' || (n as u32) >= 0x80);
                    if !starts_ident {
                        return Err(Error::unpositioned("Expected identifier."));
                    }
                    at_compound_start = false;
                }
                // A reference combinator (`/foo/`) used to be valid CSS but is
                // no longer supported; dart-sass now rejects any top-level `/`
                // in a selector with "expected selector.". (A `/` inside an
                // attribute value or a pseudo argument is at depth > 0 and is
                // handled above.)
                '/' => {
                    return Err(Error::unpositioned("expected selector."));
                }
                _ => at_compound_start = false,
            }
            i += 1;
        }
    }
    Ok(())
}

/// Index just past a quoted string starting at `start` (a `"` or `'`),
/// honouring `\` escapes. Returns `chars.len()` for an unterminated string.
fn skip_string(chars: &[char], start: usize) -> usize {
    let quote = chars[start];
    let mut i = start + 1;
    while i < chars.len() {
        match chars[i] {
            '\\' => i += 2,
            c if c == quote => return i + 1,
            _ => i += 1,
        }
    }
    chars.len()
}

/// Index of the `]` matching the `[` at `open`, skipping quoted strings and
/// escapes. Returns `chars.len()` when unmatched.
fn matching_bracket(chars: &[char], open: usize) -> usize {
    let mut i = open + 1;
    while i < chars.len() {
        match chars[i] {
            '\\' => i += 2,
            '"' | '\'' => i = skip_string(chars, i),
            ']' => return i,
            _ => i += 1,
        }
    }
    chars.len()
}

/// Validate the inner content of an `[…]` attribute selector. dart-sass allows
/// at most a single trailing ASCII-letter modifier, directly before the close
/// bracket: `[a]`, `[a=b]`, `[a=b ]`, `[a="b"i]`, and `[a=b i]` are valid, but
/// `[a b]` (no operator), `[a=b cd]` (too long), `[a=b 1]`/`[a=b _]`/`[a=b ï]`
/// (non-letter), and `[a=b i ]` (trailing space after the modifier) are not.
fn validate_attribute(inner: &[char]) -> Result<(), Error> {
    let err = || Error::unpositioned("expected \"]\".");
    let mut i = 0;
    let skip_ws = |i: &mut usize| {
        while *i < inner.len() && inner[*i].is_whitespace() {
            *i += 1;
        }
    };
    // Namespace + attribute name (identifiers, escapes, and a `|` namespace
    // separator); interpolation has already been resolved to literal text.
    skip_ws(&mut i);
    while i < inner.len() {
        let c = inner[i];
        if c == '\\' {
            i += 2;
        } else if is_name_char(c) || c == '|' || c == '*' {
            i += 1;
        } else {
            break;
        }
    }
    skip_ws(&mut i);
    if i >= inner.len() {
        return Ok(()); // bare `[name]`
    }
    // An operator must follow the name; anything else (e.g. a second
    // identifier in `[a b]`) is invalid.
    let op_ok = match inner[i] {
        '=' => true,
        '~' | '|' | '^' | '$' | '*' => inner.get(i + 1) == Some(&'='),
        _ => false,
    };
    if !op_ok {
        return Err(err());
    }
    i += if inner[i] == '=' { 1 } else { 2 };
    skip_ws(&mut i);
    // The value: a quoted string or an unquoted identifier (with escapes).
    match inner.get(i) {
        Some('"') | Some('\'') => i = skip_string(inner, i),
        Some(_) => {
            while i < inner.len() {
                let c = inner[i];
                if c == '\\' {
                    i += 2;
                } else if c.is_whitespace() {
                    break;
                } else {
                    i += 1;
                }
            }
        }
        None => return Err(err()),
    }
    skip_ws(&mut i);
    if i >= inner.len() {
        return Ok(()); // value, no modifier
    }
    // A modifier: exactly one ASCII letter, immediately before the close.
    if inner[i].is_ascii_alphabetic() && i + 1 == inner.len() {
        return Ok(());
    }
    Err(err())
}

fn is_name_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || c == '-' || c == '_' || !c.is_ascii()
}

fn is_name_start(c: char) -> bool {
    c.is_ascii_alphabetic() || c == '_' || !c.is_ascii()
}

/// Whether `s` is a plain CSS identifier that needs no escaping — so a quoted
/// attribute value `"<s>"` can be emitted unquoted as `<s>` by simply dropping
/// the quotes. Matches dart-sass's `_isIdentifier` for the escape-free case:
/// a leading `-` must be followed by a name-start char (`--x`, `-1`, `-` alone
/// are not identifiers), the first significant char is a name-start, and the
/// rest are name chars. Strings containing escapes or non-name characters are
/// conservatively treated as non-identifiers (kept quoted) so nothing
/// regresses.
fn is_plain_css_identifier(s: &str) -> bool {
    let chars: Vec<char> = s.chars().collect();
    if chars.is_empty() {
        return false;
    }
    let mut i = 0;
    if chars[0] == '-' {
        i = 1;
    }
    match chars.get(i) {
        Some(&c) if is_name_start(c) => i += 1,
        _ => return false,
    }
    chars[i..].iter().all(|&c| is_name_char(c))
}

/// Canonicalize the interior of an `[…]` attribute selector for emit, matching
/// dart-sass's `[name op value modifier]` form: whitespace around the operator
/// and at the edges is removed, and a trailing single-letter modifier is
/// preceded by exactly one space. The value text is preserved verbatim (no
/// unquoting). On any parse uncertainty the original (trimmed) text is kept so
/// no currently-passing selector regresses.
fn normalize_attribute_text(inner: &str) -> String {
    let chars: Vec<char> = inner.chars().collect();
    let fallback = || inner.trim().to_string();
    let mut i = 0;
    let skip_ws = |i: &mut usize| {
        while *i < chars.len() && chars[*i].is_whitespace() {
            *i += 1;
        }
    };
    skip_ws(&mut i);
    // Namespace + name.
    let name_start = i;
    while i < chars.len() {
        let c = chars[i];
        if c == '\\' {
            i += 2;
        } else if is_name_char(c) || c == '|' || c == '*' {
            i += 1;
        } else {
            break;
        }
    }
    if i == name_start {
        return fallback();
    }
    let name: String = chars[name_start..i.min(chars.len())].iter().collect();
    skip_ws(&mut i);
    if i >= chars.len() {
        return name; // `[name]`
    }
    // Operator.
    let op: String = match chars[i] {
        '=' => {
            i += 1;
            "=".to_string()
        }
        c @ ('~' | '|' | '^' | '$' | '*') if chars.get(i + 1) == Some(&'=') => {
            i += 2;
            format!("{c}=")
        }
        _ => return fallback(),
    };
    skip_ws(&mut i);
    // Value (quoted string or unquoted run), preserved verbatim.
    let value_start = i;
    match chars.get(i) {
        Some('"') | Some('\'') => i = skip_string(&chars, i),
        Some(_) => {
            while i < chars.len() {
                let c = chars[i];
                if c == '\\' {
                    i += 2;
                } else if c.is_whitespace() {
                    break;
                } else {
                    i += 1;
                }
            }
        }
        None => return fallback(),
    }
    let raw_value: String = chars[value_start..i.min(chars.len())].iter().collect();
    // dart-sass emits a quoted value unquoted when its content is a plain CSS
    // identifier (`[a="b"]` -> `[a=b]`). Only the escape-free, plain case is
    // unquoted here; anything needing re-escaping is kept verbatim.
    let value = unquote_plain_attribute_value(&raw_value);
    skip_ws(&mut i);
    if i >= chars.len() {
        return format!("{name}{op}{value}");
    }
    // A single-letter modifier (case-insensitive) before the close.
    if chars[i].is_ascii_alphabetic() && i + 1 == chars.len() {
        return format!("{name}{op}{value} {}", chars[i]);
    }
    fallback()
}

/// Drop the quotes from an attribute value when its content is a plain CSS
/// identifier; otherwise return it unchanged.
fn unquote_plain_attribute_value(raw: &str) -> String {
    let bytes: Vec<char> = raw.chars().collect();
    if bytes.len() >= 2 {
        let q = bytes[0];
        if (q == '"' || q == '\'') && bytes[bytes.len() - 1] == q {
            let content: String = bytes[1..bytes.len() - 1].iter().collect();
            if is_plain_css_identifier(&content) {
                return content;
            }
        }
    }
    raw.to_string()
}

/// Whether any TOP-LEVEL style rule (not nested inside an at-rule such as
/// `@media`) contains the extend `target` simple selector. Used to detect an
/// `@extend` that crosses a media-query boundary.
fn root_rule_contains_target(nodes: &[OutNode], target: &crate::selector::Simple) -> bool {
    nodes.iter().any(|node| match node {
        OutNode::Rule { selectors, .. } => selectors.iter().any(|s| {
            crate::selector::parse_list(s)
                .map(|cs| crate::selector::list_contains_simple(&cs, target))
                .unwrap_or(false)
        }),
        _ => false,
    })
}

/// Walk the flattened output tree, rewriting each style-rule selector list per
/// the collected extensions and dropping rules whose every complex selector
/// still contains a placeholder. Recurses into at-rule bodies (e.g. `@media`),
/// but NOT into `@keyframes` (whose "selectors" are keyframe stops like `50%`).
/// Scoped extend pass: rewrite `nodes` belonging to module `scope` with the
/// extensions visible there (the module's own plus those of every module that
/// (transitively) loads it — dart-sass per-module ExtensionStores), recursing
/// into [`OutNode::ModuleScope`] wrappers with their own scope.
fn rewrite_nodes_scoped(
    nodes: &mut Vec<OutNode>,
    scope: &str,
    all: &[crate::selector::Extension],
    origins: &[String],
    closures: &HashMap<String, std::collections::HashSet<String>>,
) {
    // The extensions whose origin can reach `scope` along load edges. A
    // private placeholder target (`%-name`/`%_name`) is module-private:
    // only extensions written in the same module may match it.
    let visible: Vec<crate::selector::Extension> = all
        .iter()
        .zip(origins.iter())
        .filter(|(e, o)| {
            let reachable =
                o.as_str() == scope || closures.get(o.as_str()).is_some_and(|c| c.contains(scope));
            let private_ok = match &e.target {
                Some(crate::selector::Simple::Placeholder(n)) if n.starts_with('-') || n.starts_with('_') => {
                    o.as_str() == scope
                }
                _ => true,
            };
            reachable && private_ok
        })
        .map(|(e, _)| e.clone())
        .collect();
    rewrite_with_scopes(nodes, &visible, scope, all, origins, closures);
}

/// The walk shared by [`rewrite_nodes_scoped`]: rules use the current scope's
/// `visible` extensions; a nested [`OutNode::ModuleScope`] re-enters with its
/// own scope.
fn rewrite_with_scopes(
    nodes: &mut Vec<OutNode>,
    visible: &[crate::selector::Extension],
    scope: &str,
    all: &[crate::selector::Extension],
    origins: &[String],
    closures: &HashMap<String, std::collections::HashSet<String>>,
) {
    for node in nodes.iter_mut() {
        match node {
            OutNode::ModuleScope { key, nodes } => {
                let key = key.clone();
                rewrite_nodes_scoped(nodes, &key, all, origins, closures);
            }
            OutNode::AtRule { name, body, .. } if !is_keyframes_name(name) => {
                rewrite_with_scopes(body, visible, scope, all, origins, closures);
            }
            _ => {}
        }
    }
    rewrite_nodes(nodes, visible, scope);
}

fn rewrite_nodes(nodes: &mut Vec<OutNode>, extensions: &[crate::selector::Extension], scope: &str) {
    let mut i = 0;
    while i < nodes.len() {
        let drop = match &mut nodes[i] {
            // Already rewritten (with its own scope) by rewrite_with_scopes;
            // drop the wrapper when nothing visible remains inside (so its
            // group separator doesn't leave a stray blank line).
            OutNode::ModuleScope { nodes, .. } => nodes.iter().all(|n| matches!(n, OutNode::Blank)),
            OutNode::Rule {
                selectors,
                linebreaks,
                extend_base,
                ..
            } => {
                let new_sel = extend_selector_list(selectors, linebreaks, extensions, scope, *extend_base);
                match new_sel {
                    Some((s, b)) => {
                        // Line-break flags travel with their selectors (dart's
                        // ComplexSelector.lineBreak): an original keeps its
                        // flag, an extend product takes its extender's.
                        *linebreaks = b;
                        *selectors = s;
                        false
                    }
                    // None means the rule is entirely placeholders → drop.
                    None => true,
                }
            }
            OutNode::AtRule {
                name,
                body,
                has_block,
                ..
            } => {
                // Body rules were already rewritten by rewrite_with_scopes
                // (which knows the per-module scopes); only the empty-group
                // drop remains here. A conditional group rule
                // (`@media`/`@supports`) whose body is emptied by placeholder
                // removal produces no CSS, so drop it.
                *has_block && body.is_empty() && (name == "media" || name == "supports")
            }
            _ => false,
        };
        if drop {
            nodes.remove(i);
            // Removing a rule can leave a dangling Blank separator; drop a
            // leading Blank so adjacent groups don't collapse to a blank line.
            if i < nodes.len() && matches!(nodes[i], OutNode::Blank) {
                nodes.remove(i);
            } else if i > 0 && matches!(nodes[i - 1], OutNode::Blank) {
                nodes.remove(i - 1);
                continue;
            }
        } else {
            i += 1;
        }
    }
}

/// True for `@keyframes` and its vendor-prefixed spellings, whose block
/// selectors are keyframe stops, not real selectors.
fn is_keyframes_name(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    lower == "keyframes" || lower.ends_with("-keyframes")
}

/// Derive the default namespace for `@use "<url>"`: the final path component,
/// with any leading `_` removed and everything from the first `.` (i.e. all
/// extensions) discarded. dart-sass rejects a result that is not a valid Sass
/// identifier.
fn default_namespace(url: &str, pos: Pos) -> Result<String, Error> {
    let last = url.rsplit('/').next().unwrap_or(url);
    let last = last.strip_prefix('_').unwrap_or(last);
    // Strip every extension: the namespace is the basename up to its first dot.
    let stem = match last.split_once('.') {
        Some((before, _)) => before,
        None => last,
    };
    if !is_valid_namespace(stem) {
        return Err(Error::at(
            format!("The default namespace \"{stem}\" is not a valid Sass identifier."),
            pos,
        ));
    }
    Ok(stem.to_string())
}

/// Build a predicate deciding whether an upstream `$variable` (by bare name) is
/// re-exported through a `@forward`'s `show`/`hide` clause.
fn forward_var_visibility(
    show: &Option<Vec<crate::ast::ForwardMember>>,
    hide: &Option<Vec<crate::ast::ForwardMember>>,
) -> impl Fn(&str) -> bool {
    let show = member_set(show, true);
    let hide = member_set(hide, true);
    move |name: &str| -> bool {
        let n = normalize_var_name(name);
        if let Some(s) = &show {
            return s.contains(&n);
        }
        if let Some(h) = &hide {
            return !h.contains(&n);
        }
        true
    }
}

/// Canonicalize a Sass variable name: `-` and `_` are interchangeable, so the
/// canonical form replaces every `_` with `-` (dart-sass dash-insensitivity).
fn normalize_var_name(name: &str) -> String {
    name.replace('_', "-")
}

/// Whether a member name is private (dart-sass: a leading `-` or `_`), so it is
/// not accessible across module boundaries.
fn is_private_member(name: &str) -> bool {
    name.starts_with('-') || name.starts_with('_')
}

/// Whether `module` exposes `name` as a built-in mixin. dart-sass's `sass:meta`
/// module defines the `load-css` and `apply` mixins; no other built-in module
/// exposes a mixin. Matched dash/underscore-insensitively.
fn is_builtin_mixin(module: &str, name: &str) -> bool {
    if module != "meta" {
        return false;
    }
    matches!(normalize_arg_name(name).as_str(), "load-css" | "apply")
}

/// Collect the names from a `@forward` `show`/`hide` member list, selecting
/// either the `$variable` entries (`vars == true`) or the function/mixin names.
/// Names are stored in canonical (dashed) form for dash-insensitive matching.
fn member_set(
    members: &Option<Vec<crate::ast::ForwardMember>>,
    vars: bool,
) -> Option<std::collections::HashSet<String>> {
    members.as_ref().map(|list| {
        list.iter()
            .filter_map(|m| match (m, vars) {
                (crate::ast::ForwardMember::Var(n), true) => Some(normalize_var_name(n)),
                (crate::ast::ForwardMember::Name(n), false) => Some(normalize_var_name(n)),
                _ => None,
            })
            .collect()
    })
}

/// Whether `s` is a valid Sass identifier usable as a module namespace.
fn is_valid_namespace(s: &str) -> bool {
    let mut chars = s.chars();
    match chars.next() {
        Some(c) if c == '_' || c == '-' || c.is_ascii_alphabetic() || !c.is_ascii() => {}
        _ => return false,
    }
    chars.all(|c| c == '_' || c == '-' || c.is_ascii_alphanumeric() || !c.is_ascii())
}

/// Compute the extended selector list for a rule. Returns `None` when, after
/// extension, every complex selector still contains a placeholder (the rule
/// emits no CSS). Returns `Some(unchanged)` when the selector needs no change.
fn extend_selector_list(
    selectors: &[String],
    breaks: &[bool],
    extensions: &[crate::selector::Extension],
    scope: &str,
    extend_base: usize,
) -> Option<(Vec<String>, Vec<bool>)> {
    let has_placeholder = selectors.iter().any(|s| s.contains('%'));
    // Fast path: no extensions and no placeholder → the selector is untouched.
    // Crucially this leaves selectors we don't model (keyframe stops are handled
    // separately, but also unusual selectors) byte-for-byte intact.
    if extensions.is_empty() && !has_placeholder {
        return Some((selectors.to_vec(), breaks.to_vec()));
    }
    let joined = selectors.join(", ");
    let Some(parsed) = crate::selector::parse_list(&joined) else {
        // Unparseable selector: never lose it; leave untouched.
        return Some((selectors.to_vec(), breaks.to_vec()));
    };
    let result = crate::selector::extend_selectors(&parsed, breaks, extensions, scope, extend_base);
    if result.all_placeholders {
        return None;
    }
    Some((result.selectors, result.breaks))
}

/// For each non-empty top-level comma part of a selector list, whether the
/// emitted complex selector should begin on its own line — parallel to the
/// parts `resolve_selectors` keeps.
///
/// dart-sass carries a per-complex `lineBreak` flag set when a newline precedes
/// the part in source (`a,\nb`). During parent resolution that flag survives for
/// an *implicit*-parent part (`parent.lineBreak || child.lineBreak`), but a part
/// that *references* the parent with `&` takes the parent complex's flag instead
/// and drops its own. We don't track parent line-breaks, so for a `&`-part in a
/// nested rule we conservatively report `false` (correct whenever the governing
/// parent is the first/unbroken one, and never emits a break dart-sass wouldn't).
fn comma_linebreaks(sel: &str, nested: bool) -> Vec<bool> {
    // An EMPTY comma part (a stray trailing/doubled comma) is dropped, but a
    // newline inside it still belongs to the next real part:
    // `#foo #bar,,\n,#baz #boom,` keeps `#baz #boom` on its own line.
    let mut out = Vec::new();
    let mut pending_nl = false;
    let segs = split_commas(sel);
    for (i, seg) in segs.iter().enumerate() {
        if seg.trim().is_empty() {
            pending_nl = pending_nl || (i > 0 && seg.contains('\n'));
            continue;
        }
        // dart marks a complex as line-broken when ANY newline sits between
        // it and the previous one — including BEFORE the comma (`a\n, b`).
        let leading_nl = seg.chars().take_while(|c| c.is_whitespace()).any(|c| c == '\n');
        let prev_trailing_nl = i > 0
            && segs[i - 1]
                .chars()
                .rev()
                .take_while(|c| c.is_whitespace())
                .any(|c| c == '\n');
        let newline_before = i > 0 && (leading_nl || prev_trailing_nl);
        out.push((newline_before || pending_nl) && !(nested && part_has_parent_ref(seg)));
        pending_nl = false;
    }
    out
}

/// Whether a selector comma-part contains a top-level parent reference `&`
/// (not inside `[…]` or a quoted string). Interpolation has already been
/// resolved into `sel` by the time this runs, so a `&` here is a real parent
/// reference.
fn part_has_parent_ref(part: &str) -> bool {
    let mut bracket = 0i32;
    let mut quote: Option<char> = None;
    let mut chars = part.chars();
    while let Some(c) = chars.next() {
        match quote {
            Some(q) => {
                if c == '\\' {
                    chars.next();
                } else if c == q {
                    quote = None;
                }
            }
            None => match c {
                '"' | '\'' => quote = Some(c),
                '[' => bracket += 1,
                ']' => bracket = (bracket - 1).max(0),
                '&' if bracket == 0 => return true,
                _ => {}
            },
        }
    }
    false
}

/// The char index of the first `@` outside quoted strings in a resolved
/// selector, if any — `@` has no legal position in a CSS selector.
fn find_unquoted_at(sel: &str) -> Option<usize> {
    // `@` is ASCII: no `@` byte means no occurrence at all — skip the
    // quote-tracking walk that otherwise runs for every resolved selector.
    if !sel.as_bytes().contains(&b'@') {
        return None;
    }
    let mut quote: Option<char> = None;
    let mut iter = sel.chars().enumerate();
    while let Some((i, c)) = iter.next() {
        match quote {
            Some(q) => {
                if c == '\\' {
                    iter.next();
                } else if c == q {
                    quote = None;
                }
            }
            None => match c {
                '"' | '\'' => quote = Some(c),
                '\\' => {
                    iter.next();
                }
                '@' => return Some(i),
                _ => {}
            },
        }
    }
    None
}

/// Replace top-level `&` parent references with `parent`. A `&` inside `[…]`
/// or a quoted string is literal text (issue_2291 `[str="&"]` keeps its
/// ampersand); one inside pseudo parentheses is still a real reference.
fn replace_parent_refs(part: &str, parent: &str) -> String {
    let mut out = String::with_capacity(part.len() + parent.len());
    let mut bracket = 0i32;
    let mut quote: Option<char> = None;
    let mut chars = part.chars();
    while let Some(c) = chars.next() {
        match quote {
            Some(q) => {
                out.push(c);
                if c == '\\' {
                    if let Some(n) = chars.next() {
                        out.push(n);
                    }
                } else if c == q {
                    quote = None;
                }
            }
            None => match c {
                '"' | '\'' => {
                    quote = Some(c);
                    out.push(c);
                }
                '[' => {
                    bracket += 1;
                    out.push(c);
                }
                ']' => {
                    bracket = (bracket - 1).max(0);
                    out.push(c);
                }
                '&' if bracket == 0 => out.push_str(parent),
                _ => out.push(c),
            },
        }
    }
    out
}

/// Resolve a selector against its parents with dart's `implicitParent` switch: inside
/// `@at-root` (before the first nested style rule) a part WITHOUT `&` stays
/// at the root instead of joining the parent, while `&` still substitutes.
fn resolve_selectors_opt(sel: &str, parents: &[String], implicit_parent: bool) -> Result<Vec<String>, Error> {
    let parts: Vec<String> = split_commas(sel)
        .into_iter()
        .map(|p| trim_selector_part(p).to_string())
        .filter(|p| !p.is_empty())
        .collect();
    // dart: a parent that ends in a combinator can't substitute into a `&`
    // that is part of a compound (`.a > { &.b {} }` errors; `& .b` is fine).
    let check_compound_parent = |part: &str, parent: &str| -> Result<(), Error> {
        let trimmed = parent.trim_end();
        if !matches!(trimmed.chars().last(), Some('>' | '+' | '~')) {
            return Ok(());
        }
        let chars: Vec<char> = part.chars().collect();
        for (i, &c) in chars.iter().enumerate() {
            if c == '&' {
                if let Some(&next) = chars.get(i + 1) {
                    if next.is_alphanumeric()
                        || matches!(next, '.' | '#' | ':' | '[' | '%' | '\\' | '-' | '_')
                    {
                        return Err(Error::unpositioned(format!(
                            "Selector \"{trimmed}\" can't be used as a parent in a compound selector."
                        )));
                    }
                }
            }
        }
        Ok(())
    };
    // A `&` that sits only inside pseudo arguments takes the WHOLE parent
    // list in place (dart: `:not(&-c)` under `.a, .b` is `:not(.a-c, .b-c)`,
    // ONE complex — no cartesian expansion). A part with any top-level `&`
    // (or a pseudo-`&` glued to a non-suffix simple) uses the normal path.
    let substitute_pseudo_refs = |part: &str| -> Option<String> {
        if !part.contains('&') {
            return None;
        }
        let chars: Vec<char> = part.chars().collect();
        let mut depth = 0i32;
        let mut out = String::new();
        let mut i = 0;
        let mut replaced = false;
        while i < chars.len() {
            let c = chars[i];
            match c {
                '(' => depth += 1,
                ')' => depth -= 1,
                '&' => {
                    if depth == 0 {
                        return None;
                    }
                    // Collect an identifier suffix (`&-c`); any other glued
                    // simple (`&.x`, `&:h`) bails to the normal path.
                    let mut suffix = String::new();
                    let mut j = i + 1;
                    while j < chars.len() && (chars[j].is_alphanumeric() || matches!(chars[j], '-' | '_')) {
                        suffix.push(chars[j]);
                        j += 1;
                    }
                    if matches!(chars.get(j), Some('.' | '#' | ':' | '[' | '%' | '\\' | '&')) {
                        return None;
                    }
                    let expansion = parents
                        .iter()
                        .map(|p| format!("{p}{suffix}"))
                        .collect::<Vec<_>>()
                        .join(", ");
                    out.push_str(&expansion);
                    replaced = true;
                    i = j;
                    continue;
                }
                _ => {}
            }
            out.push(c);
            i += 1;
        }
        if replaced {
            Some(out)
        } else {
            None
        }
    };
    // Count a part's TOP-LEVEL `&` references (outside parens/brackets) and
    // split it into the segments between them. With k >= 2 refs the part
    // expands to the parents' k-fold cartesian product (`& &` under
    // `ul, ol` is `ul ul, ul ol, ol ul, ol ol`, issue_1710).
    let split_parent_refs = |part: &str| -> Option<Vec<String>> {
        let mut segments = vec![String::new()];
        let mut depth = 0i32;
        let mut quote: Option<char> = None;
        for c in part.chars() {
            if let Some(q) = quote {
                segments.last_mut().unwrap().push(c);
                if c == q {
                    quote = None;
                }
                continue;
            }
            match c {
                '"' | '\'' => quote = Some(c),
                '(' | '[' => depth += 1,
                ')' | ']' => depth -= 1,
                '&' if depth == 0 => {
                    segments.push(String::new());
                    continue;
                }
                _ => {}
            }
            segments.last_mut().unwrap().push(c);
        }
        if segments.len() >= 3 {
            Some(segments)
        } else {
            None
        }
    };
    let expand_cartesian = |segments: &[String], result: &mut Vec<String>| {
        let k = segments.len() - 1;
        let n = parents.len();
        let mut idx = vec![0usize; k];
        loop {
            let mut s = String::new();
            for (i, seg) in segments[..k].iter().enumerate() {
                s.push_str(seg);
                s.push_str(&parents[idx[i]]);
            }
            s.push_str(&segments[k]);
            result.push(normalize_selector(&s));
            // Increment with the LAST ref fastest (dart's order).
            let mut j = k;
            loop {
                if j == 0 {
                    return;
                }
                j -= 1;
                idx[j] += 1;
                if idx[j] < n {
                    break;
                }
                idx[j] = 0;
            }
        }
    };
    let mut result = Vec::new();
    if parents.is_empty() {
        // At the document root (no enclosing style rule) a parent selector `&`
        // has no parent to substitute, so dart-sass keeps it literal: `& {a: b}`
        // emits `& {\u{2026}}` and `&.foo {\u{2026}}` emits `&.foo {\u{2026}}`. (A `&`-with-suffix
        // such as `&foo` is rejected earlier by `validate_selector`.)
        for part in &parts {
            result.push(normalize_selector(part));
        }
    } else if !implicit_parent {
        // dart resolves per complex: a part with `&` expands across the
        // parents; a part without stays at the root exactly once.
        for part in &parts {
            if let Some(s) = substitute_pseudo_refs(part) {
                result.push(normalize_selector(&s));
            } else if let Some(segments) = split_parent_refs(part) {
                for parent in parents {
                    check_compound_parent(part, parent)?;
                }
                expand_cartesian(&segments, &mut result);
            } else if part_has_parent_ref(part) {
                for parent in parents {
                    check_compound_parent(part, parent)?;
                    result.push(normalize_selector(&replace_parent_refs(part, parent)));
                }
            } else {
                result.push(normalize_selector(part));
            }
        }
    } else {
        for (pi, parent) in parents.iter().enumerate() {
            for part in &parts {
                // A pseudo-only `&` part resolves ONCE (whole parent list in
                // place), emitted at its position in the first parent round.
                if let Some(s) = substitute_pseudo_refs(part) {
                    if pi == 0 {
                        result.push(normalize_selector(&s));
                    }
                    continue;
                }
                // A part with k >= 2 top-level refs expands its full
                // cartesian product once, in the first parent round.
                if let Some(segments) = split_parent_refs(part) {
                    if pi == 0 {
                        for parent in parents {
                            check_compound_parent(part, parent)?;
                        }
                        expand_cartesian(&segments, &mut result);
                    }
                    continue;
                }
                let combined = if part_has_parent_ref(part) {
                    check_compound_parent(part, parent)?;
                    replace_parent_refs(part, parent)
                } else {
                    format!("{parent} {part}")
                };
                result.push(normalize_selector(&combined));
            }
        }
    }
    Ok(result)
}

/// Split `s` on top-level commas (paren/bracket depth 0), returning borrowed
/// slices of `s` — no per-part allocation. Commas inside `(...)`/`[...]` stay
/// within their part. Each part is a contiguous substring of `s`, so callers
/// that need an owned `String` call `.to_string()` themselves.
fn split_commas(s: &str) -> Vec<&str> {
    // No comma anywhere means one segment, whatever the nesting structure.
    if !s.as_bytes().contains(&b',') {
        return vec![s];
    }
    let mut out = Vec::new();
    let mut paren = 0i32;
    let mut bracket = 0i32;
    let mut start = 0usize;
    for (idx, c) in s.char_indices() {
        match c {
            '(' => paren += 1,
            ')' => paren -= 1,
            '[' => bracket += 1,
            ']' => bracket -= 1,
            ',' if paren == 0 && bracket == 0 => {
                out.push(&s[start..idx]);
                start = idx + 1; // ',' is ASCII (1 byte)
            }
            _ => {}
        }
    }
    out.push(&s[start..]);
    out
}

/// Collapse whitespace and put single spaces around `>`/`+`/`~`
/// combinators (at bracket depth 0), matching dart-sass's selector
/// serialization. Also separates adjacent compounds: a bare type/element
/// selector appearing mid-compound (`[a]b`, `:not(.x)b`) is joined to the
/// preceding simple with a descendant combinator (`[a] b`), matching
/// dart-sass's `[adjacent-compounds]` normalization.
pub(crate) fn normalize_selector(s: &str) -> String {
    // Fast path: already-canonical selectors skip the two char-vector
    // materializations below. Equivalence was proven by a check build that
    // asserted fast == slow on every call across the full sass-spec suite.
    if is_canonical_plain(s) {
        return s.to_string();
    }
    normalize_selector_slow(s)
}

/// Whether `s` is already in canonical form without running the normalizer:
/// only plain compound characters (ASCII letters/digits, `_-.#%`) separated
/// by single descendant spaces, with no leading/trailing space. Every rewrite
/// `normalize_selector` performs — whitespace collapse, hex-escape handling,
/// attribute/pseudo/combinator canonicalization — is triggered by a character
/// outside this set.
fn is_canonical_plain(s: &str) -> bool {
    let b = s.as_bytes();
    if b.is_empty() || b[0] == b' ' || b[b.len() - 1] == b' ' {
        return false;
    }
    let mut prev_space = false;
    for &c in b {
        match c {
            b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' | b'-' | b'.' | b'#' | b'%' => {
                prev_space = false;
            }
            b' ' => {
                if prev_space {
                    return false;
                }
                prev_space = true;
            }
            _ => return false,
        }
    }
    true
}

fn normalize_selector_slow(s: &str) -> String {
    // Collapse runs of whitespace to single spaces (and trim) — but a hex
    // escape's single terminating whitespace is PART of the token
    // (`selector\9 ` keeps its trailing space; dart emits `selector\9  {`).
    let cs: Vec<char> = s.chars().collect();
    let mut collapsed = String::with_capacity(s.len());
    let mut prev_space = true; // trims leading whitespace
    let mut ci = 0;
    while ci < cs.len() {
        let c = cs[ci];
        if c == '\\' && ci + 1 < cs.len() && cs[ci + 1].is_ascii_hexdigit() {
            collapsed.push('\\');
            ci += 1;
            let mut digits = 0;
            while digits < 6 && ci < cs.len() && cs[ci].is_ascii_hexdigit() {
                collapsed.push(cs[ci]);
                ci += 1;
                digits += 1;
            }
            if ci < cs.len() && cs[ci].is_whitespace() {
                collapsed.push(' ');
                ci += 1;
            }
            prev_space = false;
            continue;
        }
        // A literal escape: the next character — even whitespace (`sp\ `) —
        // is part of the token, never a separator to collapse or trim.
        if c == '\\' && ci + 1 < cs.len() {
            collapsed.push('\\');
            collapsed.push(cs[ci + 1]);
            ci += 2;
            prev_space = false;
            continue;
        }
        if c.is_whitespace() {
            if !prev_space {
                collapsed.push(' ');
            }
            prev_space = true;
            ci += 1;
            continue;
        }
        collapsed.push(c);
        prev_space = false;
        ci += 1;
    }
    // Trim a PLAIN trailing space (one belonging to an escape stays).
    if prev_space && collapsed.ends_with(' ') {
        collapsed.pop();
    }
    let chars: Vec<char> = collapsed.chars().collect();
    let mut out = String::new();
    let mut i = 0;
    // True when the current top-level compound already holds a simple selector.
    let mut mid_compound = false;
    while i < chars.len() {
        let c = chars[i];
        match c {
            '[' => {
                let end = matching_bracket(&chars, i);
                if end < chars.len() {
                    let whole: String = chars[i..=end].iter().collect();
                    out.push_str(&crate::selector::normalize_attribute(&whole));
                } else {
                    let inner: String = chars[i + 1..].iter().collect();
                    out.push('[');
                    out.push_str(&normalize_attribute_text(&inner));
                }
                i = end + 1;
                mid_compound = true;
                continue;
            }
            '.' | '#' | '%' => {
                // A class/id/placeholder sigil plus its name (one simple).
                out.push(c);
                i += 1;
                copy_name(&chars, &mut i, &mut out);
                mid_compound = true;
                continue;
            }
            ':' => {
                // A pseudo-class/element (with any `(...)` argument). A
                // selector-argument pseudo re-serializes canonically.
                let start = out.len();
                copy_pseudo(&chars, &mut i, &mut out);
                let text = out[start..].to_string();
                // An `:nth-child`/`:nth-last-child` An+B argument
                // canonicalizes (whitespace drops, lowercase `n`); a
                // selector-argument pseudo re-serializes canonically.
                let canon = crate::selector::normalize_nth(&text)
                    .or_else(|| crate::selector::normalize_pseudo_arg(&text));
                if let Some(canon) = canon {
                    out.truncate(start);
                    out.push_str(&canon);
                }
                mid_compound = true;
                continue;
            }
            '*' if chars.get(i + 1) != Some(&'|') || chars.get(i + 2) == Some(&'=') => {
                // A bare universal `*` (not a `*|...` namespace prefix). It does
                // not start a new adjacent compound on its own.
                out.push('*');
                i += 1;
                mid_compound = true;
                continue;
            }
            '>' | '~' | '+' => {
                while out.ends_with(' ') {
                    out.pop();
                }
                out.push(' ');
                out.push(c);
                out.push(' ');
                i += 1;
                while i < chars.len() && chars[i] == ' ' {
                    i += 1;
                }
                mid_compound = false;
                continue;
            }
            ' ' | '\t' | '\n' | '\r' => {
                out.push(c);
                i += 1;
                mid_compound = false;
                continue;
            }
            _ if type_selector_starts_at(&chars, i) => {
                // A type/namespaced-type selector. Mid-compound, it is a
                // separate adjacent compound: join with a descendant space.
                if mid_compound && !out.ends_with(' ') {
                    out.push(' ');
                }
                copy_type_selector(&chars, &mut i, &mut out);
                mid_compound = true;
                continue;
            }
            _ => {
                // Any other character (e.g. a digit or `%` in a keyframe stop
                // like `1e2%`, which is not a real selector). It does NOT make a
                // following identifier an adjacent compound, so clear the flag.
                out.push(c);
                i += 1;
                mid_compound = false;
            }
        }
    }
    let t = out.trim();
    // dart keeps an escape's trailing space: a hex escape's terminator
    // (`selector\9 `) and an escaped literal space (`sp\ `) both survive;
    // only plain trailing whitespace trims.
    let start = out.len() - out.trim_start().len();
    let end = start + t.len();
    if out[end..].starts_with(' ') && (ends_with_hex_escape(t) || ends_with_escaping_backslash(t)) {
        out[start..=end].to_string()
    } else {
        t.to_string()
    }
}

/// Whether `t` ends in a `\<hex>{1,6}` escape whose terminating space must
/// survive trimming.
fn ends_with_hex_escape(t: &str) -> bool {
    let b = t.as_bytes();
    let mut i = b.len();
    let mut digits = 0;
    while i > 0 && (b[i - 1] as char).is_ascii_hexdigit() && digits < 6 {
        i -= 1;
        digits += 1;
    }
    digits > 0 && i > 0 && b[i - 1] == b'\\'
}

/// Whether `t` ends in an ODD run of backslashes, so the character after it
/// (an escaped literal space, `sp\ `) is part of the identifier.
fn ends_with_escaping_backslash(t: &str) -> bool {
    let b = t.as_bytes();
    let mut n = 0;
    while n < b.len() && b[b.len() - 1 - n] == b'\\' {
        n += 1;
    }
    n % 2 == 1
}

/// Trim a selector part's surrounding whitespace, keeping the one character
/// that belongs to a trailing escape — a hex escape's terminator (`\9 `) or
/// an escaped literal space (`sp\ `).
fn trim_selector_part(p: &str) -> &str {
    let t0 = p.trim_start();
    let t = t0.trim_end();
    if t.len() < t0.len() && (ends_with_hex_escape(t) || ends_with_escaping_backslash(t)) {
        &t0[..t.len() + 1]
    } else {
        t
    }
}

/// One token of a complex selector split at the top level (paren/bracket depth
/// 0): either a combinator or a compound selector (a borrowed slice of the
/// input, trimmed).
enum SelToken<'a> {
    Combinator,
    Compound(&'a str),
}

/// Tokenize a complex selector into combinators and compounds at the top level,
/// honouring `[...]`, `(...)`, strings, and escapes so combinators inside a
/// pseudo argument or attribute aren't split out here. Compounds borrow `s`
/// (no per-token allocation): each is a contiguous, trimmed substring.
fn tokenize_complex(s: &str) -> Vec<SelToken<'_>> {
    let mut tokens = Vec::new();
    let mut paren = 0i32;
    let mut bracket = 0i32;
    let mut start = 0usize; // byte start of the compound being accumulated
    let mut it = s.char_indices();
    while let Some((idx, c)) = it.next() {
        match c {
            '\\' => {
                // An escape consumes the following character verbatim.
                it.next();
            }
            '"' | '\'' => {
                // Skip a quoted string (honouring `\` escapes) so combinators
                // inside it aren't split out. Mirrors `skip_string`.
                while let Some((_, c2)) = it.next() {
                    match c2 {
                        '\\' => {
                            it.next();
                        }
                        q if q == c => break,
                        _ => {}
                    }
                }
            }
            '(' => paren += 1,
            ')' => paren -= 1,
            '[' => bracket += 1,
            ']' => bracket -= 1,
            '>' | '+' | '~' if paren == 0 && bracket == 0 => {
                let t = trim_selector_part(&s[start..idx]);
                if !t.is_empty() {
                    tokens.push(SelToken::Compound(t));
                }
                tokens.push(SelToken::Combinator);
                start = idx + 1; // combinator char is ASCII (1 byte)
            }
            _ => {}
        }
    }
    let t = trim_selector_part(&s[start..]);
    if !t.is_empty() {
        tokens.push(SelToken::Compound(t));
    }
    tokens
}

/// Whether a resolved complex selector is a "bogus combinator" that dart-sass
/// omits from the generated CSS: two combinators in a row anywhere, or — inside
/// a pseudo argument (`in_pseudo`) — a trailing combinator, or a leading
/// combinator unless `allow_leading` (true only for `:has`, a relative selector
/// list). A single leading/trailing combinator at the top level is NOT bogus
/// here (it is kept, or handled separately by the nesting rules). The check
/// recurses into selector pseudo arguments (`:is()`, `:not()`, …).
fn complex_selector_is_bogus(s: &str, in_pseudo: bool, allow_leading: bool) -> bool {
    // Bogus-ness needs a combinator (`>`/`+`/`~`) or a selector-pseudo
    // argument (which needs a `(`); a selector containing none of those
    // bytes cannot be bogus, so skip the tokenization entirely.
    if !has_bogus_trigger(s) {
        return false;
    }
    let tokens = tokenize_complex(s);
    if tokens.is_empty() {
        return false;
    }
    // Two adjacent combinators (no compound between) is always invalid.
    let mut prev_combinator = false;
    for t in &tokens {
        match t {
            SelToken::Combinator => {
                if prev_combinator {
                    return true;
                }
                prev_combinator = true;
            }
            SelToken::Compound(_) => prev_combinator = false,
        }
    }
    if in_pseudo {
        if !allow_leading && matches!(tokens.first(), Some(SelToken::Combinator)) {
            return true;
        }
        if matches!(tokens.last(), Some(SelToken::Combinator)) {
            return true;
        }
    }
    // Recurse into selector pseudo arguments of each compound.
    for t in &tokens {
        if let SelToken::Compound(comp) = t {
            if compound_has_bogus_pseudo(comp) {
                return true;
            }
        }
    }
    false
}

/// Whether a resolved complex selector should be dropped from its own emitted
/// declaration block. This is [`complex_selector_is_bogus`] (double combinators,
/// pseudo leading/trailing combinators) PLUS a top-level trailing combinator
/// (`a >`): a trailing combinator is valid only for nesting, so the leaf block
/// it would head is omitted while the selector still serves as a parent.
fn complex_selector_block_is_bogus(s: &str) -> bool {
    if !has_bogus_trigger(s) {
        return false;
    }
    if complex_selector_is_bogus(s, false, false) {
        return true;
    }
    let tokens = tokenize_complex(s);
    matches!(tokens.last(), Some(SelToken::Combinator))
}

/// Whether `s` contains any byte that could make a complex selector bogus: a
/// combinator, or the `(` of a selector-pseudo argument to recurse into.
/// Escaped spellings (`\>`) still contain the trigger byte, so anything
/// suspicious takes the full tokenizing path.
fn has_bogus_trigger(s: &str) -> bool {
    s.bytes().any(|c| matches!(c, b'>' | b'+' | b'~' | b'('))
}

/// Whether `name` (a pseudo-class/element name, case-insensitive, without the
/// leading colon(s)) is one whose argument dart-sass parses as a selector list,
/// and so is subject to bogus-combinator checking. Mirrors dart-sass's
/// `_selectorPseudoClasses`/`_selectorPseudoElements`. Notably this EXCLUDES
/// `:global`/`:local` (CSS-modules pseudos kept verbatim).
fn is_selector_pseudo(name: &str) -> bool {
    matches!(
        name.to_ascii_lowercase().as_str(),
        "not" | "is" | "matches" | "where" | "current" | "any" | "has" | "host" | "host-context" | "slotted"
    )
}

/// Whether any selector-pseudo argument (`:is(...)`, `:has(...)`, `:not(...)`,
/// `:where(...)`, …) inside a compound contains a bogus-combinator complex
/// selector. Only pseudos in [`is_selector_pseudo`] are scanned (others, like
/// `:nth-child(2n)` or `:global(> a)`, keep their argument verbatim). `:has` is
/// a relative selector list, so a leading combinator there is allowed.
fn compound_has_bogus_pseudo(compound: &str) -> bool {
    let chars: Vec<char> = compound.chars().collect();
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        if c == '\\' {
            i += 2;
            continue;
        }
        if c == '[' {
            // Skip an attribute selector verbatim.
            i = matching_bracket(&chars, i) + 1;
            continue;
        }
        if c == ':' {
            // A pseudo with a `(...)` argument: extract and scan the argument as
            // a selector list (each comma part is one complex selector).
            let mut j = i + 1;
            if j < chars.len() && chars[j] == ':' {
                j += 1;
            }
            let name_start = j;
            while j < chars.len() && (is_name_char(chars[j]) || chars[j] == '\\') {
                if chars[j] == '\\' {
                    j += 1;
                }
                j += 1;
            }
            let name: String = chars[name_start..j.min(chars.len())].iter().collect();
            if j < chars.len() && chars[j] == '(' {
                let open = j;
                let mut depth = 0i32;
                let mut k = open;
                while k < chars.len() {
                    match chars[k] {
                        '\\' => {
                            k += 2;
                            continue;
                        }
                        '"' | '\'' => {
                            k = skip_string(&chars, k);
                            continue;
                        }
                        '(' => depth += 1,
                        ')' => {
                            depth -= 1;
                            if depth == 0 {
                                break;
                            }
                        }
                        _ => {}
                    }
                    k += 1;
                }
                if is_selector_pseudo(&name) {
                    let allow_leading = name.eq_ignore_ascii_case("has");
                    let arg: String = chars[open + 1..k.min(chars.len())].iter().collect();
                    for part in split_commas(&arg) {
                        let part = part.trim();
                        if !part.is_empty() && complex_selector_is_bogus(part, true, allow_leading) {
                            return true;
                        }
                    }
                }
                i = k + 1;
                continue;
            }
            i = j;
            continue;
        }
        i += 1;
    }
    false
}

/// Copy a CSS name (the part after a `.`/`#`/`%` sigil or a type name) starting
/// at `*i`, honouring `\` escapes, advancing `*i` past it. The captured name is
/// canonicalized to dart-sass's escape form (a numeric escape of a printable
/// character becomes the escaped character, an inline digit drops its escape,
/// etc.).
fn copy_name(chars: &[char], i: &mut usize, out: &mut String) {
    let start = *i;
    let mut has_escape = false;
    while *i < chars.len() {
        let c = chars[*i];
        if c == '\\' {
            has_escape = true;
            *i += 1;
            if *i < chars.len() {
                let esc = chars[*i];
                *i += 1;
                // A hex escape continues for up to six hex digits plus one
                // optional trailing whitespace; consume the rest of it so it
                // decodes as a single code point.
                if esc.is_ascii_hexdigit() {
                    let mut digits = 1;
                    while digits < 6 && *i < chars.len() && chars[*i].is_ascii_hexdigit() {
                        *i += 1;
                        digits += 1;
                    }
                    if *i < chars.len() && chars[*i].is_whitespace() {
                        *i += 1;
                    }
                }
            }
        } else if is_name_char(c) {
            *i += 1;
        } else {
            break;
        }
    }
    // Fast path: a plain name (no escapes) round-trips through
    // `canonicalize_ident` unchanged, so copy the slice straight out with no
    // intermediate String allocation.
    if has_escape {
        let raw: String = chars[start..*i].iter().collect();
        out.push_str(&crate::selector::canonicalize_ident(&raw));
    } else {
        out.extend(chars[start..*i].iter());
    }
}

/// Copy a pseudo-class/element selector (`:name` / `::name` plus any balanced
/// `(...)` argument) verbatim, advancing `*i` past it.
fn copy_pseudo(chars: &[char], i: &mut usize, out: &mut String) {
    out.push(chars[*i]); // first ':'
    *i += 1;
    let is_element = *i < chars.len() && chars[*i] == ':';
    if is_element {
        out.push(':');
        *i += 1;
    }
    let name_start = *i;
    copy_name(chars, i, out);
    let name: String = chars[name_start..*i].iter().collect();
    if *i < chars.len() && chars[*i] == '(' {
        out.push('(');
        *i += 1;
        // dart-sass trims the whitespace immediately inside a pseudo's argument
        // parens (interior runs are already collapsed to a single space by
        // `normalize_selector`). Leading whitespace is always dropped; trailing
        // whitespace is dropped for a pseudo-CLASS or a selector-argument
        // pseudo-element (`::slotted`), but KEPT for a text-argument
        // pseudo-element such as `::part(foo )` / `::highlight(h )`.
        let trim_trailing = !is_element || is_selector_pseudo_element(&name);
        while *i < chars.len() && chars[*i] == ' ' {
            *i += 1;
        }
        let mut depth = 1i32;
        while *i < chars.len() {
            let c = chars[*i];
            match c {
                '\\' => {
                    out.push(c);
                    *i += 1;
                    if *i < chars.len() {
                        out.push(chars[*i]);
                        *i += 1;
                    }
                    continue;
                }
                '(' => depth += 1,
                ')' => {
                    depth -= 1;
                    if depth == 0 {
                        if trim_trailing {
                            while out.ends_with(' ') {
                                out.pop();
                            }
                        }
                        out.push(')');
                        *i += 1;
                        break;
                    }
                }
                _ => {}
            }
            out.push(c);
            *i += 1;
        }
    }
}

/// Whether a `::name` pseudo-element takes a selector argument (so dart-sass
/// parses and re-serializes it, trimming the argument on both sides). Other
/// pseudo-elements (`::part`, `::highlight`) carry a raw text argument and keep
/// its trailing whitespace. Compared case-insensitively, ignoring a vendor
/// prefix, matching dart-sass's `_selectorPseudoElements`.
fn is_selector_pseudo_element(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    let unvendored = lower
        .strip_prefix('-')
        .map_or(lower.as_str(), |rest| match rest.find('-') {
            Some(idx) => &rest[idx + 1..],
            None => lower.as_str(),
        });
    matches!(unvendored, "slotted" | "cue" | "cue-region")
}

/// Copy a type/element selector, including an optional `ns|`/`*|`/`|` namespace
/// prefix and the type name (or `*`), advancing `*i` past it.
fn copy_type_selector(chars: &[char], i: &mut usize, out: &mut String) {
    // Optional namespace prefix.
    if chars[*i] == '*' {
        out.push('*');
        *i += 1;
    } else if chars[*i] == '|' {
        // bare `|type` — no namespace, handled by falling through.
    } else {
        copy_name(chars, i, out);
    }
    if *i < chars.len() && chars[*i] == '|' && chars.get(*i + 1) != Some(&'=') {
        out.push('|');
        *i += 1;
        if *i < chars.len() && chars[*i] == '*' {
            out.push('*');
            *i += 1;
        } else {
            copy_name(chars, i, out);
        }
    }
}

/// Whether a bare type/namespaced-type selector (an identifier, optionally
/// preceded by a `*|`/`ns|`/`|` namespace) begins at `chars[i]`. Used to detect
/// an adjacent compound (`[a]b` → `[a] b`). A `*` universal, the `.#%:` sigils,
/// an attribute `[`, and a combinator are NOT type-selector starts. `*|type`
/// and `|type` count as type starts.
fn type_selector_starts_at(chars: &[char], i: usize) -> bool {
    let c = chars[i];
    // `*|...` is a namespaced type/universal (but not `*|=`, an operator).
    if c == '*' {
        return chars.get(i + 1) == Some(&'|') && chars.get(i + 2) != Some(&'=');
    }
    // `|type` (empty namespace) is a type selector (but not `|=`).
    if c == '|' {
        return chars.get(i + 1) != Some(&'=');
    }
    if is_name_start(c) {
        return true;
    }
    // A leading `-` of an identifier (`-foo`, `--foo`) or an escape `\` begins
    // an identifier-led type selector.
    if c == '-' {
        return matches!(chars.get(i + 1), Some(&n) if is_name_start(n) || n == '-' || n == '\\');
    }
    c == '\\'
}

// ---- media queries -----------------------------------------------------

impl ResolvedQuery {
    /// Serialize one query (dart-sass `CssMediaQuery.toString`).
    fn render(&self) -> String {
        let mut s = String::new();
        if let Some(m) = &self.modifier {
            s.push_str(m);
            s.push(' ');
        }
        if let Some(t) = &self.mtype {
            s.push_str(t);
            if !self.conditions.is_empty() {
                s.push_str(" and ");
            }
        }
        let sep = if self.conjunction_and { " and " } else { " or " };
        s.push_str(&self.conditions.join(sep));
        s
    }
}

/// Serialize a comma list of media queries.
/// Whether a parsed media query contains `#{}` interpolation anywhere.
fn media_query_has_interp(q: &MediaQuery) -> bool {
    fn tpl(t: &[TplPiece]) -> bool {
        t.iter().any(|p| matches!(p, TplPiece::Interp(_)))
    }
    fn expr(e: &Expr) -> bool {
        match e {
            Expr::Interp(_) => true,
            Expr::Ident(t) | Expr::QuotedString(t) => tpl(t),
            Expr::Paren(inner) | Expr::Unary { operand: inner, .. } => expr(inner),
            Expr::Binary { lhs, rhs, .. } | Expr::Div { lhs, rhs, .. } => expr(lhs) || expr(rhs),
            Expr::List { items, .. } => items.iter().any(expr),
            _ => false,
        }
    }
    fn in_parens(c: &MediaInParens) -> bool {
        match c {
            MediaInParens::Feature(f) => match &**f {
                MediaFeature::Decl { name, value } => expr(name) || value.as_ref().is_some_and(expr),
                MediaFeature::Range {
                    first, second, rest, ..
                } => expr(first) || expr(second) || rest.as_ref().is_some_and(|(_, e)| expr(e)),
            },
            MediaInParens::Not(inner) => in_parens(inner),
            MediaInParens::Group { conditions, .. } => conditions.iter().any(in_parens),
            MediaInParens::Interp(_) => true,
        }
    }
    match q {
        MediaQuery::Type {
            mtype, conditions, ..
        } => tpl(mtype) || conditions.iter().any(in_parens),
        MediaQuery::Condition { conditions, .. } => conditions.iter().any(in_parens),
    }
}

/// Parse a RESOLVED (interpolation-free) media query list the way dart-sass's
/// `CssMediaQuery.parseList` does: identifiers and `and`/`or` keywords are
/// structural, while each parenthesised condition is kept as raw balanced
/// text (`((a) AnD (b))` survives verbatim).
fn css_media_parse_list(text: &str) -> Result<Vec<ResolvedQuery>, Error> {
    let mut out = Vec::new();
    for part in split_top_level_media_commas(text) {
        let part = part.trim();
        if part.is_empty() {
            continue;
        }
        let mut q = css_media_parse_one(part)?;
        // dart re-parses `(not (a))` as a negation and serializes it WITHOUT
        // the outer parentheses (`@media not (a)`).
        if q.mtype.is_none() && q.modifier.is_none() && q.conditions.len() == 1 {
            let c = q.conditions[0].clone();
            if let Some(inner) = c.strip_prefix('(').and_then(|s| s.strip_suffix(')')) {
                let t = inner.trim();
                let balanced = {
                    let mut d = 0i32;
                    let mut ok = true;
                    for ch in t.chars() {
                        match ch {
                            '(' => d += 1,
                            ')' => {
                                d -= 1;
                                if d < 0 {
                                    ok = false;
                                    break;
                                }
                            }
                            _ => {}
                        }
                    }
                    ok && d == 0
                };
                // Only the exact lowercase `not` keyword re-parses as a
                // negation (dart keeps `(NoT (a))` verbatim).
                if balanced && (t.starts_with("not ") || t.starts_with("not(")) {
                    q.conditions[0] = t.to_string();
                }
            }
        }
        out.push(q);
    }
    Ok(out)
}

fn split_top_level_media_commas(s: &str) -> Vec<String> {
    let mut parts = Vec::new();
    let mut cur = String::new();
    let mut depth = 0i32;
    for c in s.chars() {
        match c {
            '(' | '[' => {
                depth += 1;
                cur.push(c);
            }
            ')' | ']' => {
                depth -= 1;
                cur.push(c);
            }
            ',' if depth == 0 => parts.push(std::mem::take(&mut cur)),
            _ => cur.push(c),
        }
    }
    parts.push(cur);
    parts
}

fn css_media_parse_one(t: &str) -> Result<ResolvedQuery, Error> {
    let chars: Vec<char> = t.chars().collect();
    let mut i = 0usize;
    let skip_ws = |i: &mut usize| {
        while *i < chars.len() && chars[*i].is_whitespace() {
            *i += 1;
        }
    };
    // A raw balanced `(...)` condition, kept verbatim.
    let take_paren = |i: &mut usize| -> Result<String, Error> {
        let start = *i;
        let mut depth = 0i32;
        while *i < chars.len() {
            match chars[*i] {
                '(' => depth += 1,
                ')' => {
                    depth -= 1;
                    if depth == 0 {
                        *i += 1;
                        return Ok(chars[start..*i].iter().collect());
                    }
                }
                _ => {}
            }
            *i += 1;
        }
        Err(Error::unpositioned("expected \")\"."))
    };
    let take_ident = |i: &mut usize| -> String {
        let start = *i;
        while *i < chars.len() && !chars[*i].is_whitespace() && chars[*i] != '(' {
            *i += 1;
        }
        chars[start..*i].iter().collect()
    };
    skip_ws(&mut i);
    // Condition-only form: `(c) [and|or (c)]*` (possibly `not (c)`).
    if i < chars.len() && chars[i] == '(' {
        let mut conditions = vec![take_paren(&mut i)?];
        let mut conjunction_and = true;
        loop {
            skip_ws(&mut i);
            if i >= chars.len() {
                break;
            }
            let word = take_ident(&mut i);
            skip_ws(&mut i);
            match word.to_ascii_lowercase().as_str() {
                "and" => conditions.push(take_paren(&mut i)?),
                "or" => {
                    conjunction_and = false;
                    conditions.push(take_paren(&mut i)?);
                }
                _ => return Err(Error::unpositioned("expected \"and\" or \"or\".")),
            }
        }
        return Ok(ResolvedQuery {
            modifier: None,
            mtype: None,
            conditions,
            conjunction_and,
        });
    }
    let id1 = take_ident(&mut i);
    skip_ws(&mut i);
    if id1.eq_ignore_ascii_case("not") && i < chars.len() && chars[i] == '(' {
        let cond = take_paren(&mut i)?;
        return Ok(ResolvedQuery {
            modifier: None,
            mtype: None,
            conditions: vec![format!("not {cond}")],
            conjunction_and: true,
        });
    }
    // `[modifier] type [and (c)]*` — a second identifier that isn't `and`
    // makes the first the modifier.
    let mut modifier = None;
    let mut mtype = id1;
    if i < chars.len() && chars[i] != '(' {
        let save = i;
        let id2 = take_ident(&mut i);
        if !id2.is_empty() && !id2.eq_ignore_ascii_case("and") {
            modifier = Some(std::mem::replace(&mut mtype, id2));
        } else {
            i = save;
        }
    }
    let mut conditions = Vec::new();
    loop {
        skip_ws(&mut i);
        if i >= chars.len() {
            break;
        }
        let word = take_ident(&mut i);
        if !word.eq_ignore_ascii_case("and") {
            return Err(Error::unpositioned("expected \"and\"."));
        }
        skip_ws(&mut i);
        conditions.push(take_paren(&mut i)?);
    }
    Ok(ResolvedQuery {
        modifier,
        mtype: Some(mtype),
        conditions,
        conjunction_and: true,
    })
}

fn serialize_media_queries(queries: &[ResolvedQuery]) -> String {
    queries
        .iter()
        .map(ResolvedQuery::render)
        .collect::<Vec<_>>()
        .join(", ")
}

/// Merge an enclosing query list with a nested query list (dart-sass
/// `_mergeMediaQueries`). Returns `None` if any pair is unrepresentable (keep
/// the nested rule in place); otherwise the merged list, which is empty when
/// every pair is mutually exclusive (the rule is dropped).
fn merge_media_query_lists(outer: &[ResolvedQuery], inner: &[ResolvedQuery]) -> Option<Vec<ResolvedQuery>> {
    let mut merged = Vec::new();
    for a in outer {
        for b in inner {
            match merge_media_query(a, b) {
                MergeResult::Empty => continue,
                MergeResult::Unrepresentable => return None,
                MergeResult::Query(q) => merged.push(q),
            }
        }
    }
    Some(merged)
}

/// Merge two media queries (dart-sass `CssMediaQuery.merge`).
fn merge_media_query(this: &ResolvedQuery, other: &ResolvedQuery) -> MergeResult {
    if !this.conjunction_and || !other.conjunction_and {
        return MergeResult::Unrepresentable;
    }
    let our_modifier = this.modifier.as_ref().map(|s| s.to_ascii_lowercase());
    let our_type = this.mtype.as_ref().map(|s| s.to_ascii_lowercase());
    let their_modifier = other.modifier.as_ref().map(|s| s.to_ascii_lowercase());
    let their_type = other.mtype.as_ref().map(|s| s.to_ascii_lowercase());

    if our_type.is_none() && their_type.is_none() {
        let mut conditions = this.conditions.clone();
        conditions.extend(other.conditions.iter().cloned());
        return MergeResult::Query(ResolvedQuery {
            modifier: None,
            mtype: None,
            conditions,
            conjunction_and: true,
        });
    }

    let our_not = our_modifier.as_deref() == Some("not");
    let their_not = their_modifier.as_deref() == Some("not");
    let is_all = |t: &Option<String>| t.as_deref() == Some("all");

    let (modifier, mtype, conditions): (Option<String>, Option<String>, Vec<String>);
    if our_not != their_not {
        if our_type == their_type {
            let (neg, pos) = if our_not {
                (&this.conditions, &other.conditions)
            } else {
                (&other.conditions, &this.conditions)
            };
            if neg.iter().all(|c| pos.contains(c)) {
                return MergeResult::Empty;
            }
            return MergeResult::Unrepresentable;
        } else if our_type.is_none() || is_all(&our_type) || their_type.is_none() || is_all(&their_type) {
            return MergeResult::Unrepresentable;
        }
        if our_not {
            modifier = their_modifier.clone();
            mtype = their_type.clone();
            conditions = other.conditions.clone();
        } else {
            modifier = our_modifier.clone();
            mtype = our_type.clone();
            conditions = this.conditions.clone();
        }
    } else if our_not {
        if our_type != their_type {
            return MergeResult::Unrepresentable;
        }
        let (more, fewer) = if this.conditions.len() > other.conditions.len() {
            (&this.conditions, &other.conditions)
        } else {
            (&other.conditions, &this.conditions)
        };
        if !fewer.iter().all(|c| more.contains(c)) {
            return MergeResult::Unrepresentable;
        }
        modifier = our_modifier.clone();
        mtype = our_type.clone();
        conditions = more.clone();
    } else if our_type.is_none() || is_all(&our_type) {
        mtype = if (their_type.is_none() || is_all(&their_type)) && our_type.is_none() {
            None
        } else {
            their_type.clone()
        };
        let mut c = this.conditions.clone();
        c.extend(other.conditions.iter().cloned());
        conditions = c;
        modifier = their_modifier.clone();
    } else if their_type.is_none() || is_all(&their_type) {
        let mut c = this.conditions.clone();
        c.extend(other.conditions.iter().cloned());
        conditions = c;
        modifier = our_modifier.clone();
        mtype = our_type.clone();
    } else if our_type != their_type {
        return MergeResult::Empty;
    } else {
        modifier = our_modifier.clone().or_else(|| their_modifier.clone());
        let mut c = this.conditions.clone();
        c.extend(other.conditions.iter().cloned());
        conditions = c;
        mtype = our_type.clone();
    }

    // dart-sass keeps the raw (original-case) type of whichever query
    // contributed it.
    let final_type = match &mtype {
        None => None,
        Some(_) if mtype == our_type => this.mtype.clone(),
        Some(_) => other.mtype.clone(),
    };
    MergeResult::Query(ResolvedQuery {
        modifier,
        mtype: final_type,
        conditions,
        conjunction_and: true,
    })
}

// ---- modern if() condition evaluation ----------------------------------

/// The tri-state outcome of evaluating a modern `if()` condition: a static
/// boolean, or a residual non-evaluable CSS condition kept for verbatim
/// serialization.
enum CondEval {
    Bool(bool),
    Css(RCond),
}

/// A residual (non-evaluable) modern `if()` condition tree. The raw text of
/// each `Css` leaf already has interpolation resolved; the tree is preserved
/// so `and`/`or`/`not`/parentheses serialize canonically.
enum RCond {
    /// A serialized raw substitution sequence (`css(...)`, `var(...)`, ...).
    Css(String),
    Not(Box<RCond>),
    And(Vec<RCond>),
    Or(Vec<RCond>),
    Paren(Box<RCond>),
}

impl RCond {
    fn to_css(&self) -> String {
        match self {
            RCond::Css(s) => s.clone(),
            RCond::Not(c) => format!("not {}", c.to_css()),
            RCond::And(items) => items.iter().map(RCond::to_css).collect::<Vec<_>>().join(" and "),
            RCond::Or(items) => items.iter().map(RCond::to_css).collect::<Vec<_>>().join(" or "),
            RCond::Paren(c) => format!("({})", c.to_css()),
        }
    }
}

/// Combine the residual operands of an `and`/`or` whose statically-known
/// operands were already folded away. When a single residual remains, the
/// operation collapses to it (and a redundant outer paren is dropped, as in
/// dart-sass); otherwise it stays an `and`/`or` chain.
fn combine_residuals(mut residuals: Vec<RCond>, is_and: bool) -> CondEval {
    match residuals.len() {
        // No residuals: every operand was statically known. An `and` that
        // reached here had no false operand (all true) -> true; an `or`
        // that reached here had no true operand (all false) -> false.
        0 => CondEval::Bool(is_and),
        1 => {
            let single = residuals.pop().unwrap_or(RCond::Css(String::new()));
            // A single surviving operand drops a redundant outer paren.
            let unwrapped = match single {
                RCond::Paren(inner) => *inner,
                other => other,
            };
            CondEval::Css(unwrapped)
        }
        _ => {
            if is_and {
                CondEval::Css(RCond::And(residuals))
            } else {
                CondEval::Css(RCond::Or(residuals))
            }
        }
    }
}

/// Serialize a value for the modern `if()` value position, where dart-sass
/// uses a parenthesized-expression context: lists (including the empty list)
/// are wrapped in parentheses; other values serialize as usual.
fn serialize_if_value(v: &Value) -> String {
    match v {
        Value::List(_) => format!("({})", v.to_css(false)),
        Value::Null => "null".to_string(),
        other => other.to_css(false),
    }
}