accent_sass_compiler 0.16.0

Internal implementation of the accent-sass compiler
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
use std::io::Write;

use codemap::{CodeMap, Span};

use crate::{
    Options,
    ast::Mixin,
    ast::{CssStmt, MediaQuery, Style, SupportsRule},
    color::{Color, ColorFormat, ColorSpace, NAMED_COLORS},
    common::{BinaryOp, Brackets, ListSeparator, QuoteKind},
    error::SassResult,
    selector::{
        Combinator, ComplexSelector, ComplexSelectorComponent, CompoundSelector, Namespace, Pseudo,
        SelectorList, SimpleSelector,
    },
    unit::Unit,
    utils::hex_char_for,
    value::{
        ArgList, CalculationArg, CalculationName, Number, SassCalculation, SassFunction, SassMap,
        SassNumber, Value, fuzzy_equals, fuzzy_greater_than_or_equals, fuzzy_less_than,
        fuzzy_less_than_or_equals,
    },
};

/// Whether `c` is in a Unicode Private Use Area.
///
/// The Basic Multilingual Plane's area is `U+E000..=U+F8FF`; the two
/// supplementary areas together cover `U+F0000..=U+10FFFF`. dart-sass tests
/// the same two ranges, though it phrases the second as the UTF-16 high
/// surrogates `0xDB80..=0xDBFF` that encode it.
///
/// See <https://en.wikipedia.org/wiki/Private_Use_Areas>.
fn is_private_use(c: char) -> bool {
    matches!(c as u32, 0xE000..=0xF8FF | 0xF0000..=0x10FFFF)
}

/// Appends `c`'s UTF-8 encoding to `buffer`.
fn push_char(buffer: &mut Vec<u8>, c: char) {
    buffer.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes());
}

/// Writes `c` to `buffer` as a hexadecimal escape sequence.
///
/// `next` is the character that follows in the string being written. CSS ends
/// an escape at the first character that cannot continue it, so a following
/// hex digit, space or tab needs a space of its own to keep it out of the
/// escape.
fn write_escape(buffer: &mut Vec<u8>, c: char, next: Option<char>) {
    buffer.push(b'\\');

    let mut code_point = c as u32;
    let mut digits = [0u8; 6];
    let mut len = 0;
    while {
        digits[len] = hex_char_for(code_point & 0xF) as u8;
        len += 1;
        code_point >>= 4;
        code_point > 0
    } {}
    for i in (0..len).rev() {
        buffer.push(digits[i]);
    }

    if matches!(next, Some(next) if next.is_ascii_hexdigit() || next == ' ' || next == '\t') {
        buffer.push(b' ');
    }
}

pub(crate) fn serialize_selector_list(
    list: &SelectorList,
    options: &Options,
    span: Span,
) -> String {
    let map = CodeMap::new();
    let mut serializer = Serializer::new(options, &map, false, span);

    serializer.write_selector_list(list);

    serializer.finish_for_expr()
}

pub(crate) fn serialize_calculation_arg(
    arg: &CalculationArg,
    options: &Options,
    span: Span,
) -> SassResult<String> {
    let map = CodeMap::new();
    let mut serializer = Serializer::new(options, &map, false, span);

    serializer.write_calculation_arg(arg)?;

    Ok(serializer.finish_for_expr())
}

pub(crate) fn serialize_value(val: &Value, options: &Options, span: Span) -> SassResult<String> {
    let map = CodeMap::new();
    let mut serializer = Serializer::new(options, &map, false, span);

    serializer.visit_value(val, span)?;

    Ok(serializer.finish_for_expr())
}

pub(crate) fn inspect_value(val: &Value, options: &Options, span: Span) -> SassResult<String> {
    let map = CodeMap::new();
    let mut serializer = Serializer::new(options, &map, true, span);

    serializer.visit_value(val, span)?;

    Ok(serializer.finish_for_expr())
}

pub(crate) fn inspect_float(number: f64, options: &Options, span: Span) -> String {
    let map = CodeMap::new();
    let mut serializer = Serializer::new(options, &map, true, span);

    serializer.write_float(number);

    serializer.finish_for_expr()
}

pub(crate) fn inspect_map(map: &SassMap, options: &Options, span: Span) -> SassResult<String> {
    let code_map = CodeMap::new();
    let mut serializer = Serializer::new(options, &code_map, true, span);

    serializer.visit_map(map, span)?;

    Ok(serializer.finish_for_expr())
}

pub(crate) fn inspect_function_ref(
    func: &SassFunction,
    options: &Options,
    span: Span,
) -> SassResult<String> {
    let code_map = CodeMap::new();
    let mut serializer = Serializer::new(options, &code_map, true, span);

    serializer.visit_function_ref(func, span)?;

    Ok(serializer.finish_for_expr())
}

/// Serializes a first-class mixin the way `meta.inspect` does.
pub(crate) fn inspect_mixin_ref(
    mixin: &Mixin,
    options: &Options,
    span: Span,
) -> SassResult<String> {
    let code_map = CodeMap::new();
    let mut serializer = Serializer::new(options, &code_map, true, span);

    serializer.visit_mixin_ref(mixin, span)?;

    Ok(serializer.finish_for_expr())
}

pub(crate) fn inspect_number(
    number: &SassNumber,
    options: &Options,
    span: Span,
) -> SassResult<String> {
    let map = CodeMap::new();
    let mut serializer = Serializer::new(options, &map, true, span);

    serializer.visit_number(number)?;

    Ok(serializer.finish_for_expr())
}

pub(crate) struct Serializer<'a> {
    indentation: usize,
    options: &'a Options<'a>,
    inspect: bool,
    indent_width: usize,
    // todo: use this field
    _quote: bool,
    buffer: Vec<u8>,
    map: &'a CodeMap,
    // todo: use this field
    _span: Span,
    /// Set while serializing a comment that trails a statement on the same
    /// output line, so no indentation is written before it.
    inline_comment: bool,
}

impl<'a> Serializer<'a> {
    pub fn new(options: &'a Options<'a>, map: &'a CodeMap, inspect: bool, span: Span) -> Self {
        Self {
            inspect,
            _quote: true,
            indentation: 0,
            indent_width: 2,
            options,
            buffer: Vec::new(),
            map,
            _span: span,
            inline_comment: false,
        }
    }

    fn omit_spaces_around_complex_component(&self, component: &ComplexSelectorComponent) -> bool {
        self.options.is_compressed()
            && matches!(component, ComplexSelectorComponent::Combinator(..))
    }

    fn write_pseudo_selector(&mut self, pseudo: &Pseudo) {
        if let Some(sel) = &pseudo.selector
            && pseudo.name == "not"
            && sel.is_invisible()
        {
            return;
        }

        self.buffer.push(b':');

        if !pseudo.is_syntactic_class {
            self.buffer.push(b':');
        }

        self.buffer.extend_from_slice(pseudo.name.as_bytes());

        if pseudo.argument.is_none() && pseudo.selector.is_none() {
            return;
        }

        self.buffer.push(b'(');
        if let Some(arg) = &pseudo.argument {
            self.buffer.extend_from_slice(arg.as_bytes());
            if pseudo.selector.is_some() {
                self.buffer.push(b' ');
            }
        }

        if let Some(sel) = &pseudo.selector {
            self.write_selector_list(sel);
        }

        self.buffer.push(b')');
    }

