sasso 0.8.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
//! 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::borrow::Cow;
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::{CanonicalUrl, CanonicalizeContext, Importer, OutputStyle, Syntax};

mod at_rules;
mod binop;
mod calc;
mod control_flow;
mod expr;
mod meta;
mod modules;
mod plain_css;
mod scope;

use binop::*;
// `eval_div` is part of the crate-internal surface (`crate::eval::eval_div`,
// called from `builtins::math`); re-export it so that path still resolves.
pub(crate) use binop::eval_div;

/// One cached `@import` resolution: (resolved canonical key, syntax, parsed
/// sheet, source text), shared across repeated imports within a single
/// compile. The source rides along so re-executions can swap it in as the
/// current diagnostics/stamp context.
type CachedImport = std::rc::Rc<(String, Syntax, crate::ast::Stylesheet, std::rc::Rc<str>)>;

/// dart `_preModuleComments`: comments registered on a module's first load,
/// keyed by its canonical key, shared by reference down nested module
/// evaluations (see the field on [`Evaluator`]).
type PreModuleComments = Rc<RefCell<HashMap<String, Vec<(String, SrcLines)>>>>;

/// 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()))
}

/// The `@use` namespace tables visible at a callable's definition site.
/// dart's `Environment.closure()` carries them with the rest of the lexical
/// environment: a callable inlined by `@import` must resolve `list.length()`
/// against ITS file's `@use "sass:list"`, not whatever the caller has bound
/// (uswds `units()`, quasar `str-fe()`).
#[derive(Clone)]
pub(crate) struct EnvModules {
    pub(self) used_modules: HashMap<String, String>,
    pub(self) star_modules: Vec<String>,
    pub(self) used_user_modules: HashMap<String, Rc<Module>>,
    pub(self) star_user_modules: Vec<Rc<Module>>,
}

/// 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>,
    pub env_modules: EnvModules,
}

/// A style rule's selector list, carried through the output tree either as the
/// raw resolved strings (the common case — no `@extend` rewrote it, so it is
/// never parsed) or as the typed `Complex` list the `@extend` engine produced
/// (Phase 1d: the engine works on the typed model directly — no `join(", ")` +
/// `parse_list` round trip — and emit renders it via `Complex::render()`, which
/// is byte-identical to the strings the engine used to materialize).
#[derive(Clone)]
pub(crate) enum RuleSelectors {
    /// The already-resolved selector strings (`&`/interpolation substituted).
    /// Untouched by the extend pass — emit writes them verbatim. This is the
    /// zero-parse fast path: an extend-free stylesheet never leaves this form.
    Raw(Vec<String>),
    /// The typed selector list a rewrite produced. Rendered only at emit, via
    /// the same `Complex::render()` the engine used to materialize its strings.
    Parsed(Rc<[crate::selector::Complex]>),
}

impl RuleSelectors {
    /// The selector list as rendered strings: the `Raw` slice borrowed
    /// directly, or each `Parsed` `Complex` rendered (byte-identical to the
    /// strings the extend engine used to produce). Used by emit and by the
    /// pre-extend passes (reparent, plain-CSS at-body lowering) and the
    /// cross-media probe.
    pub(crate) fn to_strings(&self) -> std::borrow::Cow<'_, [String]> {
        match self {
            RuleSelectors::Raw(v) => std::borrow::Cow::Borrowed(v),
            RuleSelectors::Parsed(v) => std::borrow::Cow::Owned(v.iter().map(|c| c.render()).collect()),
        }
    }

    /// Consume into rendered strings (owned), for the pre-extend lowering paths
    /// that move a rule's selectors into an `OutItem`/joined parent shell.
    fn into_strings(self) -> Vec<String> {
        match self {
            RuleSelectors::Raw(v) => v,
            RuleSelectors::Parsed(v) => v.iter().map(|c| c.render()).collect(),
        }
    }
}

/// A flattened output node.
#[derive(Clone)]
pub(crate) enum OutNode {
    Rule {
        selectors: RuleSelectors,
        /// 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,
    },
    /// Control-only marker (never serialized): 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.
    GroupEnd,
    /// Control-only marker (never serialized): left in an enclosing `@media` body
    /// where a merged nested media rule bubbled out; the outer rule splits its own
    /// children around it.
    MediaHoist,
    /// Control-only marker (never serialized): left where an `@at-root` hoisted a
    /// batch out of one or more enclosing at-rules. `target` is 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.
    AtRootHoist {
        target: usize,
    },
    /// Control-only marker (never serialized): 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.
    AtRootPackTight,
}

impl OutNode {
    /// A non-evaluated style rule — a plain-CSS passthrough, an `@at-root`
    /// graft, a reparent shell, etc. It carries no per-complex line breaks and
    /// `extend_base` `usize::MAX`, so the `@extend` pass always applies the
    /// sequential default. Only `selectors`, `items` and `lines` vary across
    /// the call sites; the rest is shared boilerplate.
    pub(crate) fn plain_rule(selectors: Vec<String>, items: Vec<OutItem>, lines: SrcLines) -> OutNode {
        OutNode::Rule {
            selectors: RuleSelectors::Raw(selectors),
            linebreaks: Vec::new(),
            items,
            lines,
            extend_base: usize::MAX,
        }
    }

    /// A childless at-rule (`@name prelude;`) — no body, no block.
    pub(crate) fn childless_at_rule(name: String, prelude: String, lines: SrcLines) -> OutNode {
        OutNode::AtRule {
            name,
            prelude,
            body: Vec::new(),
            has_block: false,
            lines,
        }
    }
}

/// 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>),
    /// Root-hoisted buffer. `group_ends` is set only for a true `@at-root`
    /// body deposit — a completed style rule then leaves a group-end
    /// sentinel (dart marks isGroupEnd when `_styleRule == null`); generic
    /// at-rule bodies (@media/@supports) keep their own separator logic.
    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 {
        body: &'a mut Vec<OutNode>,
        group_ends: bool,
    },
}

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::childless_at_rule(name, prelude, 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::GroupEnd);
            }
            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::childless_at_rule(name, prelude, 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::plain_rule(selectors, items, SrcLines::default()))
                }
                // 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::plain_rule(selectors, items, SrcLines::default())
                            }
                            OutItem::ChildlessAtRule { name, prelude, lines } => {
                                OutNode::childless_at_rule(name, prelude, lines)
                            }
                            OutItem::NestedAtRule { name, prelude, items } => OutNode::AtRule {
                                name,
                                prelude,
                                body: vec![OutNode::plain_rule(Vec::new(), items, SrcLines::default())],
                                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) -> bool {
        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 true;
                        }
                        // (a non-Rule at that index can't happen: `flushed`
                        // only ever records a flushed block fragment)
                    }
                    let rule = OutNode::Rule {
                        selectors: RuleSelectors::Raw(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);
                    return true;
                }
            }
        }
        false
    }

    /// 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>, allow_group_end: bool) {
        match self {
            Sink::Top(out) => {
                let out = &mut **out;
                // An `@at-root` chunk hoisted in-place leaves an INTERIOR
                // group-end marker before the resumed parent rule; materialize it
                // into the one blank line dart emits there. A TRAILING marker
                // (nothing resumes) is left untouched — it's the rule's own
                // isGroupEnd, consumed by the next group's `push_group`.
                let output = materialize_interior_group_ends(output);
                // dart-sass isGroupEnd is set only by visitStyleRule, and an
                // INVISIBLE rule (e.g. `@extend`-only, no declarations) never
                // becomes `previous` in _visitChildren — it must not leave a
                // group-end behind, or the next sibling gains a phantom blank
                // line (bootstrap: two @media from consecutive @each rounds).
                let produced = output
                    .iter()
                    .any(|n| !matches!(n, OutNode::Blank | OutNode::AtRootPackTight | OutNode::GroupEnd));
                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 —
                // UNLESS the rule's own last child was an invisible empty
                // rule, which owns the group end in dart and never renders;
                // then the next group packs TIGHT (the pack-tight sentinel
                // also suppresses push_group's default blank-after-rule).
                if produced && !out.is_empty() {
                    out.push(if allow_group_end {
                        OutNode::GroupEnd
                    } else {
                        OutNode::AtRootPackTight
                    });
                }
            }
            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, group_ends } => {
                // For a true `@at-root` body: a completed style rule at the
                // body's own level marks a group end (dart sets isGroupEnd
                // only when `_styleRule == null` — rules flattened out of a
                // wrapper rule arrive inside ONE batch and pack tight); an
                // invisible trailing child packs the next group tight.
                let produced = *group_ends
                    && output
                        .iter()
                        .any(|n| !matches!(n, OutNode::Blank | OutNode::AtRootPackTight | OutNode::GroupEnd));
                body.extend(output);
                if produced {
                    body.push(if allow_group_end {
                        OutNode::GroupEnd
                    } else {
                        OutNode::AtRootPackTight
                    });
                }
            }
        }
    }

    /// 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>,
    /// Host-defined custom functions (dart-sass `functions`), matched by name.
    pub functions: &'a [crate::host_fn::HostFn],
    /// 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,
    /// Diagnostic handler (dart-sass `logger`). When set, `@warn`/`@debug`/
    /// deprecation warnings are delivered here instead of printed to stderr.
    pub warn: Option<&'a crate::WarnHandler>,
}

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>>>,
    /// dart `_preModuleComments`: on a module's FIRST load, the loader's
    /// pending top-level comments move into this map (keyed by the loaded
    /// module's canonical key) and re-emit at every dependency edge into
    /// that module. Crucially, dart does NOT reset the field when a child
    /// module evaluates — the child inherits the loader's map by REFERENCE,
    /// so the child's own edges re-emit the parent's registered comments
    /// (bulma's `/* Bulma Form */` appears before each `@use "shared"`er's
    /// CSS). `None` until a registration creates a map; eval_module
    /// saves/restores so a child-created map never leaks upward.
    pre_module_comments: Option<PreModuleComments>,
    /// Top-sink index below which pending-comment scans must not reach:
    /// everything below is a re-emitted comment CLONE (dart materializes
    /// clones at combine time, so they never re-register as pending).
    /// Indexes into the current module's top sink; reset per module eval.
    pre_comment_floor: usize,
    /// `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 [`OutNode::MediaHoist`] 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
    /// [`OutNode::AtRootHoist`] markers; 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>,
    /// Source-map position of the innermost enclosing style rule's selector
    /// (its `rule_lines`). A bubbled `@media`/`@at-root` wrapper re-uses this so
    /// the duplicated parent selector maps to the ORIGINAL rule's span (dart
    /// parity); `SrcLines::default()` when not inside a style rule. Used ONLY
    /// for source maps — never affects CSS bytes.
    cur_rule_lines: SrcLines,
    /// The enclosing style rule's `extend_base` (how many `@extend`s were
    /// registered when it was created), inherited by the wrap that re-emits
    /// its selectors inside a nested at-rule — the @media copy of a rule is
    /// created "at the same time" as the rule for dart's addSelector timing.
    cur_rule_extend_base: usize,
    /// 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>,
    /// The canonical URL of the file currently being evaluated, passed to the
    /// importer as `CanonicalizeContext::containing_url`.
    ///
    /// INVARIANT: tracked in **lockstep** with [`Self::current_file_dir`] — every
    /// site that swaps `current_file_dir` must swap this too, or a relative
    /// `@use`/`@import`/`meta.load-css` resolves against the wrong file. The four
    /// sites: entry init (`Evaluator::new`), `eval_module`, the `@import` enter,
    /// and `enter_module_file`. (The two are kept separate rather than derived
    /// because `current_file_dir` is also the `@import` cache key.)
    current_canonical: Option<CanonicalUrl>,
    /// 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 `_inUnknownAtRule`: inside the body of a generic/unknown at-rule
    /// (`@utility`, `@layer`, `@font-face`, vendor `@foo`, …). Bare
    /// declarations are legal there even without an enclosing style rule —
    /// including directly inside a nested `@media` (Tailwind v4's
    /// `@utility x { @media (…) { max-width: …; } }`).
    in_unknown_at_rule: bool,
    /// Whether the most recent CSS-NODE-CREATING statement in the current
    /// body was an EMPTY style rule (extend-only / no declarations). dart
    /// creates a CssStyleRule node even then; being invisible it still OWNS
    /// its group end, which the serializer never sees — so a rule whose LAST
    /// child was such a statement emits no blank-line separator
    /// (`.brand` stays tight after `.nav { %p {…} > .c { @extend %p; } }`).
    /// Statements that create no node (variables, @extend, loads, control
    /// flow shells) leave it untouched.
    last_child_invisible: 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>,
    /// Source-map URL OVERRIDES: a loaded file's display URL -> the URL an
    /// importer asked the source map to record for it (`ImporterResult
    /// .source_map_url`). Empty for the filesystem importer / entry file, so the
    /// generated source map is byte-identical unless a custom importer sets it.
    file_map_urls: HashMap<String, String>,
}