    fn write_namespace(&mut self, namespace: &Namespace) {
        match namespace {
            Namespace::Empty => self.buffer.push(b'|'),
            Namespace::Asterisk => self.buffer.extend_from_slice(b"*|"),
            Namespace::Other(namespace) => {
                self.buffer.extend_from_slice(namespace.as_bytes());
                self.buffer.push(b'|');
            }
            Namespace::None => {}
        }
    }

    fn write_simple_selector(&mut self, simple: &SimpleSelector) {
        match simple {
            SimpleSelector::Id(name) => {
                self.buffer.push(b'#');
                self.buffer.extend_from_slice(name.as_bytes());
            }
            SimpleSelector::Class(name) => {
                self.buffer.push(b'.');
                self.buffer.extend_from_slice(name.as_bytes());
            }
            SimpleSelector::Placeholder(name) => {
                self.buffer.push(b'%');
                self.buffer.extend_from_slice(name.as_bytes());
            }
            SimpleSelector::Universal(namespace) => {
                self.write_namespace(namespace);
                self.buffer.push(b'*');
            }
            SimpleSelector::Pseudo(pseudo) => self.write_pseudo_selector(pseudo),
            SimpleSelector::Type(name) => {
                self.write_namespace(&name.namespace);
                self.buffer.extend_from_slice(name.ident.as_bytes());
            }
            SimpleSelector::Attribute(attr) => write!(&mut self.buffer, "{}", attr).unwrap(),
            // A parent selector normally resolves before serialization. It
            // survives only in plain CSS, where `&` is the CSS nesting selector
            // and is written out as it was read.
            SimpleSelector::Parent(suffix) => {
                self.buffer.push(b'&');
                if let Some(suffix) = suffix {
                    self.buffer.extend_from_slice(suffix.as_bytes());
                }
            }
        }
    }

    fn write_compound_selector(&mut self, compound: &CompoundSelector) {
        let mut did_write = false;
        for simple in &compound.components {
            if did_write {
                self.write_simple_selector(simple);
            } else {
                let len = self.buffer.len();
                self.write_simple_selector(simple);
                if self.buffer.len() != len {
                    did_write = true;
                }
            }
        }

        // If we emit an empty compound, it's because all of the components got
        // optimized out because they match all selectors, so we just emit the
        // universal selector.
        if !did_write {
            self.buffer.push(b'*');
        }
    }

    fn write_complex_selector_component(&mut self, component: &ComplexSelectorComponent) {
        match component {
            ComplexSelectorComponent::Combinator(Combinator::NextSibling) => self.buffer.push(b'+'),
            ComplexSelectorComponent::Combinator(Combinator::Child) => self.buffer.push(b'>'),
            ComplexSelectorComponent::Combinator(Combinator::FollowingSibling) => {
                self.buffer.push(b'~')
            }
            ComplexSelectorComponent::Compound(compound) => self.write_compound_selector(compound),
        }
    }

    fn write_complex_selector(&mut self, complex: &ComplexSelector) {
        let mut last_component = None;

        for component in &complex.components {
            if let Some(c) = last_component
                && !self.omit_spaces_around_complex_component(c)
                && !self.omit_spaces_around_complex_component(component)
            {
                self.buffer.push(b' ');
            }
            self.write_complex_selector_component(component);
            last_component = Some(component);
        }
    }

    fn write_selector_list(&mut self, list: &SelectorList) {
        let complexes = list.components.iter().filter(|c| !c.is_invisible());

        let mut first = true;

        for complex in complexes {
            if first {
                first = false;
            } else {
                self.buffer.push(b',');
                if complex.line_break {
                    self.write_newline();
                    // Continuation lines of a selector list are indented to
                    // the current level, matching Dart Sass.
                    self.write_indentation();
                } else {
                    self.write_optional_space();
                }
            }
            self.write_complex_selector(complex);
        }
    }

    fn write_newline(&mut self) {
        if !self.options.is_compressed() {
            self.buffer.push(b'\n');
        }
    }

    fn write_comma_separator(&mut self) {
        self.buffer.push(b',');
        self.write_optional_space();
    }

    fn write_calculation_name(&mut self, name: CalculationName) {
        self.buffer.extend_from_slice(name.as_str().as_bytes());
    }

    fn visit_calculation(&mut self, calculation: &SassCalculation) -> SassResult<()> {
        self.write_calculation_name(calculation.name);
        self.buffer.push(b'(');

        if let Some((last, slice)) = calculation.args.split_last() {
            for arg in slice {
                self.write_calculation_arg(arg)?;
                self.write_comma_separator();
            }

            self.write_calculation_arg(last)?;
        }

        self.buffer.push(b')');

        Ok(())
    }

    fn write_calculation_arg(&mut self, arg: &CalculationArg) -> SassResult<()> {
        match arg {
            // A number inside a calculation is written inline rather than as a
            // nested `calc()`: `calc(infinity * 1px)`, not
            // `calc(calc(infinity * 1px))`.
            CalculationArg::Number(num) => {
                let has_plain_css_form = num.num.0.is_finite() && !num.unit.is_complex();

                if num.as_slash.is_none() && !has_plain_css_form {
                    self.write_calculation_number_body(num)?;
                } else {
                    self.visit_number(num)?;
                }
            }
            CalculationArg::Space(args) => {
                for (idx, arg) in args.iter().enumerate() {
                    if idx > 0 {
                        self.buffer.push(b' ');
                    }

                    self.write_calculation_arg(arg)?;
                }
            }
            // The group carries its own parentheses, so an enclosing operator
            // adds none of its own: `calc((var(--c) 1) * 2)` keeps exactly the
            // pair the source wrote.
            CalculationArg::Paren(inner) => {
                self.buffer.push(b'(');
                self.write_calculation_arg(inner)?;
                self.buffer.push(b')');
            }
            CalculationArg::Calculation(calc) => {
                self.visit_calculation(calc)?;
            }
            CalculationArg::String(s) | CalculationArg::Interpolation(s) => {
                self.buffer.extend_from_slice(s.as_bytes());
            }
            CalculationArg::Operation { lhs, op, rhs } => {
                let paren_left = match &**lhs {
                    CalculationArg::Operation { op: op2, .. } => op2.precedence() < op.precedence(),
                    // Adjacency binds looser than any operator, so a
                    // space-separated operand always needs grouping:
                    // `calc((var(--c) 1) * 2)`.
                    CalculationArg::Space(..) => true,
                    _ => false,
                };

                if paren_left {
                    self.buffer.push(b'(');
                }

                self.write_calculation_arg(lhs)?;

                if paren_left {
                    self.buffer.push(b')');
                }

                let operator_whitespace =
                    !self.options.is_compressed() || matches!(op, BinaryOp::Plus | BinaryOp::Minus);

                if operator_whitespace {
                    self.buffer.push(b' ');
                }

                // todo: avoid allocation with `write_binary_operator` method
                self.buffer.extend_from_slice(op.to_string().as_bytes());

                if operator_whitespace {
                    self.buffer.push(b' ');
                }

                let paren_right = match &**rhs {
                    CalculationArg::Operation { op: op2, .. } => {
                        CalculationArg::parenthesize_calculation_rhs(*op, *op2)
                    }
                    // A number written with unit factors behaves like a
                    // multiplication for precedence: `calc(a / (infinity * 1px))`.
                    CalculationArg::Number(num)
                        if num.as_slash.is_none() && Self::number_has_calculation_factors(num) =>
                    {
                        CalculationArg::parenthesize_calculation_rhs(*op, BinaryOp::Mul)
                    }
                    CalculationArg::Space(..) => true,
                    _ => false,
                };

                if paren_right {
                    self.buffer.push(b'(');
                }

                self.write_calculation_arg(rhs)?;

                if paren_right {
                    self.buffer.push(b')');
                }
            }
        }

        Ok(())
    }