/// 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,
    /// The module's canonical URL (the importer's dedup key), passed as the
    /// importer's `containing_url` while the module's own code (incl. a
    /// `meta.load-css` in one of its mixins) resolves relative URLs.
    canonical: 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>,
    /// dart `transitivelyContainsCss` includes `preModuleComments.isNotEmpty`
    /// on the map SNAPSHOT taken at module construction: a css-less module
    /// built while the shared pre-module-comment map holds ANY entry counts
    /// as css-bearing — it absorbs pending-comment registrations and its
    /// edges re-emit like a visible module's.
    phantom_css: bool,
}

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_canonical = CanonicalUrl::new(options.url);
        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(),
            file_map_urls: 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()),
            pre_module_comments: None,
            pre_comment_floor: 0,
            load_css_copies: RefCell::new(Vec::new()),
            copy_counter: std::cell::Cell::new(0),
            in_keyframes: false,
            in_unknown_at_rule: false,
            last_child_invisible: 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),
            // The entry file's canonical URL = its display URL; the FsImporter
            // derives the same search base from its dirname (a bare name like
            // `input.scss` -> "" = CWD, matching `entry_dir`).
            current_canonical: Some(entry_canonical),
            media_hoist: Vec::new(),
            at_root_hoist: std::collections::VecDeque::new(),
            at_rule_ctx: Vec::new(),
            cur_rule_lines: SrcLines::default(),
            cur_rule_extend_base: usize::MAX,
            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(())
    }

    /// The source-map `sources` table, ordered so that an interned file id `i`
    /// (1-based, as stamped into [`SrcLines::file`]) lands at `sources[i - 1]`.
    /// `entry_url` is forced to index 0 even when no node was stamped (an empty
    /// or output-less stylesheet), matching dart-sass always listing the entry.
    /// When `include_sources` is set, the parallel `sourcesContent` is built
    /// from the recorded file sources (empty string for a source seen only by
    /// URL, never by text).
    pub(crate) fn source_table(
        &mut self,
        entry_url: &str,
        include_sources: bool,
    ) -> (Vec<String>, Option<Vec<String>>) {
        // Guarantee the entry url occupies id 1 (index 0) even if nothing was
        // stamped during evaluation.
        if self.file_ids.is_empty() {
            self.file_ids.insert(entry_url.to_string(), 1);
        }
        let mut by_id: Vec<(u32, &str)> = self
            .file_ids
            .iter()
            .map(|(url, &id)| (id, url.as_str()))
            .collect();
        by_id.sort_by_key(|&(id, _)| id);
        // Apply any importer-supplied source-map URL override; the `content`
        // lookup below still keys on the original url, so they stay consistent.
        let sources: Vec<String> = by_id
            .iter()
            .map(|&(_, url)| {
                self.file_map_urls
                    .get(url)
                    .cloned()
                    .unwrap_or_else(|| url.to_string())
            })
            .collect();
        let content = if include_sources {
            let srcs = self.file_sources.borrow();
            Some(
                by_id
                    .iter()
                    .map(|&(_, url)| srcs.get(url).map(|s| s.to_string()).unwrap_or_default())
                    .collect(),
            )
        } else {
            None
        };
        (sources, content)
    }

    // ---- 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));
        let formatted = format!("{block}\n");
        self.emit_diag(crate::WarnEvent {
            kind: crate::WarnKind::Warn,
            deprecation: true,
            deprecation_id: dep.id,
            message: &dep.message,
            formatted: &formatted,
            url: &self.current_url,
            line: pos.line,
        });
    }

    /// 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;
        }
        let msg = format!(
            "{} repetitive deprecation warnings omitted.",
            self.deprecations_omitted
        );
        let formatted = format!("WARNING: {msg}\nRun in verbose mode to see all warnings.\n");
        self.emit_diag(crate::WarnEvent {
            kind: crate::WarnKind::Warn,
            deprecation: true,
            deprecation_id: "",
            message: &msg,
            formatted: &formatted,
            url: "",
            line: 0,
        });
    }

    /// 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;
    }

    /// Deliver a diagnostic to the embedder's handler (dart-sass `logger`), or —
    /// when none is set — print its `formatted` block to stderr (preserving the
    /// exact native output, since the handler-less path mirrors the old
    /// `eprintln!`s byte-for-byte).
    fn emit_diag(&self, ev: crate::WarnEvent<'_>) {
        match self.options.warn {
            Some(handler) => handler(&ev),
            None => eprintln!("{}", ev.formatted),
        }
    }

    /// 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();
        let formatted = if self.diag_enabled() {
            let frames = self.frames_for(pos);
            format!("WARNING: {}\n{}\n", msg, Self::render_frame_block(&frames, 4))
        } else {
            format!("WARNING: {msg}")
        };
        self.emit_diag(crate::WarnEvent {
            kind: crate::WarnKind::Warn,
            deprecation: false,
            deprecation_id: "",
            message: &msg,
            formatted: &formatted,
            url: "",
            line: 0,
        });
        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();
        let url = self.current_url.clone();
        let formatted = if self.diag_enabled() {
            format!("{url}:{} DEBUG: {msg}", pos.line)
        } else {
            format!("DEBUG: {msg}")
        };
        self.emit_diag(crate::WarnEvent {
            kind: crate::WarnKind::Debug,
            deprecation: false,
            deprecation_id: "",
            message: &msg,
            formatted: &formatted,
            url: &url,
            line: pos.line,
        });
        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
    }

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

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

    // ---- 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);
                    self.last_child_invisible = false;
                }
                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);
                        self.last_child_invisible = false;
                    }
                }
                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)?;
                    self.last_child_invisible = false;
                }
                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);
                        self.last_child_invisible = false;
                    }
                }
                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 i in 0..items.len() {
                        self.bind_each(vars, items.get(i));
                        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)?;
                    self.last_child_invisible = false;
                }
                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,
                        )?;
                    }
                    self.last_child_invisible = false;
                }
                Stmt::CssCustomAtRule { name, prelude, body } => {
                    self.eval_css_custom_at_rule(name, prelude, body, sink)?;
                    self.last_child_invisible = false;
                }
                Stmt::Media { query, body, lines } => {
                    let stamped = self.stamp(*lines);
                    self.eval_media(query, body, stamped, parents, sink)?;
                    self.last_child_invisible = false;
                }
                Stmt::Supports {
                    condition,
                    body,
                    lines,
                } => {
                    let stamped = self.stamp(*lines);
                    self.eval_supports(condition, body, stamped, parents, sink)?;
                    self.last_child_invisible = false;
                }
                Stmt::AtRoot { query, body } => {
                    self.eval_at_root(query.as_deref(), body, parents, sink)?;
                    self.last_child_invisible = false;
                }
                Stmt::Keyframes {
                    name,
                    prelude,
                    body,
                    lines,
                } => {
                    let lines = self.stamp(*lines);
                    self.eval_keyframes(name, prelude, body, lines, sink)?;
                    self.last_child_invisible = false;
                }
                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.
        // Fast path for the line-break flags: no newline anywhere in the source
        // list and no inherited parent breaks means every flag is false — an
        // EMPTY vec, which all consumers read as all-false. Keyframe selector
        // lists always take it (dart re-serializes stops joined with ", ").
        let lbs_fast = self.in_keyframes || (self.current_linebreaks.is_empty() && !sel_str.contains('\n'));
        let part_lbs: Vec<bool> = if lbs_fast {
            Vec::new()
        } else {
            comma_linebreaks(&sel_str, false)
        };
        let parent_lbs: &[bool] = if self.current_linebreaks.len() == parents.len() {
            &self.current_linebreaks
        } else {
            &[]
        };
        let (current, resolved_lbs): (Vec<String>, Vec<bool>) = if self.in_keyframes {
            (
                split_commas(&sel_str)
                    .into_iter()
                    .map(|p| p.trim().to_string())
                    .filter(|p| !p.is_empty())
                    .collect(),
                Vec::new(),
            )
        } else {
            resolve_selectors_opt(
                &sel_str,
                parents,
                !self.at_root_excluding_style_rule,
                &part_lbs,
                parent_lbs,
            )?
            .into_iter()
            .unzip()
        };
        // 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.
        // Keyframe selector lists always take it: dart re-serializes the
        // stops joined with ", " (KeyframeSelectorParser), dropping author
        // line breaks that style-rule selectors would preserve.
        let full_lbs: Vec<bool> = if lbs_fast { Vec::new() } else { resolved_lbs };
        let mut emit_selectors: Vec<String> = Vec::with_capacity(current.len());
        let mut emit_linebreaks: Vec<bool> = Vec::with_capacity(current.len());
        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,
            // Source-map: the selector's 0-based start column (its first
            // character), mapped on the rule's first output line.
            start_col: (rule.selector_pos.col as u32).saturating_sub(1),
            map_file: 0,
            map_line: 0,
        });
        // A `@media`/`@at-root` nested in this rule's body bubbles a copy of the
        // selector out; that copy maps back to THIS selector's source position
        // (dart parity). Source-map only — never touches CSS.
        let prev_rule_lines = std::mem::replace(&mut self.cur_rule_lines, rule_lines);
        let prev_rule_extend_base = std::mem::replace(&mut self.cur_rule_extend_base, self.extends.len());
        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();
        // Fresh trailing-invisible tracking for THIS body (the exit below
        // overwrites the flag with this rule's own contribution, so the
        // parent needs no save).
        self.last_child_invisible = false;
        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() {
                // The flushed block is the subtree's last node — visible.
                self.last_child_invisible = false;
            }
            r
        };
        self.current_selector = prev_selector;
        self.current_linebreaks = prev_linebreaks;
        self.at_root_excluding_style_rule = prev_at_root;
        self.cur_rule_lines = prev_rule_lines;
        self.cur_rule_extend_base = prev_rule_extend_base;
        self.pop_scope();
        result?;
        // The body's own trailing-invisible state gates THIS rule's group
        // end; then report this rule's contribution to the PARENT body
        // (empty output = dart's invisible node).
        let body_last_invisible = std::mem::replace(&mut self.last_child_invisible, false);
        let this_rule_invisible = nested.is_empty() && !self.in_keyframes;
        sink.emit_style_rule(nested, !body_last_invisible);
        // dart's group separator rides the subtree's LAST flattened node: a
        // trailing invisible chain ANY levels down (`#al { a { &:hover {
        // @extend } } }`) owns the enclosing group's end and never renders,
        // so the next group packs tight (chirpy panel -> footer seam).
        self.last_child_invisible = this_rule_invisible || body_last_invisible;
        Ok(())
    }

    fn eval_decl(&mut self, d: &Declaration) -> Result<Option<OutItem>, Error> {
        let name = trim_owned(self.eval_template(&d.property)?);
        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,
                // Source-map: the property name's 0-based start column.
                start_col: (d.pos.col as u32).saturating_sub(1),
                map_file: 0,
                map_line: 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 = trim_owned(self.eval_template(&d.property)?);
        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,
                // Source-map: the property name's 0-based start column.
                start_col: (d.pos.col as u32).saturating_sub(1),
                map_file: 0,
                map_line: 0,
            }),
        }))
    }

    /// 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 = trim_owned(self.eval_template(&ps.property)?);
        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();
                            // Two-phase resolution (canonicalize, then load),
                            // both inside ONE arena pause so the importer's owned
                            // allocations survive this compile's arena reset.
                            let resolved = match importer {
                                Some(imp) => {
                                    let ctx = CanonicalizeContext {
                                        from_import: true,
                                        containing_url: self.current_canonical.as_ref(),
                                    };
                                    match imp.canonicalize(path, &ctx) {
                                        Err(e) => {
                                            crate::arena::resume(saved);
                                            return Err(Error::unpositioned(e.message));
                                        }
                                        Ok(None) => None,
                                        Ok(Some(canon)) => match imp.load(&canon) {
                                            Err(e) => {
                                                crate::arena::resume(saved);
                                                return Err(Error::unpositioned(e.message));
                                            }
                                            Ok(None) => None,
                                            // `res.source_map_url` is intentionally dropped here:
                                            // `@import` is textual, so the imported file gets NO
                                            // distinct source-map entry (its tokens map under the
                                            // importing file). Only `@use`/`@forward` (modules.rs)
                                            // record the override.
                                            Ok(Some(res)) => {
                                                Some((canon.as_str().to_string(), res.contents, res.syntax))
                                            }
                                        },
                                    }
                                }
                                None => None,
                            };
                            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 = match parse_with_syntax(&src, syntax) {
                                        Ok(sheet) => sheet,
                                        Err(err) => {
                                            // A parse error names the IMPORTED
                                            // file: render eagerly under its
                                            // url/source with an `@import`
                                            // frame at the URL token (dart:
                                            // `_mod.scss 3:19  @import`).
                                            let diag = self.module_diag_url(path, &resolved_key);
                                            let saved_member = self.enter_call(*pos, *length, "@import");
                                            let saved_url = std::mem::replace(&mut self.current_url, diag);
                                            let saved_source = std::mem::replace(
                                                &mut self.current_source,
                                                Rc::from(src.as_str()),
                                            );
                                            let err = self.finalize_error(err);
                                            self.current_url = saved_url;
                                            self.current_source = saved_source;
                                            self.leave_call(saved_member);
                                            return Err(err);
                                        }
                                    };
                                    let e = std::rc::Rc::new((
                                        resolved_key,
                                        syntax,
                                        sheet,
                                        std::rc::Rc::<str>::from(src.as_str()),
                                    ));
                                    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);
                            // The diagnostic `@import` frame records the
                            // IMPORTING file at the URL token — push it before
                            // the context swap below rebinds current_url.
                            let saved_member = self.enter_call(*pos, *length, "@import");
                            // The imported file becomes the diagnostics/stamp
                            // context while its body runs (dart shows ITS name
                            // in error frames, and the trailing-comment check
                            // compares file identity): swap in its display URL
                            // and source, and re-intern the SrcLines file id.
                            let import_diag = if resolved_key.is_empty() {
                                self.current_url.clone()
                            } else {
                                self.module_diag_url(path, resolved_key)
                            };
                            if self.diag_enabled() && !resolved_key.is_empty() {
                                self.file_sources
                                    .borrow_mut()
                                    .entry(import_diag.clone())
                                    .or_insert_with(|| Rc::clone(&entry.3));
                            }
                            let saved_import_url = std::mem::replace(&mut self.current_url, import_diag);
                            let saved_import_source =
                                std::mem::replace(&mut self.current_source, Rc::clone(&entry.3));
                            self.current_url_stamp = 0;
                            // 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)
                                    .map_err(|e| self.finalize_error(e));
                                self.loading.pop();
                                self.current_url = saved_import_url;
                                self.current_source = saved_import_source;
                                self.current_url_stamp = 0;
                                self.leave_call(saved_member);
                                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).into_owned(), (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))
                            };
                            // Track the imported file's canonical URL in lockstep
                            // (so a nested relative `@use`/`@import` inside it
                            // resolves against ITS directory).
                            let saved_canonical = if resolved_key.is_empty() {
                                self.current_canonical.clone()
                            } else {
                                self.current_canonical
                                    .replace(CanonicalUrl::new(resolved_key.clone()))
                            };
                            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 \"{\"."));
                            }
                            // Render any error before the context restores
                            // below strip its attribution (the `@import`
                            // frame from above is still on the stack).
                            let result = self
                                .exec(&sheet.stmts, parents, sink)
                                .map_err(|e| self.finalize_error(e));
                            self.leave_call(saved_member);
                            self.current_url = saved_import_url;
                            self.current_source = saved_import_source;
                            self.current_url_stamp = 0;
                            self.current_file_dir = saved_dir;
                            self.current_canonical = saved_canonical;
                            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(())
    }
}

/// 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,
            } => {
                let selectors = selectors.into_strings();
                if selectors.iter().any(|s| part_has_parent_ref(s)) {
                    preserved.push(OutItem::NestedRule { selectors, items });
                } else {
                    rest.push(OutNode::Rule {
                        selectors: RuleSelectors::Raw(
                            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::plain_rule(
            parents.to_vec(),
            preserved,
            SrcLines::default(),
        ));
    }
    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,
    )
}

/// 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,
}

/// The lexical context a statement is nested in, used to statically reject
/// misplaced statements exactly like dart-sass — *before* evaluation, so even
/// an unexecuted `@if false { … }` branch is validated.
#[derive(Clone, Copy)]
struct ScopeCtx {
    /// `@function`/`@mixin`/control declaration scope (see [`DeclScope`]).
    decl: DeclScope,
    /// Lexically inside a style rule (dart-sass's parser `_inStyleRule`). Set by
    /// [`Stmt::Rule`]; preserved through `@media`/`@supports`/`@keyframes`/
    /// generic at-rules and control directives. Governs where `@extend` may
    /// appear lexically.
    in_style_rule: bool,
    /// Inside an `@at-root` body or an `@include` content block: the lexical
    /// `@extend` placement check is deferred to the evaluator, which checks the
    /// *runtime* style-rule context (the `@at-root` query and the include site
    /// determine whether a style rule survives — neither is knowable statically).
    /// All other validations still apply.
    defer_extend: bool,
}

impl ScopeCtx {
    fn root() -> Self {
        ScopeCtx {
            decl: DeclScope::Allowed,
            in_style_rule: false,
            defer_extend: false,
        }
    }
    fn with(self, decl: DeclScope) -> Self {
        ScopeCtx { decl, ..self }
    }
}

/// Reject statements nested where dart-sass forbids them. Runs once after
/// parsing, so an unexecuted `@while (false) { @function … }` still errors (it
/// is a compile-time, not run-time, restriction). Covers:
/// - `@function`/`@mixin` declarations in control/function/mixin bodies;
/// - the full set of statements illegal inside a `@function` body (style rules,
///   declarations, and everything that isn't a var assignment / control flow /
///   `@return` / `@warn` / `@debug` / `@error`);
/// - `@content` outside a `@mixin` declaration;
/// - `@extend` outside a style rule or mixin.
pub(crate) fn validate_declarations(sheet: &Stylesheet) -> Result<(), Error> {
    validate_decl_scope(&sheet.stmts, ScopeCtx::root())
}