    /// Dart Sass's `_asInt`: the channel as a whole number, or `None`. The
    /// check is exact outside inspect mode, so a channel with float noise
    /// (`204.99999999999994`) makes the whole color print as percentages;
    /// in inspect mode the check is fuzzy.
    fn as_int(&self, channel: f64) -> Option<f64> {
        let rounded = channel.round();
        let is_int = if self.inspect {
            fuzzy_equals(channel, rounded)
        } else {
            channel == rounded
        };
        if is_int { Some(rounded) } else { None }
    }

    /// Writes the three channels of an rgb-space color as comma-separated
    /// integers, or writes nothing and returns false when one of them is
    /// not a whole number.
    fn try_integer_rgb_channels(&mut self, rgb: &Color) -> bool {
        let red = match self.as_int(rgb.channel0()) {
            Some(red) => red,
            None => return false,
        };
        let green = match self.as_int(rgb.channel1()) {
            Some(green) => green,
            None => return false,
        };
        let blue = match self.as_int(rgb.channel2()) {
            Some(blue) => blue,
            None => return false,
        };

        self.write_float(red);
        self.write_comma_separator();
        self.write_float(green);
        self.write_comma_separator();
        self.write_float(blue);
        true
    }

    /// Writes a legacy color in the `rgb()`/`rgba()` syntax. Non-integral
    /// channels are written as percentages of 255, as Dart Sass does.
    fn write_rgb(&mut self, color: &Color) {
        let opaque = fuzzy_equals(color.alpha(), 1.0);
        let rgb = color.to_space(ColorSpace::Rgb, true);

        if opaque {
            self.buffer.extend_from_slice(b"rgb(");
        } else {
            self.buffer.extend_from_slice(b"rgba(");
        }

        if !self.try_integer_rgb_channels(&rgb) {
            self.write_channel(Some(rgb.channel0() * 100.0 / 255.0), Some(Unit::Percent));
            self.write_comma_separator();
            self.write_channel(Some(rgb.channel1() * 100.0 / 255.0), Some(Unit::Percent));
            self.write_comma_separator();
            self.write_channel(Some(rgb.channel2() * 100.0 / 255.0), Some(Unit::Percent));
        }

        if !opaque {
            self.write_comma_separator();
            self.write_float(color.alpha());
        }

        self.buffer.push(b')');
    }

    /// Writes one color channel the way Dart Sass's `_writeChannel` does:
    /// `none` for a missing channel, a plain number with `unit` for a
    /// finite one, and a `calc(..)` for a non-finite one
    /// (`calc(NaN * 1%)`).
    fn write_channel(&mut self, channel: Option<f64>, unit: Option<Unit>) {
        let value = match channel {
            Some(value) => value,
            None => {
                self.buffer.extend_from_slice(b"none");
                return;
            }
        };

        if value.is_finite() {
            self.write_float(value);
            if let Some(unit) = unit {
                let _ = write!(&mut self.buffer, "{}", unit);
            }
        } else {
            let number = SassNumber {
                num: Number(value),
                unit: unit.unwrap_or(Unit::None),
                as_slash: None,
            };
            // Writing a bare number never fails; the `Result` only exists
            // because the buffer implements `io::Write`.
            let _ = self.write_number_as_calculation(&number);
        }
    }

    /// Writes a legacy color in the `hsl()`/`hsla()` syntax, converting
    /// to hsl first. A missing hue reads as `0`.
    fn write_hsl(&mut self, color: &Color) {
        let opaque = fuzzy_equals(color.alpha(), 1.0);
        let hsl = color.to_space(ColorSpace::Hsl, true);

        if opaque {
            self.buffer.extend_from_slice(b"hsl(");
        } else {
            self.buffer.extend_from_slice(b"hsla(");
        }

        self.write_channel(Some(hsl.channel0()), None);
        self.write_comma_separator();
        self.write_channel(Some(hsl.channel1()), Some(Unit::Percent));
        self.write_comma_separator();
        self.write_channel(Some(hsl.channel2()), Some(Unit::Percent));

        if !opaque {
            self.write_comma_separator();
            self.write_float(color.alpha());
        }

        self.buffer.push(b')');
    }

    /// Writes an hwb color in the modern `hwb(H W% B% / A)` syntax. Dart
    /// Sass only uses this in inspect mode (`@debug`, `inspect()`).
    fn write_hwb(&mut self, color: &Color) {
        let hwb = color.to_space(ColorSpace::Hwb, true);

        self.buffer.extend_from_slice(b"hwb(");
        self.write_float(hwb.channel0());
        self.buffer.push(b' ');
        self.write_float(hwb.channel1());
        self.buffer.push(b'%');
        self.buffer.push(b' ');
        self.write_float(hwb.channel2());
        self.buffer.push(b'%');

        if !fuzzy_equals(color.alpha(), 1.0) {
            self.buffer.extend_from_slice(b" / ");
            self.write_float(color.alpha());
        }

        self.buffer.push(b')');
    }

    /// Writes ` / A` when the color is not opaque (`/A` when compressed),
    /// with `none` for a missing alpha.
    fn write_slash_alpha(&mut self, color: &Color) {
        if fuzzy_equals(color.alpha(), 1.0) {
            return;
        }
        self.write_optional_space();
        self.buffer.push(b'/');
        self.write_optional_space();
        self.write_channel(color.alpha_or_none(), None);
    }

    /// Writes a color in the `color(<space> c0 c1 c2 / A)` syntax, which
    /// is how every space without a dedicated CSS function serializes.
    fn write_color_function(&mut self, color: &Color) {
        self.buffer.extend_from_slice(b"color(");
        self.buffer
            .extend_from_slice(color.space().name().as_bytes());
        for channel in color.channels_or_none() {
            self.buffer.push(b' ');
            self.write_channel(channel, None);
        }
        self.write_slash_alpha(color);
        self.buffer.push(b')');
    }

    fn write_hex_component(&mut self, channel: u32) {
        debug_assert!(channel < 256);

        self.buffer.push(hex_char_for(channel >> 4) as u8);
        self.buffer.push(hex_char_for(channel & 0xF) as u8);
    }

    fn is_symmetrical_hex(channel: u32) -> bool {
        channel & 0xF == channel >> 4
    }

    fn can_use_short_hex(red: u32, green: u32, blue: u32) -> bool {
        Self::is_symmetrical_hex(red)
            && Self::is_symmetrical_hex(green)
            && Self::is_symmetrical_hex(blue)
    }

    /// Whether every channel of an rgb-space color is a whole number
    /// within `0..=255`, so the color can be written as a hex code (Dart
    /// Sass's `_canUseHex`).
    fn can_use_hex(rgb: &Color) -> bool {
        rgb.channels().iter().all(|&channel| {
            fuzzy_equals(channel, channel.round())
                && fuzzy_greater_than_or_equals(channel, 0.0)
                && fuzzy_less_than(channel, 256.0)
        })
    }

    /// The rounded channels of an rgb-space color that can be written as
    /// hex.
    fn hex_channels(rgb: &Color) -> (u32, u32, u32) {
        let [red, green, blue] = rgb.channels();
        (
            red.round() as u32,
            green.round() as u32,
            blue.round() as u32,
        )
    }