fn validate_decl_scope(stmts: &[Stmt], ctx: ScopeCtx) -> Result<(), Error> {
    let scope = ctx.decl;
    for stmt in stmts {
        // Inside a `@function` body dart-sass only permits variable
        // assignments, control flow, `@return`, `@warn`/`@debug`/`@error`, and
        // comments. Reject the rest here (with dart's precedence ordering)
        // before the generic per-statement handling below.
        if scope == DeclScope::Function {
            match stmt {
                // The indented-syntax parser can attach a function header's
                // parameter list on a continuation line (`@function a\n  ()`) as
                // a spurious empty-`()` "style rule" in the body. dart-sass reads
                // it as the (empty) parameter list, not a rule — and `()` is not
                // a valid selector dart would ever produce — so this artifact is
                // not a real style rule. Skip it; a genuine rule is rejected.
                Stmt::Rule(r) if is_empty_parens_selector(&r.selector) => {}
                Stmt::Rule(_) => {
                    return Err(Error::unpositioned(
                        "@function rules may not contain style rules.".to_string(),
                    ));
                }
                Stmt::Decl(_) | Stmt::CustomDecl(_) | Stmt::PropertySet(_) => {
                    return Err(Error::unpositioned(
                        "@function rules may not contain declarations.".to_string(),
                    ));
                }
                // Allowed in a function body: keep walking (control flow) or
                // accept verbatim (assignments / `@return` / diagnostics /
                // comments). Function/mixin definitions fall through to the
                // declaration check below, which already yields dart's
                // "This at-rule is not allowed here." for a nested function.
                Stmt::VarDecl(_)
                | Stmt::Return(_)
                | Stmt::Warn { .. }
                | Stmt::Debug { .. }
                | Stmt::Error { .. }
                | Stmt::Comment(..)
                | Stmt::If(_)
                | Stmt::For { .. }
                | Stmt::Each { .. }
                | Stmt::While { .. }
                | Stmt::FunctionDef(_)
                | Stmt::MixinDef(_) => {}
                // Anything else (@extend, @content, @include, @media, @at-root,
                // @use, @import, @charset, generic at-rules, …) is rejected.
                _ => {
                    return Err(Error::unpositioned(
                        "This at-rule is not allowed here.".to_string(),
                    ));
                }
            }
        }
        match stmt {
            Stmt::FunctionDef(c) => {
                if let Some(msg) = decl_error(scope, "function") {
                    return Err(Error::unpositioned(msg));
                }
                validate_decl_scope(&c.body, ctx.with(DeclScope::Function))?;
            }
            Stmt::MixinDef(c) => {
                if let Some(msg) = decl_error(scope, "mixin") {
                    return Err(Error::unpositioned(msg));
                }
                validate_decl_scope(&c.body, ctx.with(DeclScope::Mixin))?;
            }
            // `@content` is only legal lexically within a `@mixin` declaration
            // (directly or nested through style rules / control / at-rules). The
            // `decl` scope is `Mixin` throughout a mixin body, so testing it
            // captures every nesting. (Inside a `@function` the earlier guard
            // already emitted "This at-rule is not allowed here.".)
            Stmt::Content(_) if scope != DeclScope::Mixin => {
                return Err(Error::unpositioned(
                    "@content is only allowed within mixin declarations.".to_string(),
                ));
            }
            // `@extend` applies at the include site, so lexically it is legal
            // only within a style rule or a mixin. Elsewhere — top level, or a
            // control directive not inside a style rule — dart-sass errors at
            // parse time. (Inside a `@function` the earlier guard wins; inside
            // an `@at-root` body or an `@include` content block the check is
            // deferred to the evaluator — see `defer_extend`.)
            Stmt::Extend { .. } if !ctx.defer_extend && !ctx.in_style_rule && scope != DeclScope::Mixin => {
                return Err(Error::unpositioned(
                    "@extend may only be used within style rules.".to_string(),
                ));
            }
            // Control directives establish (or keep) the control/function/mixin
            // scope; a `@function`/`@mixin` body's scope sticks through them.
            // They preserve the enclosing `in_style_rule` flag.
            Stmt::If(branches) => {
                let inner = ctx.with(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, ctx.with(enter_control(scope)))?;
            }
            // A style rule establishes the style-rule context for `@extend`.
            Stmt::Rule(r) => {
                validate_decl_scope(
                    &r.body,
                    ScopeCtx {
                        in_style_rule: true,
                        ..ctx
                    },
                )?;
            }
            // `@at-root` runs its body at the document root: whether a style
            // rule survives depends on the (runtime-evaluated) `with`/`without`
            // query, so defer the `@extend` placement check to the evaluator.
            // A nested style rule inside the body re-establishes `in_style_rule`
            // for its own descendants (handled by the `Stmt::Rule` arm).
            Stmt::AtRoot { body, .. } => {
                validate_decl_scope(
                    body,
                    ScopeCtx {
                        defer_extend: true,
                        ..ctx
                    },
                )?;
            }
            // Plain at-rules / `@media` / `@supports` / `@keyframes` preserve
            // both the declaration scope and the style-rule context.
            Stmt::AtRule { body: Some(body), .. }
            | Stmt::Media { body, .. }
            | Stmt::Supports { body, .. }
            | Stmt::Keyframes { body, .. } => validate_decl_scope(body, ctx)?,
            // An `@include`'s content block resolves at the include site, so its
            // `@extend` placement is only knowable at runtime — defer it. The
            // block is still mixin-body-like for declaration validation, so the
            // other checks keep running with the surrounding scope.
            Stmt::Include {
                content: Some(content),
                ..
            } => validate_decl_scope(
                content,
                ScopeCtx {
                    defer_extend: true,
                    ..ctx
                },
            )?,
            // 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(())
}

/// True when a rule selector is the empty-`()` artifact the indented-syntax
/// parser emits for a `@function` header whose parameter list spills onto a
/// continuation line. dart-sass treats `()` there as the parameter list, never
/// a selector, so it must not count as a style rule inside a `@function` body.
fn is_empty_parens_selector(selector: &[TplPiece]) -> bool {
    match selector {
        [TplPiece::Lit(s)] => s.trim() == "()",
        _ => false,
    }
}

/// 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.")),
    }
}

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;
                        rest.push(OutNode::ModuleScope {
                            key,
                            nodes: inner_rest,
                        });
                    }
                }
                _ => 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 mut tail = own.split_off(li + 1);
            imports.extend(own.into_iter().filter(|n| !matches!(n, OutNode::Blank)));
            // Pulling the run leaves a NEW seam between the preceding css and
            // the remainder: its eval-time separator left with the run, so
            // re-derive it exactly like the eval-time `push_group` (dart's
            // group-end rule). Everything after the seam keeps its eval-time
            // grouping verbatim (a parent rule packs tight against its own
            // flattened nested children).
            while matches!(tail.first(), Some(OutNode::Blank)) {
                tail.remove(0);
            }
            if tail.iter().any(|n| !matches!(n, OutNode::Blank)) {
                *css_seen = true;
            }
            push_group(&mut rest, tail);
            return rest;
        }
        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);
    // The css flow keeps its eval-time grouping and packs tight against the
    // imports bucket (dart writes the flow right after the imports).
    let mut rest = rest;
    while matches!(rest.first(), Some(OutNode::Blank)) {
        rest.remove(0);
    }
    out.extend(rest);
    while matches!(out.last(), Some(OutNode::Blank)) {
        out.pop();
    }
}

/// 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);
    }
}

/// Turn an INTERIOR `GroupEnd` marker (one that is immediately followed by an
/// output-producing node) into a single `Blank`, leaving a trailing marker
/// untouched. An in-place `@at-root` hoist that resumes its enclosing style rule
/// leaves such a marker between the hoisted style rule and the resumed parent;
/// dart separates them with one blank line. Today the only `GroupEnd` reaching a
/// style rule's `nested` is that one (top-level post-rule markers stay trailing,
/// consumed by the next `push_group`), so this is a no-op for every other shape.
pub(super) fn materialize_interior_group_ends(nodes: Vec<OutNode>) -> Vec<OutNode> {
    let is_content = |n: &OutNode| {
        !matches!(
            n,
            OutNode::Blank
                | OutNode::GroupEnd
                | OutNode::MediaHoist
                | OutNode::AtRootHoist { .. }
                | OutNode::AtRootPackTight
        )
    };
    let mut result: Vec<OutNode> = Vec::with_capacity(nodes.len());
    let mut iter = nodes.into_iter().peekable();
    while let Some(node) = iter.next() {
        if matches!(node, OutNode::GroupEnd) && iter.peek().is_some_and(is_content) {
            result.push(OutNode::Blank);
        } else {
            result.push(node);
        }
    }
    result
}

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::AtRootPackTight | OutNode::GroupEnd) {
        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). An EMPTY
    // module scope (e.g. a settings module of pure variables) is invisible
    // and must not act as the separator anchor — skip it and keep drilling
    // (uswds/bulma function modules ending in `@use "settings"`).
    fn invisible_wrapper(n: &OutNode) -> bool {
        match n {
            OutNode::Blank => true,
            OutNode::ModuleScope { nodes, .. } => nodes.iter().all(invisible_wrapper),
            _ => false,
        }
    }
    fn last_effective(n: &OutNode) -> &OutNode {
        if let OutNode::ModuleScope { nodes, .. } = n {
            if let Some(l) = nodes.iter().rev().find(|x| !invisible_wrapper(x)) {
                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::GroupEnd));
    if top_marker {
        out.pop();
    }
    let last_eff = out.last().map(last_effective);
    let prev_group_end = top_marker || matches!(last_eff, Some(OutNode::GroupEnd));
    // 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,
        // A passed-through CSS `@import` and the remaining hoist markers (which a
        // module wrapper's last child can be) pack tight; only a group-end marker
        // forces the separator.
        Some(
            OutNode::Raw(_) | OutNode::MediaHoist | OutNode::AtRootHoist { .. } | OutNode::AtRootPackTight,
        ) => true,
        _ => 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) -> Cow<'_, str> {
    if name.contains('\\') {
        return Cow::Owned(decode_ident_escapes(name).replace('_', "-"));
    }
    // The common case is a name with no underscore: borrow it untouched
    // (this runs 4-6x per function call, so the no-alloc path matters).
    if name.contains('_') {
        Cow::Owned(name.replace('_', "-"))
    } else {
        Cow::Borrowed(name)
    }
}

/// 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,
    }
}

/// The dart-sass "isn't a valid CSS value." error message for a value that
/// cannot be serialized to CSS, or `None` if it can. Mirrors the
/// declaration-emit guard exactly: a MAP found anywhere (including nested in a
/// list) is rejected with its own serialization, and a TOP-LEVEL empty
/// unbracketed list (`()`) is rejected as `()`. A bracketed `[]`, and an empty
/// list merely nested inside a non-empty list, both serialize fine. Reused at
/// every other CSS-serialization site (unary `-`/`+`, the `+`/`-`/`/` string
/// joins, and `#{…}` interpolation) so they reject the same shapes dart does
/// instead of silently emitting bogus output.
pub(super) fn css_value_error_msg(v: &Value) -> Option<String> {
    if let Some(m) = find_map(v) {
        return Some(format!("{} isn't a valid CSS value.", m.to_css(false)));
    }
    if let Value::List(l) = v {
        if l.items.is_empty() && !l.bracketed {
            return Some("() isn't a valid CSS value.".to_string());
        }
    }
    None
}

/// Serialize a value for interpolation, erroring (like dart-sass) if it is a
/// map or empty list that cannot become CSS. Shared by every interpolation
/// context that turns a value into text (`@media`/`@supports` queries and
/// feature decls). The error carries no span — these template sites have no
/// per-piece source position — but matches dart's message and non-zero exit.
pub(super) fn interp_checked(v: &Value) -> Result<String, Error> {
    if let Some(msg) = css_value_error_msg(v) {
        return Err(Error::unpositioned(msg));
    }
    Ok(v.to_interp())
}

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())
}

/// 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>,
}

/// 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::MediaHoist => true,
        OutNode::AtRootHoist { target } => *target < 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: selectors.into_strings(),
                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)),
            // Raw passthroughs, blanks, and the control-only hoist markers carry
            // no rule-block item.
            OutNode::Raw(_)
            | OutNode::Blank
            | OutNode::GroupEnd
            | OutNode::MediaHoist
            | OutNode::AtRootHoist { .. }
            | OutNode::AtRootPackTight => {}
        }
    }
    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 \")\"."));
                    }
                }
                _ => {}
            }
        }
    }
    // Any pseudo-class/element must name an identifier: a bare or repeated colon
    // with no ident-start after it (`a::`, `a:::before`, `::before::`, `a:`) is
    // dart's `Expected identifier.`. Gated on a `:` being present.
    if sel.as_bytes().contains(&b':') {
        validate_pseudo_names(sel)?;
    }
    // Grammar-typed pseudo arguments — the An+B microsyntax of
    // `:nth-child`/`:nth-last-child` and the non-empty selector list of
    // `:not`/`:is`/`:where`/`:has`/… — are validated against dart's parser.
    // Gated on a parenthesized pseudo (a `:` somewhere before a `(`).
    if sel.as_bytes().contains(&b'(') && sel.as_bytes().contains(&b':') {
        crate::selector::validate_pseudo_args(sel).map_err(Error::unpositioned)?;
    }
    // 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(())
    }
}

/// Every pseudo-class/element must name an identifier: after its leading `:`
/// (or `::`), an identifier-start character is required. A bare or repeated
/// colon (`a::`, `a:::before`, `a:`, `::before::`) — including one nested in a
/// selector-argument pseudo (`:not(::)`) — is dart's `Expected identifier.`.
/// Colons inside `[...]` attribute selectors and string literals are exempt.
fn validate_pseudo_names(sel: &str) -> Result<(), Error> {
    let chars: Vec<char> = sel.chars().collect();
    let mut i = 0usize;
    while i < chars.len() {
        match chars[i] {
            '\\' => {
                i += 2;
            }
            '"' | '\'' => i = skip_string(&chars, i),
            '[' => i = matching_bracket(&chars, i) + 1,
            ':' => {
                i += 1;
                // A second colon makes a pseudo-element (`::before`).
                if chars.get(i) == Some(&':') {
                    i += 1;
                }
                // The name must begin with a CSS identifier-start character.
                if !pseudo_name_starts_at(&chars, i) {
                    return Err(Error::unpositioned("Expected identifier."));
                }
            }
            _ => i += 1,
        }
    }
    Ok(())
}

/// Whether `chars[i..]` begins a CSS identifier (the pseudo name after a colon):
/// a letter, `_`, escape, or non-ASCII char; or a `-` provided the NEXT
/// character is itself an identifier-start (`-foo`, `--foo`) — a lone `-`, a
/// `-` then a digit (`-9`), and a leading digit (`0`, `9x`) are not.
fn pseudo_name_starts_at(chars: &[char], i: usize) -> bool {
    let is_start = |c: char| c.is_ascii_alphabetic() || c == '_' || c == '\\' || (c as u32) >= 0x80;
    match chars.get(i).copied() {
        Some(c) if is_start(c) => true,
        Some('-') => matches!(chars.get(i + 1).copied(), Some(n) if is_start(n) || n == '-'),
        _ => false,
    }
}