    /// The color's name, when an opaque rgb-space color matches one.
    fn color_name(rgb: &Color) -> Option<&'static str> {
        if !Self::can_use_hex(rgb) {
            return None;
        }
        let (red, green, blue) = Self::hex_channels(rgb);
        NAMED_COLORS
            .get_by_rgba([red as u8, green as u8, blue as u8])
            .copied()
    }

    /// Writes an opaque rgb-space color as whichever of its name, short
    /// hex, or long hex is shortest, or writes nothing and returns false
    /// when it cannot be written as hex.
    fn try_hex_or_named_rgb(&mut self, rgb: &Color) -> bool {
        if !Self::can_use_hex(rgb) {
            return false;
        }

        let (red, green, blue) = Self::hex_channels(rgb);
        let short_hex = Self::can_use_short_hex(red, green, blue);
        let max_name_length = if short_hex { 4 } else { 7 };

        if let Some(name) = Self::color_name(rgb).filter(|name| name.len() <= max_name_length) {
            self.buffer.extend_from_slice(name.as_bytes());
        } else if short_hex {
            self.buffer.push(b'#');
            self.buffer.push(hex_char_for(red & 0xF) as u8);
            self.buffer.push(hex_char_for(green & 0xF) as u8);
            self.buffer.push(hex_char_for(blue & 0xF) as u8);
        } else {
            self.buffer.push(b'#');
            self.write_hex_component(red);
            self.write_hex_component(green);
            self.write_hex_component(blue);
        }
        true
    }

    /// Writes a legacy color with no missing channels, choosing the
    /// representation the way Dart Sass's `_writeLegacyColor` does:
    ///
    /// 1. an out-of-gamut color can only be represented exactly in hsl;
    /// 2. compressed output takes the shortest of hex, name, rgb, or hsl;
    /// 3. an hsl-space color always keeps hsl form;
    /// 4. a color written as `rgb()`, a hex code, or a name keeps that form;
    /// 5. otherwise an opaque whole-number color becomes a name or hex code,
    ///    and anything else is `rgb()`, or `hsl()` for an hwb-space color.
    fn write_legacy_color(&mut self, color: &Color) {
        let opaque = fuzzy_equals(color.alpha(), 1.0);

        if !color.is_in_gamut() && !self.inspect {
            self.write_hsl(color);
            return;
        }

        if self.options.is_compressed() {
            let rgb = color.to_space(ColorSpace::Rgb, true);
            if opaque && self.try_hex_or_named_rgb(&rgb) {
                return;
            }

            // Emit whichever of rgb and hsl is shorter, computing hsl from
            // the rgb channels as Dart Sass does. The two extra characters
            // account for the `%` signs on saturation and lightness.
            let start = self.buffer.len();
            self.write_rgb(&rgb);
            let rgb_string = self.buffer.split_off(start);
            self.write_hsl(&rgb.to_space(ColorSpace::Hsl, true));
            let hsl_string = self.buffer.split_off(start);
            if rgb_string.len() <= hsl_string.len() + 2 {
                self.buffer.extend_from_slice(&rgb_string);
            } else {
                self.buffer.extend_from_slice(&hsl_string);
            }
            return;
        }

        if color.space() == ColorSpace::Hsl {
            self.write_hsl(color);
            return;
        } else if self.inspect && color.space() == ColorSpace::Hwb {
            self.write_hwb(color);
            return;
        }

        match &color.format {
            ColorFormat::Rgb => {
                self.write_rgb(color);
                return;
            }
            ColorFormat::Literal(text) => {
                self.buffer.extend_from_slice(text.as_bytes());
                return;
            }
            ColorFormat::Infer => {}
        }

        // Always emit generated transparent colors in rgba format. This works
        // around an IE bug. See sass/sass#1782.
        if opaque {
            let rgb = color.to_space(ColorSpace::Rgb, true);
            if let Some(name) = Self::color_name(&rgb) {
                self.buffer.extend_from_slice(name.as_bytes());
                return;
            }

            if Self::can_use_hex(&rgb) {
                let (red, green, blue) = Self::hex_channels(&rgb);
                self.buffer.push(b'#');
                self.write_hex_component(red);
                self.write_hex_component(green);
                self.write_hex_component(blue);
                return;
            }
        }

        // An hwb color that can't be written as hex is written as hsl
        // rather than rgb, since that more clearly captures the author's
        // intent.
        if color.space() == ColorSpace::Hwb {
            self.write_hsl(color);
        } else {
            self.write_rgb(color);
        }
    }

    /// Writes a color the way Dart Sass's `visitColor` does. A legacy color
    /// with no missing channels takes the legacy syntax; anything else uses
    /// the CSS Color 4 syntax of its space, with `none` for missing
    /// channels. A lab-family color whose lightness is out of range (or
    /// whose chroma is negative) has no direct CSS form, so it is written
    /// as a `color-mix()` from its xyz value, or with a relative `from`
    /// prefix when it also has missing channels.
    pub fn visit_color(&mut self, color: &Color) {
        let space = color.space();
        let compressed = self.options.is_compressed();
        let [channel0, channel1, channel2] = color.channels_or_none();
        let missing0 = channel0.is_none();
        let missing1 = channel1.is_none();
        let missing2 = channel2.is_none();
        let fuzzy_in_range = |number: f64, min: f64, max: f64| {
            fuzzy_greater_than_or_equals(number, min) && fuzzy_less_than_or_equals(number, max)
        };

        match space {
            ColorSpace::Rgb | ColorSpace::Hsl | ColorSpace::Hwb if !color.has_missing_channel() => {
                self.write_legacy_color(color);
            }
            ColorSpace::Rgb => {
                self.buffer.extend_from_slice(b"rgb(");
                self.write_channel(channel0, None);
                self.buffer.push(b' ');
                self.write_channel(channel1, None);
                self.buffer.push(b' ');
                self.write_channel(channel2, None);
                self.write_slash_alpha(color);
                self.buffer.push(b')');
            }
            ColorSpace::Hsl | ColorSpace::Hwb => {
                self.buffer.extend_from_slice(space.name().as_bytes());
                self.buffer.push(b'(');
                self.write_channel(channel0, if compressed { None } else { Some(Unit::Deg) });
                self.buffer.push(b' ');
                self.write_channel(channel1, Some(Unit::Percent));
                self.buffer.push(b' ');
                self.write_channel(channel2, Some(Unit::Percent));
                self.write_slash_alpha(color);
                self.buffer.push(b')');
            }
            ColorSpace::Lab | ColorSpace::Lch | ColorSpace::Oklab | ColorSpace::Oklch => {
                let polar = space.is_polar();
                let lightness_max = match space {
                    ColorSpace::Lab | ColorSpace::Lch => 100.0,
                    _ => 1.0,
                };
                let lightness_out_of_range = !fuzzy_in_range(color.channel0(), 0.0, lightness_max);
                let negative_chroma = polar && fuzzy_less_than(color.channel1(), 0.0);

                if !self.inspect
                    && ((lightness_out_of_range && !missing1 && !missing2)
                        || (negative_chroma && !missing0 && !missing1))
                {
                    self.buffer.extend_from_slice(b"color-mix(in ");
                    self.buffer.extend_from_slice(space.name().as_bytes());
                    self.write_comma_separator();
                    self.write_color_function(&color.to_space(ColorSpace::XyzD65, true));
                    self.write_optional_space();
                    self.buffer.extend_from_slice(b"100%");
                    self.write_comma_separator();
                    self.buffer
                        .extend_from_slice(if compressed { b"red" } else { b"black" });
                    self.buffer.push(b')');
                    return;
                }

                self.buffer.extend_from_slice(space.name().as_bytes());
                self.buffer.push(b'(');

                // Dart Sass checks the lightness against `0..100` here for
                // every lab-family space, oklab and oklch included.
                if !self.inspect
                    && (!fuzzy_in_range(color.channel0(), 0.0, 100.0) || negative_chroma)
                {
                    self.buffer.extend_from_slice(b"from ");
                    self.buffer
                        .extend_from_slice(if compressed { b"red" } else { b"black" });
                    self.buffer.push(b' ');
                }

                if !compressed && !missing0 {
                    self.write_float(color.channel0() * 100.0 / lightness_max);
                    self.buffer.push(b'%');
                } else {
                    self.write_channel(channel0, None);
                }
                self.buffer.push(b' ');
                self.write_channel(channel1, None);
                self.buffer.push(b' ');
                self.write_channel(
                    channel2,
                    if polar && !compressed {
                        Some(Unit::Deg)
                    } else {
                        None
                    },
                );
                self.write_slash_alpha(color);
                self.buffer.push(b')');
            }
            _ => self.write_color_function(color),
        }
    }

    fn write_media_query(&mut self, query: &MediaQuery) {
        if let Some(modifier) = &query.modifier {
            self.buffer.extend_from_slice(modifier.as_bytes());
            self.buffer.push(b' ');
        }

        if let Some(media_type) = &query.media_type {
            self.buffer.extend_from_slice(media_type.as_bytes());

            if !query.conditions.is_empty() {
                self.buffer.extend_from_slice(b" and ");
            }
        }

        if query.conditions.len() == 1 && query.conditions.first().unwrap().starts_with("(not ") {
            self.buffer.extend_from_slice(b"not ");
            let condition = query.conditions.first().unwrap();
            // Slicing the `str` and then taking its bytes, rather than slicing
            // `as_bytes()` as clippy::sliced_string_as_bytes suggests. The two
            // differ on malformed input: the str slice panics on a non-UTF-8
            // boundary, while the byte slice would push invalid UTF-8 into the
            // output buffer and corrupt the stylesheet silently. The bounds
            // check the prefix guard above already proves is worth keeping.
            #[allow(clippy::sliced_string_as_bytes)]
            let inner = condition["(not ".len()..condition.len() - 1].as_bytes();
            self.buffer.extend_from_slice(inner);
        } else {
            let operator = if query.conjunction { " and " } else { " or " };
            self.buffer
                .extend_from_slice(query.conditions.join(operator).as_bytes());
        }
    }

    pub fn visit_number(&mut self, number: &SassNumber) -> SassResult<()> {
        if let Some(as_slash) = &number.as_slash {
            self.visit_number(&as_slash.0)?;
            self.buffer.push(b'/');
            self.visit_number(&as_slash.1)?;
            return Ok(());
        }

        // A number that has no plain-CSS representation -- non-finite, or
        // carrying complex units -- is written as a `calc()` expression, which
        // is what Dart Sass emits and, unlike a bare `NaN` or `1px/em`, is
        // valid CSS.
        if !number.num.0.is_finite() || number.unit.is_complex() {
            return self.write_number_as_calculation(number);
        }

        self.write_float(number.num.0);
        write!(&mut self.buffer, "{}", number.unit)?;

        Ok(())
    }

    /// Writes a number as a `calc()` expression, mirroring Dart Sass's
    /// `_writeCalculationValue`: a non-finite value becomes the `infinity`,
    /// `-infinity`, or `NaN` keyword with every unit written as a factor
    /// (`calc(infinity * 1px)`), while a finite value keeps its first
    /// numerator unit attached (`calc(1px / 1em)`).
    fn write_number_as_calculation(&mut self, number: &SassNumber) -> SassResult<()> {
        self.buffer.extend_from_slice(b"calc(");
        self.write_calculation_number_body(number)?;
        self.buffer.push(b')');

        Ok(())
    }

    /// Whether [`Serializer::write_calculation_number_body`] writes more than a
    /// single term for this number, which decides whether it needs parentheses
    /// in an enclosing calculation operation.
    fn number_has_calculation_factors(number: &SassNumber) -> bool {
        if !number.num.0.is_finite() {
            return number.unit != Unit::None;
        }

        number.unit.is_complex()
    }

    /// Writes the body of a number's `calc()` form -- everything between the
    /// parentheses -- so that a number appearing inside a larger calculation is
    /// inlined (`calc(1% + infinity * 1px)`) instead of nested.
    fn write_calculation_number_body(&mut self, number: &SassNumber) -> SassResult<()> {
        let (numer, denom) = number.unit.clone().numer_and_denom();
        let value = number.num.0;
        let mut factors: &[Unit] = &numer;

        if value.is_finite() {
            self.write_float(value);
            if let Some((first, rest)) = numer.split_first() {
                write!(&mut self.buffer, "{}", first)?;
                factors = rest;
            }
        } else if value.is_nan() {
            self.buffer.extend_from_slice(b"NaN");
        } else if value.is_sign_negative() {
            self.buffer.extend_from_slice(b"-infinity");
        } else {
            self.buffer.extend_from_slice(b"infinity");
        }

        for unit in factors {
            self.write_optional_space();
            self.buffer.push(b'*');
            self.write_optional_space();
            write!(&mut self.buffer, "1{}", unit)?;
        }

        for unit in &denom {
            self.write_optional_space();
            self.buffer.push(b'/');
            self.write_optional_space();
            write!(&mut self.buffer, "1{}", unit)?;
        }

        Ok(())
    }

    /// Writes a number the way Dart Sass's `_writeNumber` does: a whole
    /// number as an integer, a short decimal as-is, and a longer one
    /// rounded to ten decimal places by decimal digit. Compressed output
    /// drops the zero before the decimal point (`.5`), except on a short
    /// negative number, which Dart Sass leaves alone (`-0.5`).
    ///
    /// Exact negative zero is written as `-0`, as dart-sass does from 1.104.0
    /// on, so it keeps its sign when used in a CSS calculation. A value that
    /// merely rounds to zero, such as `-0.00000000001`, is still written `0`.
    fn write_float(&mut self, float: f64) {
        if float.is_infinite() && float.is_sign_negative() {
            self.buffer.extend_from_slice(b"-Infinity");
            return;
        } else if float.is_infinite() {
            self.buffer.extend_from_slice(b"Infinity");
            return;
        } else if float.is_nan() {
            self.buffer.extend_from_slice(b"NaN");
            return;
        } else if float == 0.0 && float.is_sign_negative() {
            self.buffer.extend_from_slice(b"-0");
            return;
        }

        let rounded = float.round();
        let is_int = if self.inspect {
            fuzzy_equals(float, rounded)
        } else {
            float == rounded
        };
        if is_int {
            // Dart rounds to a 64-bit integer and prints its exact digits;
            // beyond that range the shortest representation is all that is
            // left.
            if rounded == 0.0 {
                self.buffer.push(b'0');
            } else if rounded.abs() < 9.0e18 {
                let _ = write!(&mut self.buffer, "{}", rounded as i64);
            } else {
                let _ = write!(&mut self.buffer, "{}", rounded);
            }
            return;
        }

        // Rust's `Display` for `f64` is the shortest round-trip
        // representation without an exponent, which is what Dart's
        // `toString()` gives after `_removeExponent`.
        let mut text = float.to_string();

        if self.inspect {
            self.buffer.extend_from_slice(text.as_bytes());
            return;
        }

        // `SassNumber.precision + 2`
        if text.len() < 12 {
            if self.options.is_compressed() && text.starts_with('0') {
                text.remove(0);
            }
            self.buffer.extend_from_slice(text.as_bytes());
            return;
        }

        self.write_rounded(&text);
    }

    /// Dart Sass's `_writeRounded`: rounds a decimal string to ten
    /// fractional digits by looking at the eleventh, carrying into the
    /// integer part when needed, and drops trailing zeros.
    fn write_rounded(&mut self, text: &str) {
        const PRECISION: usize = 10;

        if let Some(integer) = text.strip_suffix(".0") {
            self.buffer.extend_from_slice(integer.as_bytes());
            return;
        }

        let bytes = text.as_bytes();
        // One extra leading slot to carry into.
        let mut digits = vec![0u8; bytes.len() + 1];
        let mut digits_index = 1;

        let mut text_index = 0;
        let negative = bytes[0] == b'-';
        if negative {
            text_index += 1;
        }
        loop {
            if text_index == bytes.len() {
                self.buffer.extend_from_slice(bytes);
                return;
            }

            let byte = bytes[text_index];
            text_index += 1;
            if byte == b'.' {
                break;
            }
            digits[digits_index] = byte - b'0';
            digits_index += 1;
        }
        let first_fractional_digit = digits_index;

        let index_after_precision = text_index + PRECISION;
        if index_after_precision >= bytes.len() {
            self.buffer.extend_from_slice(bytes);
            return;
        }

        while text_index < index_after_precision {
            digits[digits_index] = bytes[text_index] - b'0';
            digits_index += 1;
            text_index += 1;
        }

        if bytes[text_index] - b'0' >= 5 {
            loop {
                digits[digits_index - 1] += 1;
                if digits[digits_index - 1] != 10 {
                    break;
                }
                digits_index -= 1;
            }
        }

        // Pad the integer part back out if the carry consumed it, then
        // drop trailing zeros from the fraction.
        while digits_index < first_fractional_digit {
            digits[digits_index] = 0;
            digits_index += 1;
        }
        while digits_index > first_fractional_digit && digits[digits_index - 1] == 0 {
            digits_index -= 1;
        }

        if digits_index == 2 && digits[0] == 0 && digits[1] == 0 {
            self.buffer.push(b'0');
            return;
        }

        if negative {
            self.buffer.push(b'-');
        }

        let mut written_index = 0;
        if digits[0] == 0 {
            written_index += 1;
            if self.options.is_compressed() && digits[1] == 0 {
                written_index += 1;
            }
        }
        while written_index < first_fractional_digit {
            self.buffer.push(b'0' + digits[written_index]);
            written_index += 1;
        }

        if digits_index > first_fractional_digit {
            self.buffer.push(b'.');
            while written_index < digits_index {
                self.buffer.push(b'0' + digits[written_index]);
                written_index += 1;
            }
        }
    }

    pub fn visit_group(
        &mut self,
        stmt: CssStmt,
        prev_was_group_end: bool,
        prev_requires_semicolon: bool,
    ) -> SassResult<()> {
        if prev_requires_semicolon {
            self.buffer.push(b';');
        }

        if !self.buffer.is_empty() {
            self.write_optional_newline();
        }

        if prev_was_group_end && !self.buffer.is_empty() {
            self.write_optional_newline();
        }

        self.visit_stmt(stmt)?;

        Ok(())
    }

    fn finish_for_expr(self) -> String {
        // SAFETY: todo
        unsafe { String::from_utf8_unchecked(self.buffer) }
    }

    pub fn finish(mut self, prev_requires_semicolon: bool) -> String {
        let is_not_ascii = self.buffer.iter().any(|&c| !c.is_ascii());

        if prev_requires_semicolon {
            self.buffer.push(b';');
        }

        if !self.buffer.is_empty() {
            self.write_optional_newline();
        }

        // SAFETY: todo
        let mut as_string = unsafe { String::from_utf8_unchecked(self.buffer) };

        if is_not_ascii && self.options.is_compressed() && self.options.allows_charset {
            as_string.insert(0, '\u{FEFF}');
        } else if is_not_ascii && self.options.allows_charset {
            as_string.insert_str(0, "@charset \"UTF-8\";\n");
        }

        as_string
    }

    fn write_indentation(&mut self) {
        if self.options.is_compressed() {
            return;
        }

        self.buffer.reserve(self.indentation);
        for _ in 0..self.indentation {
            self.buffer.push(b' ');
        }
    }

    fn write_list_separator(&mut self, sep: ListSeparator) {
        match (sep, self.options.is_compressed()) {
            (ListSeparator::Space | ListSeparator::Undecided, _) => self.buffer.push(b' '),
            (ListSeparator::Comma, true) => self.buffer.push(b','),
            (ListSeparator::Comma, false) => self.buffer.extend_from_slice(b", "),
            (ListSeparator::Slash, true) => self.buffer.push(b'/'),
            (ListSeparator::Slash, false) => self.buffer.extend_from_slice(b" / "),
        }
    }

    fn elem_needs_parens(sep: ListSeparator, elem: &Value) -> bool {
        // An arglist is a list, so it takes parentheses on the same terms. In
        // dart-sass `SassArgumentList` extends `SassList` and
        // `_elementNeedsParens` covers both without saying so; here the two
        // are separate variants, and only the map-value rule had been carried
        // across.
        let (len, elem_sep, brackets) = match elem {
            Value::List(elems, elem_sep, brackets) => (elems.len(), *elem_sep, *brackets),
            Value::ArgList(arglist) => (arglist.elems.len(), arglist.separator, Brackets::None),
            _ => return false,
        };

        if len < 2 || brackets == Brackets::Bracketed {
            return false;
        }

        match sep {
            ListSeparator::Comma => elem_sep == ListSeparator::Comma,
            ListSeparator::Slash => {
                elem_sep == ListSeparator::Comma || elem_sep == ListSeparator::Slash
            }
            _ => elem_sep != ListSeparator::Undecided,
        }
    }

    fn visit_list(
        &mut self,
        list_elems: &[Value],
        sep: ListSeparator,
        brackets: Brackets,
        span: Span,
    ) -> SassResult<()> {
        if brackets == Brackets::Bracketed {
            self.buffer.push(b'[');
        } else if list_elems.is_empty() {
            if !self.inspect {
                return Err(("() isn't a valid CSS value.", span).into());
            }

            self.buffer.extend_from_slice(b"()");
            return Ok(());
        }

        let is_singleton = self.inspect
            && list_elems.len() == 1
            && (sep == ListSeparator::Comma || sep == ListSeparator::Slash);

        if is_singleton && brackets != Brackets::Bracketed {
            self.buffer.push(b'(');
        }

        let (mut x, mut y);
        let elems: &mut dyn Iterator<Item = &Value> = if self.inspect {
            x = list_elems.iter();
            &mut x
        } else {
            y = list_elems.iter().filter(|elem| !elem.is_blank());
            &mut y
        };

        let mut elems = elems.peekable();

        while let Some(elem) = elems.next() {
            if self.inspect {
                let needs_parens = Self::elem_needs_parens(sep, elem);
                if needs_parens {
                    self.buffer.push(b'(');
                }

                self.visit_value(elem, span)?;

                if needs_parens {
                    self.buffer.push(b')');
                }
            } else {
                self.visit_value(elem, span)?;
            }

            if elems.peek().is_some() {
                self.write_list_separator(sep);
            }
        }

        if is_singleton {
            match sep {
                ListSeparator::Comma => self.buffer.push(b','),
                ListSeparator::Slash => self.buffer.push(b'/'),
                _ => unreachable!(),
            }

            if brackets != Brackets::Bracketed {
                self.buffer.push(b')');
            }
        }

        if brackets == Brackets::Bracketed {
            self.buffer.push(b']');
        }

        Ok(())
    }

    fn write_map_element(&mut self, value: &Value, span: Span) -> SassResult<()> {
        // A comma-separated list needs parentheses to keep the map
        // unambiguous: `(positional: (1, 2))`, not `(positional: 1, 2)`. An
        // argument list is a list too, and needs them on the same condition
        // -- which is its own separator, not always a comma.
        let needs_parens = match value {
            Value::List(_, separator, Brackets::None) => *separator == ListSeparator::Comma,
            Value::ArgList(arglist) => arglist.separator == ListSeparator::Comma,
            _ => false,
        };

        if needs_parens {
            self.buffer.push(b'(');
        }

        self.visit_value(value, span)?;

        if needs_parens {
            self.buffer.push(b')');
        }

        Ok(())
    }

    fn visit_map(&mut self, map: &SassMap, span: Span) -> SassResult<()> {
        if !self.inspect {
            return Err((
                format!(
                    "{} isn't a valid CSS value.",
                    inspect_map(map, self.options, span)?
                ),
                span,
            )
                .into());
        }

        self.buffer.push(b'(');

        let mut elems = map.iter().peekable();

        while let Some((k, v)) = elems.next() {
            self.write_map_element(&k.node, k.span)?;
            self.buffer.extend_from_slice(b": ");
            self.write_map_element(v, k.span)?;
            if elems.peek().is_some() {
                self.buffer.extend_from_slice(b", ");
            }
        }

        self.buffer.push(b')');

        Ok(())
    }

    fn visit_unquoted_string(&mut self, string: &str) {
        let mut after_newline = false;
        self.buffer.reserve(string.len());

        let mut chars = string.chars().peekable();

        while let Some(c) = chars.next() {
            match c {
                '\n' => {
                    self.buffer.push(b' ');
                    after_newline = true;
                }
                ' ' => {
                    if !after_newline {
                        self.buffer.push(b' ');
                    }
                }
                _ => {
                    after_newline = false;

                    if is_private_use(c) && !self.options.is_compressed() {
                        let mut escaped = Vec::new();
                        write_escape(&mut escaped, c, chars.peek().copied());
                        self.buffer.extend_from_slice(&escaped);
                    } else {
                        push_char(&mut self.buffer, c);
                    }
                }
            }
        }
    }

    fn visit_quoted_string(&mut self, force_double_quote: bool, string: &str) {
        let mut has_single_quote = false;
        let mut has_double_quote = false;

        let mut buffer = Vec::new();

        if force_double_quote {
            buffer.push(b'"');
        }
        let mut iter = string.chars().peekable();
        while let Some(c) = iter.next() {
            match c {
                '\'' => {
                    if force_double_quote {
                        buffer.push(b'\'');
                    } else if has_double_quote {
                        self.visit_quoted_string(true, string);
                        return;
                    } else {
                        has_single_quote = true;
                        buffer.push(b'\'');
                    }
                }
                '"' => {
                    if force_double_quote {
                        buffer.push(b'\\');
                        buffer.push(b'"');
                    } else if has_single_quote {
                        self.visit_quoted_string(true, string);
                        return;
                    } else {
                        has_double_quote = true;
                        buffer.push(b'"');
                    }
                }
                '\x00'..='\x08' | '\x0A'..='\x1F' => {
                    write_escape(&mut buffer, c, iter.peek().copied());
                }
                '\\' => {
                    buffer.push(b'\\');
                    buffer.push(b'\\');
                }
                _ => {
                    if is_private_use(c) && !self.options.is_compressed() {
                        write_escape(&mut buffer, c, iter.peek().copied());
                    } else {
                        push_char(&mut buffer, c);
                    }
                }
            }
        }

        if force_double_quote {
            buffer.push(b'"');
            self.buffer.extend_from_slice(&buffer);
        } else {
            let quote = if has_double_quote { b'\'' } else { b'"' };
            self.buffer.push(quote);
            self.buffer.extend_from_slice(&buffer);
            self.buffer.push(quote);
        }
    }

    fn visit_function_ref(&mut self, func: &SassFunction, span: Span) -> SassResult<()> {
        if !self.inspect {
            return Err((
                format!(
                    "{} isn't a valid CSS value.",
                    inspect_function_ref(func, self.options, span)?
                ),
                span,
            )
                .into());
        }

        // A plain function keeps the spelling it was given, as dart-sass
        // prints it: `get-function("file_join")`, not `file-join`.
        let name = match func {
            SassFunction::Plain { name } => name.clone(),
            _ => func.name().to_string(),
        };

        self.buffer.extend_from_slice(b"get-function(");
        self.visit_quoted_string(false, &name);
        self.buffer.push(b')');

        Ok(())
    }

    /// Writes a first-class mixin. Like a function reference, it has no plain
    /// CSS form, so it is only ever written under `inspect`.
    fn visit_mixin_ref(&mut self, mixin: &Mixin, span: Span) -> SassResult<()> {
        if !self.inspect {
            return Err((
                format!(
                    "{} isn't a valid CSS value.",
                    inspect_mixin_ref(mixin, self.options, span)?
                ),
                span,
            )
                .into());
        }

        self.buffer.extend_from_slice(b"get-mixin(");
        self.visit_quoted_string(false, mixin.name().as_str());
        self.buffer.push(b')');

        Ok(())
    }

    fn visit_arglist(&mut self, arglist: &ArgList, span: Span) -> SassResult<()> {
        // An arglist carries the separator of the list splatted into it, or a
        // comma when nothing decided one, so it writes like the list it came
        // from rather than always with commas.
        self.visit_list(&arglist.elems, arglist.separator, Brackets::None, span)
    }

    fn visit_value(&mut self, value: &Value, span: Span) -> SassResult<()> {
        match value {
            Value::Dimension(num) => self.visit_number(num)?,
            Value::Color(color) => self.visit_color(color),
            Value::Calculation(calc) => self.visit_calculation(calc)?,
            Value::List(elems, sep, brackets) => self.visit_list(elems, *sep, *brackets, span)?,
            Value::True => self.buffer.extend_from_slice(b"true"),
            Value::False => self.buffer.extend_from_slice(b"false"),
            Value::Null => {
                if self.inspect {
                    self.buffer.extend_from_slice(b"null")
                }
            }
            Value::Map(map) => self.visit_map(map, span)?,
            Value::FunctionRef(func) => self.visit_function_ref(func, span)?,
            Value::MixinRef(mixin) => self.visit_mixin_ref(mixin.inner(), span)?,
            Value::String(s, QuoteKind::Quoted) => self.visit_quoted_string(false, s),
            Value::String(s, QuoteKind::None) => self.visit_unquoted_string(s),
            Value::ArgList(arglist) => self.visit_arglist(arglist, span)?,
        }

        Ok(())
    }

    fn write_style(&mut self, style: Style) -> SassResult<()> {
        if !self.options.is_compressed() {
            self.write_indentation();
        }

        self.buffer
            .extend_from_slice(style.property.resolve_ref().as_bytes());
        self.buffer.push(b':');

        // todo: _writeFoldedValue and _writeReindentedValue
        if style.parsed_as_sass_script && !self.options.is_compressed() {
            self.buffer.push(b' ');
        }

        self.visit_value(&style.value.node, style.value.span)?;

        Ok(())
    }

    fn write_import(&mut self, import: &str, modifiers: Option<String>) -> SassResult<()> {
        self.write_indentation();
        self.buffer.extend_from_slice(b"@import ");
        write!(&mut self.buffer, "{}", import)?;

        if let Some(modifiers) = modifiers {
            self.buffer.push(b' ');
            self.buffer.extend_from_slice(modifiers.as_bytes());
        }

        Ok(())
    }

    fn write_comment(&mut self, comment: &str, span: Span) -> SassResult<()> {
        if self.options.is_compressed() && !comment.starts_with("/*!") {
            return Ok(());
        }

        if !self.inline_comment {
            self.write_indentation();
        }
        let col = self.map.look_up_pos(span.low()).position.column;
        let mut lines = comment.lines();

        if let Some(line) = lines.next() {
            self.buffer.extend_from_slice(line.trim_start().as_bytes());
        }

        let lines = lines
            .map(|line| {
                let diff = (line.len() - line.trim_start().len()).saturating_sub(col);
                format!("{}{}", " ".repeat(diff), line.trim_start())
            })
            .collect::<Vec<String>>()
            .join("\n");

        if !lines.is_empty() {
            write!(&mut self.buffer, "\n{}", lines)?;
        }

        Ok(())
    }

    pub fn requires_semicolon(stmt: &CssStmt) -> bool {
        match stmt {
            CssStmt::Style(_) | CssStmt::Import(_, _) => true,
            CssStmt::UnknownAtRule(rule, _) => !rule.has_body,
            _ => false,
        }
    }

    /// The source line a statement ends on, for the statements that carry a
    /// span. Used to keep a trailing comment on the same output line as the
    /// declaration it follows, as Dart Sass does.
    fn stmt_end_line(&self, stmt: &CssStmt) -> Option<usize> {
        match stmt {
            CssStmt::Style(style) => {
                Some(self.map.look_up_pos(style.value.span.high()).position.line)
            }
            CssStmt::Comment(_, span) => Some(self.map.look_up_pos(span.high()).position.line),
            _ => None,
        }
    }

    /// Whether `stmt` is a comment that starts on `prev_end_line`, and should
    /// therefore be written on the same output line as the previous statement.
    fn is_trailing_comment(&self, stmt: &CssStmt, prev_end_line: Option<usize>) -> bool {
        if self.options.is_compressed() {
            return false;
        }
        match (stmt, prev_end_line) {
            (CssStmt::Comment(_, span), Some(prev_line)) => {
                self.map.look_up_pos(span.low()).position.line == prev_line
            }
            _ => false,
        }
    }

    fn write_children(&mut self, children: Vec<CssStmt>) -> SassResult<()> {
        if self.options.is_compressed() {
            self.buffer.push(b'{');
        } else {
            self.buffer.extend_from_slice(b" {\n");
        }

        self.indentation += self.indent_width;

        let len = children.len();
        let mut prev_end_line: Option<usize> = None;

        for (idx, child) in children.into_iter().enumerate() {
            let is_last = idx + 1 == len;
            let needs_semicolon = Self::requires_semicolon(&child);
            let end_line = self.stmt_end_line(&child);

            if self.is_trailing_comment(&child, prev_end_line) {
                // Rewind the newline written after the previous statement so
                // the comment lands on the same line, separated by a space.
                if self.buffer.last() == Some(&b'\n') {
                    self.buffer.pop();
                }
                self.buffer.push(b' ');
                self.inline_comment = true;
            }

            let did_write = self.visit_stmt(child)?;
            self.inline_comment = false;

            if !did_write {
                continue;
            }

            prev_end_line = end_line;

            if needs_semicolon && !(is_last && self.options.is_compressed()) {
                self.buffer.push(b';');
            }

            self.write_optional_newline();
        }

        self.indentation -= self.indent_width;

        if self.options.is_compressed() {
            self.buffer.push(b'}');
        } else {
            self.write_indentation();
            self.buffer.extend_from_slice(b"}");
        }

        Ok(())
    }

    fn write_optional_space(&mut self) {
        if !self.options.is_compressed() {
            self.buffer.push(b' ');
        }
    }

    fn write_optional_newline(&mut self) {
        if !self.options.is_compressed() {
            self.buffer.push(b'\n');
        }
    }

    fn write_supports_rule(&mut self, supports_rule: SupportsRule) -> SassResult<()> {
        self.write_indentation();
        self.buffer.extend_from_slice(b"@supports");

        if !supports_rule.params.is_empty() {
            self.buffer.push(b' ');
            self.buffer
                .extend_from_slice(supports_rule.params.as_bytes());
        }

        self.write_children(supports_rule.body)?;

        Ok(())
    }

    /// Returns whether or not text was written
    fn visit_stmt(&mut self, stmt: CssStmt) -> SassResult<bool> {
        if stmt.is_invisible() {
            return Ok(false);
        }

        match stmt {
            CssStmt::RuleSet { selector, body, .. } => {
                self.write_indentation();
                self.write_selector_list(&selector.as_selector_list());

                self.write_children(body)?;
            }
            CssStmt::Media(media_rule, ..) => {
                self.write_indentation();
                self.buffer.extend_from_slice(b"@media ");

                if let Some((last, rest)) = media_rule.query.split_last() {
                    for query in rest {
                        self.write_media_query(query);

                        self.buffer.push(b',');

                        self.write_optional_space();
                    }

                    self.write_media_query(last);
                }

                self.write_children(media_rule.body)?;
            }
            CssStmt::UnknownAtRule(unknown_at_rule, ..) => {
                self.write_indentation();
                self.buffer.push(b'@');
                self.buffer
                    .extend_from_slice(unknown_at_rule.name.as_bytes());

                if !unknown_at_rule.params.is_empty() {
                    write!(&mut self.buffer, " {}", unknown_at_rule.params)?;
                }

                if !unknown_at_rule.has_body {
                    debug_assert!(unknown_at_rule.body.is_empty());
                    return Ok(true);
                } else if unknown_at_rule.body.iter().all(CssStmt::is_invisible) {
                    self.buffer.extend_from_slice(b" {}");
                    return Ok(true);
                }

                self.write_children(unknown_at_rule.body)?;
            }
            CssStmt::Style(style) => self.write_style(style)?,
            CssStmt::Comment(comment, span) => self.write_comment(&comment, span)?,
            CssStmt::KeyframesRuleSet(keyframes_rule_set) => {
                self.write_indentation();
                // todo: i bet we can do something like write_with_separator to avoid extra allocation
                let selector = keyframes_rule_set
                    .selector
                    .into_iter()
                    .map(|s| s.to_string())
                    .collect::<Vec<String>>()
                    .join(", ");

                self.buffer.extend_from_slice(selector.as_bytes());

                self.write_children(keyframes_rule_set.body)?;
            }
            CssStmt::Import(import, modifier) => self.write_import(&import, modifier)?,
            CssStmt::Supports(supports_rule, _) => self.write_supports_rule(supports_rule)?,
        }

        Ok(true)
    }
}