/// 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.to_strings().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>>,
    order: &ExtendOrderCtx,
) {
    // 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();
    // dart builds ONE `ExtensionStore` per module scope, then extends each rule
    // against it incrementally. Build the scope-fixed extend plan ONCE here and
    // reuse it for every rule in this scope, rather than re-deriving the whole
    // transitive closure per rule (the old O(rules × extensions) blow-up).
    let plan = crate::selector::build_extend_plan(
        &visible,
        scope,
        if order.has_import_clones {
            std::collections::HashMap::new()
        } else {
            order.rank_for(scope)
        },
        order.has_import_clones,
    );
    rewrite_with_scopes(nodes, &plan, scope, all, origins, closures, order);
}

/// The walk shared by [`rewrite_nodes_scoped`]: rules use the current scope's
/// `plan` (the prebuilt extend closure); a nested [`OutNode::ModuleScope`]
/// re-enters with its own scope and its own plan.
/// The module-graph context for dart's store-merge ORDER: reverse load
/// edges (who loads whom) plus each origin's first registration index.
pub(crate) struct ExtendOrderCtx {
    /// loaded module -> loaders (direct downstream modules).
    pub rev_deps: HashMap<String, Vec<String>>,
    /// origin -> smallest extension registration index (first-load rank).
    pub first_reg: HashMap<String, usize>,
    /// Module-loading `@import`s (clone scopes) are in play: dart merges the
    /// cloned subtree's extension stores into the IMPORTING module's own,
    /// which the pure-`@use` store-merge order below cannot express — fall
    /// back to the legacy fold order for the whole compile.
    pub has_import_clones: bool,
}

impl ExtendOrderCtx {
    /// The per-origin rank in `scope`'s downstream store-merge flatten:
    /// DFS from `scope` over reverse edges, visiting each level's direct
    /// downstream modules in DESCENDING first-load order (a later-loaded
    /// sibling's store registers earlier into the upstream's list), own
    /// store before its absorbed downstreams (pre-order).
    fn rank_for(&self, scope: &str) -> std::collections::HashMap<String, usize> {
        let mut rank = std::collections::HashMap::new();
        let mut next = 0usize;
        let mut stack: Vec<String> = Vec::new();
        let push_children =
            |of: &str, stack: &mut Vec<String>, rank: &std::collections::HashMap<String, usize>| {
                let mut kids: Vec<&String> = self
                    .rev_deps
                    .get(of)
                    .map(|v| {
                        v.iter()
                            .filter(|k| !rank.contains_key(*k) && k.as_str() != scope)
                            .collect()
                    })
                    .unwrap_or_default();
                // Descending first-load; push reversed so the largest pops first.
                kids.sort_by_key(|k| self.first_reg.get(*k).copied().unwrap_or(usize::MAX));
                for k in kids {
                    stack.push(k.clone());
                }
            };
        push_children(scope, &mut stack, &rank);
        while let Some(m) = stack.pop() {
            if rank.contains_key(&m) {
                continue;
            }
            rank.insert(m.clone(), next);
            next += 1;
            push_children(&m, &mut stack, &rank);
        }
        rank
    }
}

fn rewrite_with_scopes(
    nodes: &mut Vec<OutNode>,
    plan: &crate::selector::ExtendPlan,
    scope: &str,
    all: &[crate::selector::Extension],
    origins: &[String],
    closures: &HashMap<String, std::collections::HashSet<String>>,
    order: &ExtendOrderCtx,
) {
    for node in nodes.iter_mut() {
        match node {
            OutNode::ModuleScope { key, nodes } => {
                let key = key.clone();
                rewrite_nodes_scoped(nodes, &key, all, origins, closures, order);
            }
            OutNode::AtRule { name, body, .. } if !is_keyframes_name(name) => {
                rewrite_with_scopes(body, plan, scope, all, origins, closures, order);
            }
            _ => {}
        }
    }
    rewrite_nodes(nodes, plan, scope);
}

fn rewrite_nodes(nodes: &mut Vec<OutNode>, plan: &crate::selector::ExtendPlan, 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). Post-eval,
            // group-end/pack-tight sentinels are inert (their eval-time
            // consumers have run), so a wrapper holding only markers — e.g. a
            // placeholder-only module whose rules were all dropped — counts
            // as empty too.
            OutNode::ModuleScope { nodes, .. } => {
                fn invisible(nodes: &[OutNode]) -> bool {
                    nodes.iter().all(|n| match n {
                        OutNode::Blank | OutNode::GroupEnd | OutNode::AtRootPackTight => true,
                        OutNode::ModuleScope { nodes, .. } => invisible(nodes),
                        _ => false,
                    })
                }
                invisible(nodes)
            }
            OutNode::Rule {
                selectors,
                linebreaks,
                extend_base,
                ..
            } => {
                {
                    match extend_selector_list(selectors, linebreaks, plan, scope, *extend_base) {
                        // No change → skip the clone + write-back entirely.
                        SelectorRewrite::Unchanged => false,
                        SelectorRewrite::Changed(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
                        }
                        // Entirely placeholders → drop the rule.
                        SelectorRewrite::Drop => 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) {
                // Removing the PRECEDING blank shifts the yet-unexamined
                // successor down to `i - 1`; step back so it isn't skipped.
                nodes.remove(i - 1);
                i -= 1;
            }
        } 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.as_ref());
        }
        if let Some(h) = &hide {
            return !h.contains(n.as_ref());
        }
        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) -> Cow<'_, str> {
    // `-`/`_` are interchangeable; borrow when there is nothing to replace
    // (the overwhelmingly common case).
    if name.contains('_') {
        Cow::Owned(name.replace('_', "-"))
    } else {
        Cow::Borrowed(name)
    }
}

/// 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_ref(), "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).into_owned()),
                (crate::ast::ForwardMember::Name(n), false) => Some(normalize_var_name(n).into_owned()),
                _ => 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())
}

/// The outcome of extending one rule's selector list.
enum SelectorRewrite {
    /// The selector needs no change — leave the rule's selectors in place
    /// (no clone, no write-back). The common case on extend-free stylesheets.
    Unchanged,
    /// The selector was extended/placeholder-stripped — replace it.
    Changed(RuleSelectors, Vec<bool>),
    /// Every complex selector is still a placeholder after extension, so the
    /// rule emits no CSS — drop it.
    Drop,
}

/// Compute the extended selector list for a rule. [`SelectorRewrite::Drop`]
/// when, after extension, every complex selector still contains a placeholder
/// (the rule emits no CSS); [`SelectorRewrite::Unchanged`] when the selector
/// needs no change (so the caller skips the clone + write-back entirely).
///
/// Phase 1d: the engine works on the typed [`crate::selector::Complex`] model
/// and the result is carried as [`RuleSelectors::Parsed`] — emit renders it
/// directly, so there is no `join(", ")` + `parse_list` round trip back to
/// strings. The fast path (no `@extend` and no placeholder) and the
/// unparseable fallback keep the rule's original [`RuleSelectors::Raw`] strings
/// untouched, byte-for-byte.
fn extend_selector_list(
    selectors: &RuleSelectors,
    breaks: &[bool],
    plan: &crate::selector::ExtendPlan,
    scope: &str,
    extend_base: usize,
) -> SelectorRewrite {
    let has_placeholder = match selectors {
        RuleSelectors::Raw(v) => v.iter().any(|s| s.contains('%')),
        RuleSelectors::Parsed(v) => v.iter().any(crate::selector::complex_has_placeholder),
    };
    // 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 plan.is_empty() && !has_placeholder {
        return SelectorRewrite::Unchanged;
    }
    // Parse the rule's selectors into the typed model exactly once. A `Raw`
    // rule (the only shape an evaluated rule arrives in) is joined and parsed
    // here; a `Parsed` rule (a re-entered already-rewritten list, not produced
    // today) is borrowed directly.
    let parsed_owned;
    let parsed: &[crate::selector::Complex] = match selectors {
        RuleSelectors::Raw(v) => {
            let joined = v.join(", ");
            match crate::selector::parse_list(&joined) {
                Some(p) => {
                    parsed_owned = p;
                    &parsed_owned
                }
                // Unparseable selector: never lose it; leave untouched.
                None => return SelectorRewrite::Unchanged,
            }
        }
        RuleSelectors::Parsed(v) => v,
    };
    let result = crate::selector::extend_selectors(parsed, breaks, plan, scope, extend_base);
    if result.all_placeholders {
        return SelectorRewrite::Drop;
    }
    SelectorRewrite::Changed(RuleSelectors::Parsed(result.selectors.into()), 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.
/// Also derives each output complex's source line-break flag (dart carries
/// `lineBreak` on the ComplexSelector object): a part WITHOUT `&` keeps its
/// own flag OR'd with the joined parent's; a part WITH `&` drops its own flag
/// and takes the substituted parent's (dart rebuilds those complexes from a
/// `lineBreak: false` base); a k>=2 cartesian combo ORs its chosen parents'.
fn resolve_selectors_opt(
    sel: &str,
    parents: &[String],
    implicit_parent: bool,
    part_lbs: &[bool],
    parent_lbs: &[bool],
) -> Result<Vec<(String, bool)>, 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, bool)>| {
        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]);
            // A `&` nested in pseudo parens is NOT a cartesian position (the
            // split counts depth-0 refs only) but still substitutes — with
            // the whole parent list, like any pseudo-`&`
            // (quasar: `&-container:not(&--mini-animate) &--mini`).
            let s = substitute_pseudo_refs(&s).unwrap_or(s);
            // The combo's flag ORs its chosen parents' flags (mastodon's
            // adjacent-state selectors break per combo, not per template).
            let flag = idx.iter().any(|&pi| parent_lbs.get(pi).copied().unwrap_or(false));
            result.push((normalize_selector(&s), flag));
            // 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<(String, bool)> = 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 (pi, part) in parts.iter().enumerate() {
            result.push((
                normalize_selector(part),
                part_lbs.get(pi).copied().unwrap_or(false),
            ));
        }
    } 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_i, part) in parts.iter().enumerate() {
            if let Some(s) = substitute_pseudo_refs(part) {
                result.push((normalize_selector(&s), false));
            } 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 (pi, parent) in parents.iter().enumerate() {
                    check_compound_parent(part, parent)?;
                    result.push((
                        normalize_selector(&replace_parent_refs(part, parent)),
                        parent_lbs.get(pi).copied().unwrap_or(false),
                    ));
                }
            } else {
                result.push((
                    normalize_selector(part),
                    part_lbs.get(part_i).copied().unwrap_or(false),
                ));
            }
        }
    } else {
        // dart `resolveParentSelectors`: each part resolves to its own ROW of
        // complexes, and the final list is `flattenVertically(rows)` —
        // column-major across the parts. For `&`-less and single-`&` parts
        // (rows of exactly `parents.len()`) that is the familiar parent-major
        // order; a part with k >= 2 top-level refs contributes a row of
        // `parents.len()^k` combos, interleaved column-by-column with its
        // sibling parts (mastodon's `&:hover + &:is(...)` lists).
        let mut rows: Vec<Vec<(String, bool)>> = Vec::with_capacity(parts.len());
        for (part_i, part) in parts.iter().enumerate() {
            // A pseudo-only `&` part resolves ONCE (whole parent list in
            // place): a single-entry row.
            if let Some(s) = substitute_pseudo_refs(part) {
                rows.push(vec![(normalize_selector(&s), false)]);
                continue;
            }
            if let Some(segments) = split_parent_refs(part) {
                for parent in parents {
                    check_compound_parent(part, parent)?;
                }
                let mut row = Vec::new();
                expand_cartesian(&segments, &mut row);
                rows.push(row);
                continue;
            }
            let has_ref = part_has_parent_ref(part);
            let mut row = Vec::with_capacity(parents.len());
            for (pi, parent) in parents.iter().enumerate() {
                let parent_lb = parent_lbs.get(pi).copied().unwrap_or(false);
                let (combined, flag) = if has_ref {
                    check_compound_parent(part, parent)?;
                    // A `&` part drops its own source flag (dart rebuilds the
                    // complex from a lineBreak:false base) and takes the
                    // substituted parent's.
                    (replace_parent_refs(part, parent), parent_lb)
                } else {
                    (
                        format!("{parent} {part}"),
                        part_lbs.get(part_i).copied().unwrap_or(false) || parent_lb,
                    )
                };
                row.push((normalize_selector(&combined), flag));
            }
            rows.push(row);
        }
        let longest = rows.iter().map(|r| r.len()).max().unwrap_or(0);
        for j in 0..longest {
            for row in &rows {
                if let Some(entry) = row.get(j) {
                    result.push(entry.clone());
                }
            }
        }
    }
    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.
/// `s.trim().to_string()` without the allocation when `s` has no surrounding
/// whitespace — the common case for an evaluated property name. Reuses the
/// owned buffer in place (`trim` removed nothing → same length) instead of
/// copying the bytes into a fresh `String`.
fn trim_owned(s: String) -> String {
    if s.trim().len() == s.len() {
        s
    } else {
        s.trim().to_string()
    }
}

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  {`).
    // Inside pseudo parens, a run that follows a comma and contains a
    // newline collapses to '\n' instead: dart's arg complexes carry their
    // source lineBreak and the serializer honors it anywhere
    // (`:is(a,\n[type=color])` keeps its lines — quasar's field selectors).
    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 paren = 0i32;
    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() {
            let mut has_nl = c == '\n';
            ci += 1;
            while ci < cs.len() && cs[ci].is_whitespace() {
                has_nl |= cs[ci] == '\n';
                ci += 1;
            }
            if !prev_space {
                if paren > 0 && has_nl && collapsed.ends_with(',') {
                    collapsed.push('\n');
                } else {
                    collapsed.push(' ');
                }
            }
            prev_space = true;
            continue;
        }
        match c {
            '(' => paren += 1,
            ')' => paren -= 1,
            _ => {}
        }
        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 -----------------------------------------------------

/// Append an `and`/`or` media-query separator. dart-sass's compressed media
/// serializer omits the space BEFORE the keyword when the text so far ends in
/// `)` (`(a)and (b)`) but keeps it after an identifier (`screen and (a)`); the
/// trailing space is always present. Expanded always emits ` and `/` or `.
/// (`@supports` conditions are serialized elsewhere and are NOT tightened.)
fn push_media_sep(s: &mut String, is_and: bool, compressed: bool) {
    let word = if is_and { "and" } else { "or" };
    if compressed && s.ends_with(')') {
        s.push_str(word);
    } else {
        s.push(' ');
        s.push_str(word);
    }
    s.push(' ');
}

impl ResolvedQuery {
    /// Serialize one query (dart-sass `CssMediaQuery.toString`). `compressed`
    /// tightens the `and`/`or` separators per dart's compressed serializer.
    fn render(&self, compressed: bool) -> 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() {
                // A media type is an identifier, so the space is kept
                // (`screen and (a)`) — the `ends_with(')')` rule yields that.
                push_media_sep(&mut s, true, compressed);
            }
        }
        for (i, c) in self.conditions.iter().enumerate() {
            if i > 0 {
                push_media_sep(&mut s, self.conjunction_and, compressed);
            }
            s.push_str(c);
        }
        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], compressed: bool) -> String {
    // Compressed drops the space after the comma between queries (`(a),(b)`).
    let sep = if compressed { "," } else { ", " };
    queries
        .iter()
        .map(|q| q.render(compressed))
        .collect::<Vec<_>>()
        .join(sep)
}

/// 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),
    }
}