tsv_css 0.8.0

CSS formatter and parser compatible with Svelte's parseCss — part of tsv
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
use super::{CssParser, is_boolean_operator_keyword};
use crate::ast::*;
use crate::lexer::TokenKind;
use crate::parser::selectors::{parse_complex_selector_list, parse_forgiving_selector_list};
use crate::whitespace::{Comments, Edge, holds_boundary_member, spell_run};
use tsv_lang::{Error, Span};

/// Whether the current token is a CSS `<function-token>` — an identifier
/// immediately followed by `(` with no intervening whitespace (`url(`, `layer(`,
/// `supports(`, `selector(`). The lexer emits the name and `(` as separate tokens
/// (only an unquoted `url(...)` is one opaque `Url` token), so the
/// function-vs-plain-ident distinction is recovered here by peeking the source byte
/// after the identifier.
///
/// This is the whole of css-values-4 §"Functional Notations" on the point — any
/// character between the name and the `(`, whitespace included, leaves an ordinary
/// identifier followed by a parenthesis — and every reader of that rule in this file
/// asks it here, so a condition part, a container name and a value function cannot
/// disagree about what a function is.
fn is_function_token(parser: &CssParser<'_, '_>) -> bool {
    parser.check(TokenKind::Identifier) && {
        let end_pos = parser.current_end();
        parser.source.get(end_pos..=end_pos) == Some("(")
    }
}

/// Is the current token the `selector` of a `selector(` function token — the
/// condition grammar's one function whose argument is a selector rather than a
/// declaration?
///
/// The name is matched ASCII case-insensitively, css-values-4's other half of the
/// same section: "like keywords, function names are ASCII case-insensitive".
fn at_selector_function(parser: &CssParser<'_, '_>) -> bool {
    is_function_token(parser) && parser.current_identifier().eq_ignore_ascii_case("selector")
}

/// Read a `selector()` argument as the selector it is, with the parser positioned
/// on the argument's first token (just past the `(`).
///
/// On success the parser is seated on the closing `)`. Otherwise it is rewound to
/// `arg_start` — every token and every comment registration undone — and the
/// caller consumes the argument as opaque text: `<supports-in-parens>` falls
/// through to `<general-enclosed>` (css-conditional-3), a `<function-token>`
/// whose contents the grammar leaves undefined, so there is nothing to normalize
/// and a UA evaluates it as false.
///
/// Landing anywhere but the closing `)` counts as failure even when the parse
/// returned `Ok`: `parse_complex_selector` stops at the first token it cannot
/// continue with rather than erroring, so `Ok` alone would also accept a selector
/// followed by garbage.
fn parse_selector_argument<'arena>(
    parser: &mut CssParser<'_, 'arena>,
    arg_start: usize,
    comments_len: usize,
) -> Result<Option<SelectorList<'arena>>, Error> {
    match parse_complex_selector_list(parser) {
        Ok(list) if parser.check(TokenKind::RightParen) => return Ok(Some(list)),
        // a depth limit is no verdict on the argument (see `parse_forgiving_selector_list`)
        Err(error) if error.kind() == tsv_lang::ErrorKind::TooDeep => return Err(error),
        Ok(_) | Err(_) => {}
    }
    parser.rewind_to(arg_start, comments_len)?;
    Ok(None)
}

/// Must a spacing rule emit its own separator before the current token, or does the
/// part buffer already end in one?
///
/// The two rules that pad a token — the boolean operator's space and the comment's —
/// both ask this, so they can never stack into a double space with each other or with
/// the rules that ran before them (a source whitespace run, the space after a value
/// `:`, the space after a comment). `trailing_spaces` is the buffer's count of
/// *programmatic* trailing spaces, so it answers that directly; the one separated
/// position it can't see is an opening paren, which wants no separator at all
/// (`(not (…))` and `(/* c */ a: b)` keep the paren tight, matching prettier). `None`
/// is the part's first token, which is always that `(`.
fn needs_separator_before(prev: Option<TokenKind>, trailing_spaces: usize) -> bool {
    trailing_spaces == 0 && !matches!(prev, None | Some(TokenKind::LeftParen))
}

/// Skip a gap between condition parts, registering its comments and widening `end`
/// past the last of them.
///
/// The query's own gaps — before a part, and after a connector (`(a) /* c */ and
/// /* d */ (b)`) — are printer-reconstructed, so their comments must be *registered*
/// rather than emitted (a dropping skip loses them silently). That is
/// `skip_whitespace_registering_comments`'s job everywhere else in this file; the one
/// thing it can't do is report where the last comment ended, and the query's span has
/// to cover it — a trailing `(a) /* c */` gap is inside the prelude the printer
/// re-emits from. Hence the loop, in one place rather than at each gap.
///
/// ⚠️ **The gap steps the boundary class**, not ASCII whitespace alone: a non-ASCII space
/// here (`@supports <NBSP> (a: b)`, `(a: b) and <NBSP> (c: d)`) is one the lexer reads as
/// the head of an identifier, and an identifier the reader cannot start a part with — so
/// an ASCII skip sent the whole prelude to the verbatim path, its condition no longer read
/// at all. The run is the author's, and the printer claims it back from the gap
/// (`Printer::build_condition_query_doc`), the same partition every boundary claim keeps.
///
/// `run` collects the gap's comments as it goes — the query cannot yet know whether
/// a part will follow to bind them, and one that never does keeps them (see
/// [`ConditionQuery::trailing_operators`]). A part that does binds them, and the query
/// loop clears the buffer. A gap that holds a boundary MEMBER goes into it as one item,
/// spelled in place (`crate::whitespace::spell_run`), so a run between two operators
/// (`and <NBSP> or`) rides the connector run's text with the comments around it.
fn skip_gap_registering_comments(
    parser: &mut CssParser<'_, '_>,
    end: &mut usize,
    run: &mut OperatorRun,
) -> Result<(), Error> {
    let gap_start = parser.current_start();
    let mark = run.text.len();
    parser.skip_boundary_whitespace()?;
    while parser.check(TokenKind::Comment) {
        parser.register_current_comment();
        run.push_comment(
            parser.current_value(),
            parser.span_pos(parser.current_end()),
        );
        *end = parser.base_offset() + parser.current_end();
        parser.advance()?;
        parser.skip_boundary_whitespace()?;
    }
    let gap_end = parser.current_start();
    if holds_boundary_member(parser.source(), gap_start, gap_end) {
        // Both edges as the author wrote them: a run glued to the word after it (`<NBSP>or`)
        // is one identifier with it to css-syntax-3, so the run text must not space them.
        let spelled = spell_run(
            parser.source(),
            gap_start,
            gap_end,
            false,
            (Edge::Presence, Edge::Presence),
            Comments::Carried,
        );
        run.text.truncate(mark);
        run.push_gap(&spelled, parser.span_pos(gap_end));
    }
    Ok(())
}

/// What a condition query has consumed since its last part — the operators, whether a
/// part will bind them or not, and the gap comments collected beside them.
///
/// The facts move together (a part binds all of them at once), so they are one value:
/// keeping them as parallel locals is how a site comes to update some of them.
///
/// The buffer answers **two** questions off one walk, which is why they share it: the
/// operator run a following part binds ([`Self::connector_run`], which becomes that
/// part's `ConnectorRun`) and the one no part ever comes for ([`Self::finish`], which
/// becomes the query's `trailing_operators`). They differ only in their bounds — the
/// bound run stops at the first and last *operator*, so the comments on either side of
/// it stay the printer's to claim, while the unbound one is the whole gap, there being
/// no part left to claim anything. Named for the material rather than for either answer:
/// whether the run is bound is a question you ask it, not a fact about the buffer.
struct OperatorRun {
    /// The words so far, a single space between them whatever the author wrote — the run's
    /// spacing is the grammar's, exactly as a condition part's is (`parse_condition_part`
    /// builds `part_buf` the same way). Each word is pushed **verbatim** from source, so an
    /// operator keeps its case (`AND` stays `AND`) and a comment its interior.
    text: String,
    /// The bound run's bounds, set once an operator lands. `None` while the buffer holds
    /// only comments — a gap that ends the query holding just those
    /// (`@container b /* c */ {`) is the ordinary trailing-comment claim's, and they stay
    /// registered for it, so only an operator turns the buffer into a run.
    ///
    /// One `Option` rather than three fields because the three are meaningless apart: an
    /// end with no start, or a registry length belonging to an operator that never landed,
    /// are states this buffer must not be able to hold.
    operators: Option<OperatorBounds>,
    /// The comment registry's length when the run began, to truncate back to if it does
    /// end up claiming its comments.
    comments_len: usize,
    /// Where the last item collected ends in the document — the far end of an unbound run,
    /// which the query's span has to reach (its words are the prelude's, and the printer's
    /// tail claim starts after them).
    source_end: u32,
    /// Whether the last item was a boundary run the author glued to whatever comes next, so
    /// the next word joins it with no space (`<NBSP>or`, one identifier to css-syntax-3).
    glued_to_next: bool,
}

/// Where a bound run sits in [`OperatorRun::text`], and what the comment registry owes it.
struct OperatorBounds {
    /// Where the run's first operator starts.
    start: usize,
    /// Where its last operator ends. Everything between the two is run text — the later
    /// operators and the comments among them.
    end: usize,
    /// The registry's length when the **first** operator landed, to truncate back to when a
    /// later one proves the comments since then are inside the run's own text.
    comments_len: usize,
    /// The same bounds in the document: the first operator's start through the last one's end.
    source: Span,
}

impl OperatorRun {
    /// A fresh run, with the comment registry standing at `comments_len`.
    fn new(comments_len: usize) -> Self {
        Self {
            text: String::new(),
            operators: None,
            comments_len,
            source_end: 0,
            glued_to_next: false,
        }
    }

    /// Collect a gap comment — not yet a run, since a part may still bind it. `end` is where
    /// it ends in the document.
    fn push_comment(&mut self, comment: &str, end: u32) {
        self.push_word(comment);
        self.source_end = end;
    }

    /// Collect a gap holding a boundary run, already spelled with its comments in place and
    /// the author's separation on both edges (a leading and a trailing space where they wrote
    /// one) — one item, like a comment. `end` is where the gap ends in the document.
    ///
    /// Its own edges ARE its separators: it takes no joining space ahead of it (its leading
    /// one says whether the author separated it from the word before), and hands the next
    /// word a glued join where the author glued it (`glued_to_next`). At the run's head there
    /// is no word to separate from, so a leading space is dropped.
    fn push_gap(&mut self, spelled: &str, end: u32) {
        let spelled = if self.text.is_empty() {
            spelled.trim_start_matches(' ')
        } else {
            spelled
        };
        let (body, glued) = match spelled.strip_suffix(' ') {
            Some(body) => (body, false),
            None => (spelled, true),
        };
        self.text.push_str(body);
        self.glued_to_next = glued;
        self.source_end = end;
    }

    /// Collect an operator, which is what makes the buffer a run.
    ///
    /// `comments_len` is the registry's length now. The return is the length to truncate
    /// it back to, `Some` only for an operator that is **not** the run's first: the
    /// comments registered since that first one sit *between* two operators, so the run's
    /// own text carries them and their registration has to go, or the printer's gap sweep
    /// would print each a second time.
    ///
    /// `#[must_use]` is the pairing's enforcement — a caller that pushes an operator and
    /// drops the answer leaves a comment for two emitters to print, and the double print is
    /// invisible to every fixed-point gate.
    #[must_use]
    fn push_operator(
        &mut self,
        operator: &str,
        comments_len: usize,
        source: Span,
    ) -> Option<usize> {
        // Read before the push: `None` here is exactly "this is the run's first operator".
        let unregister_to = self.operators.as_ref().map(|bounds| bounds.comments_len);
        let start = self.push_word(operator);
        self.source_end = source.end;
        match &mut self.operators {
            Some(bounds) => {
                bounds.end = self.text.len();
                bounds.source.end = source.end;
            }
            None => {
                self.operators = Some(OperatorBounds {
                    start,
                    end: self.text.len(),
                    comments_len,
                    source,
                });
            }
        }
        unregister_to
    }

    /// Push a word and report where it landed in `text`.
    fn push_word(&mut self, word: &str) -> usize {
        if !self.text.is_empty() && !self.glued_to_next {
            self.text.push(' ');
        }
        self.glued_to_next = false;
        let start = self.text.len();
        self.text.push_str(word);
        start
    }

    /// The operator run a part would bind — first operator through last, the comments
    /// between them included — or `None` when nothing but comments has been collected.
    ///
    /// Bounded at the operators on **both** ends, unlike [`Self::finish`]: a comment
    /// before the first (`(a: b) /* c */ and (c: d)`) or after the last (`and /* c */
    /// (c: d)`) is one the printer's own gap sweep claims onto its authored side of the
    /// separator, so the run must not swallow it.
    fn connector_run(&self) -> Option<(&str, Span)> {
        self.operators
            .as_ref()
            .map(|bounds| (&self.text[bounds.start..bounds.end], bounds.source))
    }

    /// A part bound everything collected so far: its connector run rides the part and the
    /// gap comments outside that run stay registered for the printer's separator, so the
    /// run restarts here — in place, keeping the buffer's allocation across a many-part
    /// query.
    fn bind(&mut self, comments_len: usize) {
        self.text.clear();
        self.operators = None;
        self.comments_len = comments_len;
        self.glued_to_next = false;
    }

    /// The run's text and the comment-registry length to truncate back to, or `None` when
    /// the query bound everything it consumed — every well-formed condition.
    ///
    /// The whole buffer, comments on both ends included: no part is coming to claim them,
    /// so the run is the only carrier they have.
    fn finish(&self) -> Option<(&str, usize, u32)> {
        self.operators
            .as_ref()
            .map(|_| (self.text.as_str(), self.comments_len, self.source_end))
    }
}

/// Can a boolean operator (`and`/`or`/`not`) begin at this point in a condition?
///
/// Only where the grammar can start one: at the beginning of a condition, or
/// against a parenthesis — `not (…)`, `(…) and (…)`. Everywhere else an
/// identifier spelled `and` is just an identifier: a value (`(font-family: and)`),
/// a class (`selector(.and)`), a pseudo-class name (`selector(div:not(.a))`).
/// Spacing one of those as an operator does not merely look wrong, it rewrites
/// the declaration or the selector.
///
/// `prev` is the previous **significant** token — whitespace and comments are
/// transparent, since neither can turn an identifier into an operator.
fn boolean_operator_position(prev: Option<TokenKind>, in_selector_args: bool) -> bool {
    !in_selector_args
        && matches!(
            prev,
            None | Some(TokenKind::LeftParen) | Some(TokenKind::RightParen)
        )
}

/// Which of prettier's two prelude readers a condition prelude is read by — the axis
/// that decides whether its value text is regrouped or kept as the author wrote it.
///
/// `parser-postcss.js` hands `@supports` (and the `supports()` of an `@import`) to
/// `parseValue`, which regroups the value into its own nodes and prints its own
/// separators, so a comma there is a separator and takes prettier's `, `.
/// `@container` is on **neither** of prettier's lists: its params stay raw, so a comma
/// between its parens is the author's byte and moving it would be a rewrite.
///
/// The axis `value_normalization::ValueReader` already names for the printer's
/// number/hex rules, stated here for the parser's separator rules.
/// ⚠️ The variants name **prettier's** reader, not tsv's output. `Raw` bounds the comma
/// rule and nothing else: tsv still applies its own boolean-operator and value-colon
/// spacing to a `@container` prelude, a deliberate divergence with its own catalog entry
/// (`container_spacing_prettier_divergence` — ◆spec_violation, the grammar requires the
/// space `and(` omits). Don't read `Raw` as "tsv emits this verbatim".
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum ConditionReader {
    /// `@supports`, and `@import`'s `supports()` — read by `parseValue`.
    Value,
    /// `@container` — read by neither of prettier's readers, so its prelude text is
    /// prettier's verbatim.
    Raw,
}

/// Parse a condition query — `(prop: val)` parts connected by `and`/`or`, with
/// an optional leading `not` and function-style `selector(...)` conditions.
///
/// This *is* the entire `@supports` prelude (`<supports-condition>`), and
/// `@container` reuses it verbatim for its `<container-query>` — the two grammars
/// are identical; `@container` only adds an optional `<container-name>` preamble
/// before calling this. The returned span starts at the parser's current
/// position (the first condition token); `parse_container_prelude` widens the
/// start to cover the name.
///
/// Examples:
/// - `(display: grid)` - single condition
/// - `(display: grid) and (flex: 1)` - conjunction
/// - `not (color: red)` - negation
/// - `(a) and (b) or (c)` - mixed (parsed left-to-right)
pub(super) fn parse_condition_query<'arena>(
    parser: &mut CssParser<'_, 'arena>,
    reader: ConditionReader,
) -> Result<(ConditionQuery<'arena>, Span), Error> {
    // The prelude's head, when it opens on a boundary run: stepped before the span begins,
    // like the ASCII whitespace the at-rule already stepped, so the span starts where the
    // canonical (trimmed) prelude does. The printer claims the run from the name's end.
    parser.skip_boundary_whitespace()?;
    let start = parser.base_offset() + parser.current_start();
    let mut parts = parser.bvec();
    let mut current_connector: Option<ConditionConnector> = None;
    let mut end_pos = start;
    // What the loop has consumed since the last part — the connector run a part binds
    // (`ConditionPart::connector`, whose source text and case the printer preserves),
    // or, if none ever comes, `ConditionQuery::trailing_operators`.
    let mut run = OperatorRun::new(parser.comments.len());

    while !parser.at_prelude_end() {
        // The gap before a part (`(a) /* comment */ and (b)`)
        skip_gap_registering_comments(parser, &mut end_pos, &mut run)?;

        // Check for `and`/`or` connector. CSS grammar keywords are ASCII
        // case-insensitive (CSS Syntax 3), so `AND`/`Or` connect like `and`; the
        // enum normalizes for logic but the run's source text is kept in `ConnectorRun::text`
        // and preserved by the printer (matching prettier).
        if parser.check(TokenKind::Identifier) {
            let ident = parser.current_identifier();

            let connector = if ident.eq_ignore_ascii_case("and") {
                Some(ConditionConnector::And)
            } else if ident.eq_ignore_ascii_case("or") {
                Some(ConditionConnector::Or)
            } else {
                None
            };

            if let Some(conn) = connector {
                // This is a connector between parts. `current_connector` is the run's
                // LAST operator — the one whose kind the printer splits the gap's
                // comments around — while the run itself keeps every word.
                current_connector = Some(conn);
                let source = Span {
                    start: parser.span_pos(parser.current_start()),
                    end: parser.span_pos(parser.current_end()),
                };
                if let Some(comments_len) =
                    run.push_operator(parser.current_value(), parser.comments.len(), source)
                {
                    parser.comments.truncate(comments_len);
                }
                // Widen over the keyword itself, so a connector that never finds its
                // part still lies inside the query's span (a part that does follow
                // widens past it anyway).
                end_pos = parser.base_offset() + parser.current_end();
                parser.advance()?;
                // The gap after a connector (`and /* comment */ (b)`)
                skip_gap_registering_comments(parser, &mut end_pos, &mut run)?;
                continue;
            }
        }

        // The run this part binds, allocated once here rather than per operator.
        let connector =
            current_connector
                .take()
                .zip(run.connector_run())
                .map(|(kind, (text, span))| ConnectorRun {
                    kind,
                    text: parser.alloc_str_in(text),
                    span,
                });
        let part_start = parser.span_pos(parser.current_start());
        match parse_condition_part(parser, connector, end_pos, reader)? {
            ConditionPartOutcome::Parsed { part, end, .. } => {
                end_pos = end;
                run.bind(parser.comments.len());
                if let Some(part) = part {
                    parts.push(part);
                }
            }
            // Not a valid condition part, so the query ends here; the caller reports
            // whatever follows. A `not` prefix the part reader consumed before giving up
            // comes back with it — the reader took those bytes, so it owes them.
            ConditionPartOutcome::NotAPart { consumed, end } => {
                if let Some(consumed) = consumed {
                    // No part is coming, so `finish` truncates the registry past this
                    // anyway; honored all the same, so one rule holds at every call.
                    let source = Span {
                        start: part_start,
                        end: end as u32,
                    };
                    if let Some(comments_len) =
                        run.push_operator(consumed, parser.comments.len(), source)
                    {
                        parser.comments.truncate(comments_len);
                    }
                }
                end_pos = end;
                break;
            }
        }
    }

    // Whatever is left is a run of operators with no operand. Its comments were
    // registered on the way in, when a part might still have bound them; they ride the
    // run's own text now, so drop the registrations or both would print it — the pair
    // `CssParser::rewind_to` keeps together, for the same reason.
    // The span reaches the run's last item, a boundary run after its last word included, so
    // the printer's tail claim — which starts at the span's end — can never print it twice.
    let trailing_operators = run.finish().map(|(text, comments_len, source_end)| {
        parser.comments.truncate(comments_len);
        end_pos = end_pos.max(source_end as usize);
        parser.alloc_str_in(text)
    });

    let span = Span {
        start: start as u32,
        end: end_pos as u32,
    };

    Ok((
        ConditionQuery {
            parts: parts.into_bump_slice(),
            trailing_operators,
        },
        span,
    ))
}

/// What one `parse_condition_part` call produced.
enum ConditionPartOutcome<'arena> {
    /// A parsed part — `None` when its content came out empty, which records nothing
    /// but has still consumed tokens. `end` is the widened end position; `closed` is
    /// false only when the content ran to end-of-input without the part's own `)`.
    Parsed {
        part: Option<ConditionPart<'arena>>,
        end: usize,
        closed: bool,
    },
    /// The current token can't start a condition part. `consumed` is the `not` prefix
    /// the reader had already taken (with any comments after it) — the one thing it
    /// consumes before it can tell, and content the query owes back rather than drops;
    /// `None` on the ordinary path, where nothing was consumed. `end` is the widened end.
    NotAPart {
        consumed: Option<&'arena str>,
        end: usize,
    },
}

/// Parse one condition part — an optional leading `not`, an optional function name,
/// then the parenthesized content, whose tokens are re-emitted with the spacing the
/// grammar calls for (the space after a value `:`, the spacing around a boolean
/// operator), except where the grammar says they are a selector.
///
/// `end_pos` is the query's end position so far, widened by the part and handed back
/// in the outcome.
fn parse_condition_part<'arena>(
    parser: &mut CssParser<'_, 'arena>,
    connector: Option<ConnectorRun<'arena>>,
    mut end_pos: usize,
    reader: ConditionReader,
) -> Result<ConditionPartOutcome<'arena>, Error> {
    let part_start = parser.span_pos(parser.current_start());
    // One growable buffer instead of a `Vec<String>` of per-token / per-space pieces
    // joined at the end (mirrors `parse_raw_prelude_content` and
    // `parse_declaration`): tokens `push_str` straight in, separators are a single
    // `push(' ')`. `trailing_spaces` counts the trailing programmatic spaces (the
    // collapse unit) so `truncate` strips exactly those, never a token's own
    // escape-terminator space — the old `Vec` "last part is `\" \"`" test, exactly.
    let mut part_buf = String::new();
    // The part's content. Everything lands in `part_buf` and flushes to one `Text`
    // segment, except a `selector()` argument, which is parsed as a selector and
    // rides its own segment for the printer to hand to the selector printer.
    let mut segments = parser.bvec();
    let mut trailing_spaces: usize = 0;
    let mut paren_depth: usize = 0;
    // `Some(depth)` while inside a `selector()` argument the selector parse
    // declined — a `<general-enclosed>`, where the declaration rules below (the
    // value colon's spacing, boolean operators) must not fire.
    let mut general_enclosed_selector: Option<usize> = None;

    // Check for leading `not` (ASCII case-insensitive). Its source case is kept
    // (pushed verbatim), preserved by the printer like the `and`/`or` connectors.
    if parser.check(TokenKind::Identifier) {
        let ident = parser.current_identifier();
        if ident.eq_ignore_ascii_case("not") {
            part_buf.push_str(parser.current_value());
            // Widen over the keyword before consuming it: a `not` whose operand never
            // arrives is handed back to the query with this end (`NotAPart`), and the
            // query's span has to reach it.
            end_pos = parser.base_offset() + parser.current_end();
            parser.advance()?;
            // The gap after `not` is inside the part, so it rides the part's own text.
            // Comments go in the buffer rather than being registered, since they're inside
            // the condition part's span (e.g., `not /* comment */ (...)`). A boundary run
            // is stepped like the query's own gaps (`skip_gap_registering_comments`) and
            // spelled back in place, its comments with it: the gap holds nothing the
            // printer could reach from outside the part.
            let gap_start = parser.current_start();
            let not_end = part_buf.len();
            parser.skip_boundary_whitespace()?;
            while parser.check(TokenKind::Comment) {
                part_buf.push(' ');
                part_buf.push_str(parser.current_value());
                end_pos = parser.base_offset() + parser.current_end();
                parser.advance()?;
                parser.skip_boundary_whitespace()?;
            }
            let gap_end = parser.current_start();
            if holds_boundary_member(parser.source(), gap_start, gap_end) {
                part_buf.truncate(not_end);
                // `not` is a NAME, so the run behind it takes a space whatever the author
                // wrote (`not<NBSP>` would be one identifier); against what follows it
                // keeps the author's glue (`not <NBSP>(a: b)`).
                part_buf.push_str(&spell_run(
                    parser.source(),
                    gap_start,
                    gap_end,
                    false,
                    (Edge::Space, Edge::Presence),
                    Comments::Carried,
                ));
                trailing_spaces = usize::from(part_buf.ends_with(' '));
            } else {
                part_buf.push(' ');
                trailing_spaces = 1;
            }
        }
    }

    // Check for function-style condition like `selector(:has(...))`: an
    // identifier directly followed by `(`. The name is serialized verbatim from
    // source (escapes preserved) — only `and`/`or`/`not` keyword matches decode.
    let mut at_selector_args = false;
    if is_function_token(parser) {
        at_selector_args = at_selector_function(parser);
        part_buf.push_str(parser.current_value());
        trailing_spaces = 0;
        parser.advance()?;
        // Continue to parse the parenthesized part below
    }

    // Now parse the parenthesized condition
    if !parser.check(TokenKind::LeftParen) {
        // Not a valid @supports part, so the query ends here. Only the `not` prefix
        // above can have consumed anything by now (a function token is an identifier
        // glued to its `(`, so that branch always finds one); it goes back to the query
        // as the operator-with-no-operand it is, rather than being dropped with the
        // buffer.
        let consumed = (!part_buf.is_empty()).then(|| {
            parser
                .alloc_str_in(part_buf.trim_end_matches(crate::whitespace::is_boundary_whitespace))
        });
        return Ok(ConditionPartOutcome::NotAPart {
            consumed,
            end: end_pos,
        });
    }

    // Whether the part's own closing `)` was reached. False means the content ran
    // to end-of-input unterminated, which only the `supports()` caller cares about
    // (a condition prelude is bounded by the `{`/`;` its at-rule needs anyway).
    let mut closed = false;

    // Parse until we close all parens and hit whitespace/and/or/brace
    // Track state for whitespace normalization
    let mut prev_token_kind: Option<TokenKind> = None;
    // The previous token that can decide a spacing rule — whitespace and comments
    // are transparent to both readers (the value colon's space, and whether an
    // `and`/`or`/`not` sits where the grammar can start a boolean operator).
    let mut last_significant_kind: Option<TokenKind> = None;

    while !parser.check(TokenKind::Eof) {
        let opening_selector_args = at_selector_args;
        at_selector_args = false;

        // A `selector()` argument is a selector, not a declaration: parse it as
        // one so the printer can hand it to the selector printer, and the
        // declaration rules below never see its tokens. An argument that declines
        // to parse is a `<general-enclosed>` and falls through to the loop, which
        // consumes it as opaque text.
        if opening_selector_args && parser.check(TokenKind::LeftParen) {
            part_buf.push('(');
            trailing_spaces = 0;
            let paren_start = parser.span_pos(parser.current_start());
            parser.advance()?; // consume '('
            let arg_start = parser.current_start();
            let comments_len = parser.comments.len();
            if let Some(list) = parse_selector_argument(parser, arg_start, comments_len)? {
                if !part_buf.is_empty() {
                    segments.push(ConditionSegment::Text(parser.alloc_str_in(&part_buf)));
                    part_buf.clear();
                }
                let paren = Span {
                    start: paren_start,
                    end: parser.span_pos(parser.current_end()),
                };
                segments.push(ConditionSegment::Selectors { list, paren });
                // Seated on the closing `)`; the `(` it matches was consumed above,
                // so the two cancel and `paren_depth` never saw either.
                part_buf.push(')');
                end_pos = parser.base_offset() + parser.current_end();
                parser.advance()?;
                prev_token_kind = Some(TokenKind::RightParen);
                last_significant_kind = Some(TokenKind::RightParen);
                if paren_depth == 0 {
                    // The part *was* the `selector()` call, and its `)` just closed
                    // it (`@supports selector(a)`, no wrapping paren).
                    closed = true;
                    break;
                }
                continue;
            }
            // Rewound to the argument's first token: the `(` stays consumed, so
            // account for it and mark the region the declaration rules skip.
            paren_depth += 1;
            general_enclosed_selector.get_or_insert(paren_depth);
            prev_token_kind = Some(TokenKind::LeftParen);
            last_significant_kind = Some(TokenKind::LeftParen);
            continue;
        }

        // Track paren depth
        if parser.check(TokenKind::LeftParen) {
            paren_depth += 1;
        } else if parser.check(TokenKind::RightParen) {
            if paren_depth == 0 {
                break;
            }
            paren_depth -= 1;
            if general_enclosed_selector == Some(paren_depth + 1) {
                general_enclosed_selector = None;
            }
        }

        // Check for end of part (at top level)
        if paren_depth == 0 && parser.check(TokenKind::RightParen) {
            // Include the closing paren (loop ends here, so no counter reset needed)
            part_buf.push(')');
            end_pos = parser.base_offset() + parser.current_end();
            parser.advance()?;
            closed = true;
            break;
        }

        // Handle whitespace normalization
        if parser.check(TokenKind::Whitespace) {
            // A whitespace run right after a value colon (`(a: )`, empty value) is
            // the prettier-mandated single space after `:` — keep it before `)`
            // rather than dropping it, or `(a: )` would collapse to `(a:)` while
            // `(a:)` gains the space (the colon-space rule below), an F1 oscillation.
            // In `@supports`/`@container` a `:` is always a value colon.
            let after_value_colon = matches!(prev_token_kind, Some(TokenKind::Colon));
            let skip_whitespace = matches!(prev_token_kind, Some(TokenKind::LeftParen))
                || (matches!(parser.peek_kind(), Ok(TokenKind::RightParen)) && !after_value_colon);

            parser.advance()?;

            if skip_whitespace {
                continue;
            }
            part_buf.push(' ');
            trailing_spaces += 1;
            prev_token_kind = Some(TokenKind::Whitespace);
            continue;
        }

        let is_comment = matches!(parser.current_kind(), TokenKind::Comment);

        // Check if this is a boolean operator (and/or/not) inside nested parens.
        // Match on the decoded value, not the verbatim source slice, so an escaped
        // operator still spaces correctly — and only where the grammar can start
        // one, so an identifier that merely spells `and` keeps its own spacing.
        let is_bool_op = matches!(parser.current_kind(), TokenKind::Identifier)
            && is_boolean_operator_keyword(parser.current_identifier())
            && boolean_operator_position(
                last_significant_kind,
                general_enclosed_selector.is_some(),
            );

        // The next token opens a `selector()` argument, handled at the top of the
        // loop once its `(` is current.
        at_selector_args = at_selector_function(parser);

        // Two token kinds carry their own leading separator: a boolean operator, and a
        // comment (padded on **both** sides — the after side is handled once the token
        // is emitted, below; emitting only one leaves `(display: grid/* c */)`
        // half-spaced). They ask for it in ONE place, because two emission sites each
        // seeing only its own reason to pad is exactly how the doubled `/* c */  and`
        // arose. The comment's bound is `pads_comment`, which **both** of its sides
        // read for the same reason: inside a `<general-enclosed>` `selector()` argument
        // the tokens are opaque by grammar, so it is bounded like the value colon's rule
        // below — a space inserted inside a compound would turn
        // `selector([a=1.5]/* c */.b)` into a descendant `[a=1.5] .b`, and a bound only
        // one side honors inserts that space from the other. The operator's matching
        // bound rides inside `is_bool_op`, which its after-space reads too.
        let pads_comment = is_comment && general_enclosed_selector.is_none();
        let pads_before = is_bool_op || pads_comment;
        if pads_before && needs_separator_before(prev_token_kind, trailing_spaces) {
            part_buf.push(' ');
            trailing_spaces += 1;
        }

        // A comma is a SEPARATOR on the value reader, which regroups the value into its
        // own nodes and prints its own `, ` — so its left side is stripped below and its
        // right side padded further down, the same pair the value colon takes. Bounded
        // twice: `@container` is on neither of prettier's reader lists (its params are
        // verbatim, comma included), and inside a `<general-enclosed>` `selector()`
        // argument the comma separates a selector list the selector printer owns.
        let pads_comma = matches!(parser.current_kind(), TokenKind::Comma)
            && reader == ConditionReader::Value
            && general_enclosed_selector.is_none();

        // Remove trailing whitespace before a value ':' or a separator ',' — only the
        // counted programmatic spaces, never a token's own escape-terminator space. (The
        // counter is reset by the token emission just below, which always runs next.)
        // Inside a `<general-enclosed>` `selector()` argument the colon opens a
        // pseudo-class instead, where a preceding space is a descendant combinator:
        // `selector(div :hover)` is not `selector(div:hover)`. One statement of which
        // tokens strip, the `raw.rs` sibling's shape.
        let strips_leading_space = pads_comma
            || (matches!(parser.current_kind(), TokenKind::Colon)
                && general_enclosed_selector.is_none());
        if strips_leading_space {
            part_buf.truncate(part_buf.len() - trailing_spaces);
        }

        // Emit the token verbatim from source: identifiers serialize their raw slice so
        // escapes survive (`\@foo` stays `\@foo`), a string keeps its surrounding quotes,
        // and a comment is included verbatim.
        match parser.current_kind() {
            TokenKind::String { quote } => {
                let content =
                    &parser.source()[parser.current_start() + 1..parser.current_end() - 1];
                part_buf.push(quote);
                part_buf.push_str(content);
                part_buf.push(quote);
            }
            _ => part_buf.push_str(parser.current_value()),
        }
        trailing_spaces = 0;
        let current_kind = parser.current_kind();
        end_pos = parser.base_offset() + parser.current_end();
        parser.advance()?;

        // Add space after boolean operators — a separator to the operand the grammar
        // binds to their right (`and <supports-in-parens>`), so a `)` closing the group
        // means there is nothing to separate from and the space would strand before it
        // (`((a: b) and )`). The comment's own pad below reads the same `)`, and the
        // text path states the rule once more (`Printer::build_and_or_wrap_doc`).
        if is_bool_op
            && !parser.check(TokenKind::Whitespace)
            && !parser.check(TokenKind::RightParen)
        {
            part_buf.push(' ');
            trailing_spaces += 1;
        }

        // Add space after comment if followed by non-whitespace
        // (e.g., `/* comment */ grid` needs space before `grid`)
        if pads_comment
            && !parser.check(TokenKind::Whitespace)
            && !parser.check(TokenKind::RightParen)
        {
            part_buf.push(' ');
            trailing_spaces += 1;
        }

        // Add space after a value-reader comma — `pads_comma`, whose left-side strip
        // above is the same rule read from the other side. The space separates the comma
        // from the element after it, so a comma closing its group (`(x: a,)`, `fn(a,)`)
        // takes none: the whitespace arm above drops an authored run ahead of a `)`, and
        // a space written here would be read back as that run — the comma is kept, glued
        // to the `)`, the same bound the operator's and the comment's pads read.
        if pads_comma
            && !parser.check(TokenKind::Whitespace)
            && !parser.check(TokenKind::RightParen)
        {
            part_buf.push(' ');
            trailing_spaces += 1;
        }

        // Add space after ':' for property:value pairs — a value colon only. The
        // colon of a pseudo-class inside a `<general-enclosed>` argument binds the
        // name to it (`selector(div:hover)`), and spacing it makes a selector that
        // no longer parses.
        if !parser.check(TokenKind::Whitespace)
            && matches!(current_kind, TokenKind::Colon)
            && general_enclosed_selector.is_none()
            && matches!(
                last_significant_kind,
                Some(TokenKind::Identifier)
                    | Some(TokenKind::Number)
                    | Some(TokenKind::Dimension { .. })
                    | Some(TokenKind::Percentage)
            )
        {
            part_buf.push(' ');
            trailing_spaces += 1;
        }

        prev_token_kind = Some(current_kind);
        if !matches!(current_kind, TokenKind::Whitespace | TokenKind::Comment) {
            last_significant_kind = Some(current_kind);
        }
    }

    // Build the part. The buffer's outer whitespace is trimmed as one whole:
    // only the first and last segments can carry any, and both
    // are `Text` whenever a selector segment is present — the function name opens
    // the part and its `)` closes it.
    //
    // ⚠️ The trim's class is `is_boundary_whitespace`, **not** `str::trim`'s Unicode
    // `White_Space` — which excludes `U+FEFF`, where JS `\s` includes it. This gap is also
    // the one `build_condition_query_doc` restores a boundary run into, and the two have to
    // agree on where the part's text begins or the character belongs to both: a
    // `@container name <ZWNBSP>(a: b)` kept it inside the segment AND beside it, doubling the
    // run on every pass. Same lesson as the declaration's property→colon trim
    // (`trim_property_part`) — a printer-facing trim beside a boundary claim owes the claim's
    // class.
    if !part_buf.is_empty() {
        segments.push(ConditionSegment::Text(parser.alloc_str_in(&part_buf)));
    }
    if let Some(ConditionSegment::Text(first)) = segments.first_mut() {
        *first = first.trim_start_matches(crate::whitespace::is_boundary_whitespace);
    }
    if let Some(ConditionSegment::Text(last)) = segments.last_mut() {
        *last = last.trim_end_matches(crate::whitespace::is_boundary_whitespace);
    }
    let is_empty = segments
        .iter()
        .all(|segment| matches!(segment, ConditionSegment::Text(text) if text.is_empty()));
    let part = (!is_empty).then(|| ConditionPart {
        connector,
        segments: segments.into_bump_slice(),
        span: Span {
            start: part_start,
            end: end_pos as u32,
        },
    });

    Ok(ConditionPartOutcome::Parsed {
        part,
        end: end_pos,
        closed,
    })
}

/// Parse the argument of an `@import` prelude's `supports()` as the condition it is,
/// with the parser seated on the function's `(`.
///
/// `supports( <supports-condition> | <declaration> )` (css-cascade-5 §"Conditional
/// import rules") is the same grammar `@supports` takes, so the argument is read by
/// the same reader and printed by the same printer — one condition, one form,
/// wherever it appears. Seating on the `(` rather than past it is what makes that
/// work: **the function's own parentheses are the condition part's**, so the bare
/// `<declaration>` alternative (`supports(display: grid)`) reuses the
/// parenthesized-part grammar unchanged instead of needing a second reader.
///
/// Exactly one part can come of that (the parens wrap the whole argument), so this
/// never runs the query loop — which is also what bounds it to the function:
/// whatever follows the `)` is the caller's (`supports(a) screen`).
///
/// Returns with the parser just past the matching `)`, or `None` when the argument is
/// not a parenthesized part or never closed — the caller reports the unterminated
/// function.
pub(super) fn parse_supports_function_condition<'arena>(
    parser: &mut CssParser<'_, 'arena>,
) -> Result<Option<(ConditionQuery<'arena>, Span)>, Error> {
    let start = parser.base_offset() + parser.current_start();
    let ConditionPartOutcome::Parsed {
        part,
        end,
        closed: true,
    } = parse_condition_part(parser, None, start, ConditionReader::Value)?
    else {
        return Ok(None);
    };

    let mut parts = parser.bvec();
    if let Some(part) = part {
        parts.push(part);
    }
    Ok(Some((
        ConditionQuery {
            // The query loop never runs here, so nothing can go unbound: the one part is
            // the function's parenthesized argument, and an operator inside it is the
            // part's own text.
            parts: parts.into_bump_slice(),
            trailing_operators: None,
        },
        Span {
            start: start as u32,
            end: end as u32,
        },
    )))
}

/// Parse @container prelude into structured condition parts with optional name
///
/// CSS Syntax: `@container [<container-name>]? <container-query>`
/// where container-query is similar to @supports: `(prop: val)` parts connected by `and`/`or`
///
/// Examples:
/// - `(min-width: 100px)` - no name, single condition
/// - `(min-width: 100px) and (max-width: 200px)` - no name, conjunction
/// - `sidebar (min-width: 100px)` - named container
/// - `sidebar (min-width: 100px) and (max-width: 200px)` - named container with conjunction
pub(super) fn parse_container_prelude<'arena>(
    parser: &mut CssParser<'_, 'arena>,
) -> Result<(Option<&'arena str>, ConditionQuery<'arena>, Span), Error> {
    // A boundary run at the prelude's head is stepped before the name is read — it is no
    // name (`@container <NBSP> x (…)`) — and before the span begins, so the span opens on the
    // name, where the printer reads it from (`prelude.start + name.len()`). The printer claims
    // the run from the at-rule name's end.
    parser.skip_boundary_whitespace()?;
    let start = parser.span_pos(parser.current_start());

    // Check for optional container name: an identifier before the first '(' that
    // isn't a `not`/`and`/`or` keyword or a function call (`style(...)`, no space
    // before `(`). The keyword/function exclusion decodes + a structural `(`
    // lookahead; the stored name is serialized verbatim from source so escapes
    // survive (`\@named` stays `\@named`).
    let container_name = if parser.check(TokenKind::Identifier)
        && !is_function_token(parser)
        && !is_boolean_operator_keyword(parser.current_identifier())
    {
        // Copy into the arena only on the path that stores the name as a node.
        let name = parser.alloc_str_in(parser.current_value());
        parser.advance()?;
        // The name→condition gap is the query's first gap, so it steps the boundary class
        // too (`skip_gap_registering_comments`); the printer claims the run from the name.
        parser.skip_boundary_whitespace()?;
        Some(name)
    } else {
        None
    };

    // Now parse the condition (same grammar as @supports).
    let (condition, cond_span) = parse_condition_query(parser, ConditionReader::Raw)?;

    // The prelude span keeps the pre-name `start` and takes the condition's end,
    // so a named `@container foo (…)` covers the name while an unnamed one matches
    // `parse_condition_query` exactly.
    let span = Span {
        start,
        end: cond_span.end,
    };

    Ok((container_name, condition, span))
}

/// Parse one `@scope` clause — `(<forgiving-selector-list>)` — with the in-paren
/// leading/trailing gap comments registered (the printer re-emits them from the AST via
/// `comments_to_emit_in_range`, the same wrapping `:is()` args use). Assumes the current token
/// is `(`. The list is **forgiving** (css-cascade-6 makes `<scope-start>`/`<scope-end>`
/// `<forgiving-selector-list>`s, the same production `:is()`/`:where()` use), so an empty
/// or invalid list — `@scope ()`, `@scope (.a, , .b)`, `@scope (.)` — parses (each is
/// kept verbatim), matching parseCss (which captures the prelude raw) and prettier.
/// `what` names the clause for the unterminated-`)` error.
fn parse_scope_clause<'arena>(
    parser: &mut CssParser<'_, 'arena>,
    what: &str,
) -> Result<ScopeClause<'arena>, Error> {
    let paren_start = parser.span_pos(parser.current_start());
    parser.advance()?; // consume '('
    // Both gaps inside the parens step the boundary class (the list's own start and its
    // compound break step it too); the printer claims a run at either end back
    // (`Printer::build_paren_selector_list_inner`).
    parser.skip_boundary_whitespace_registering_comments()?; // leading comment
    let list = parse_forgiving_selector_list(parser)?;
    parser.skip_boundary_whitespace_registering_comments()?; // trailing comment
    if !parser.check(TokenKind::RightParen) {
        return Err(parser.error_expected_after("')'", what));
    }
    let paren_end = parser.span_pos(parser.current_end());
    parser.advance()?; // consume ')'
    Ok(ScopeClause {
        list,
        paren: Span {
            start: paren_start,
            end: paren_end,
        },
    })
}

/// Parse an @scope prelude into a `PreludeValue::Selectors`.
///
/// CSS Syntax (css-cascade-6): `@scope [(<scope-start>)]? [to (<scope-end>)]?` —
/// **both clauses are independently optional**, so all four combinations are valid
/// (parseCss accepts each): a bare `@scope { … }`, root-only, limit-only, and both.
///
/// Examples:
/// - `` (empty) - bare `@scope { … }`, scopes to the enclosing context
/// - `(.card)` - scope root only
/// - `(.card) to (.footer)` - scope root and limit
/// - `to (.footer)` - scope limit only
/// - `(article > header)` - with combinator
///
/// The span covers the authored prelude (first clause start to last `)`); when both
/// clauses are absent it is a zero-width span at the cursor, so the public AST's
/// `prelude` string extracts to `""` (matching parseCss).
pub(super) fn parse_scope_prelude<'arena>(
    parser: &mut CssParser<'_, 'arena>,
) -> Result<PreludeValue<'arena>, Error> {
    // Leading gap comments (`@scope /* c */ …`) register here: the shared at-rule
    // name skip in `parse_atrule` is a plain skip that stops at a comment, so a leading
    // comment is the current token on entry. Capturing `start` *after* this keeps it out
    // of the wire prelude (extracted from `span`), matching parseCss, which drops it.
    //
    // Every structural gap of the prelude — this one, between the clauses, after `to`, and
    // before the block — steps the BOUNDARY class, not ASCII whitespace alone: a run there
    // (`@scope <NBSP> (.a)`) is one the lexer reads as an identifier, which no clause starts
    // with, so an ASCII skip rejected a prelude `parseCss` stores as it stands. The printer
    // claims each gap back (`Printer::write_scope_prelude`).
    parser.skip_boundary_whitespace_registering_comments()?;
    let start = parser.span_pos(parser.current_start());
    // Widens to each clause's closing `)`; stays at `start` when no clause is present.
    let mut end = start;

    // Optional root clause `(<scope-start>)`. After it, the between-clause (`) /* c */ to`)
    // and pre-`{` gaps register their comments so the printer can re-emit them.
    let root = if parser.check(TokenKind::LeftParen) {
        let clause = parse_scope_clause(parser, "@scope root selectors")?;
        end = clause.paren.end;
        parser.skip_boundary_whitespace_registering_comments()?; // between-clause / pre-`{` gap
        Some(clause)
    } else {
        None
    };

    // Optional limit clause `to (<scope-end>)` — valid with or without a root. `to` is a
    // case-insensitive grammar keyword (lowercased at the printer's ` to ` literal); its
    // span lets the printer tell a between-clause comment (before `to`) from an after-`to`
    // one. The after-`to` and pre-`{` gaps register comments the same way.
    let limit = if let Some(to_len) = scope_to_keyword_len(parser) {
        let to_start = parser.current_start();
        let to_span = Span {
            start: parser.span_pos(to_start),
            end: parser.span_pos(to_start + to_len),
        };
        // Consume `to` — up to a run glued to it, which ends the keyword where `parseCss`'s
        // JS-`\s` reading ends it, and is left standing for the gap's skip below.
        parser.advance_from(to_start + to_len)?;
        parser.skip_boundary_whitespace_registering_comments()?; // after-`to` gap
        if !parser.check(TokenKind::LeftParen) {
            return Err(parser.error_expected_after("'('", "'to' in @scope prelude"));
        }
        let clause = parse_scope_clause(parser, "@scope limit selectors")?;
        end = clause.paren.end;
        parser.skip_boundary_whitespace_registering_comments()?; // pre-`{` gap
        Some(ScopeLimit { to_span, clause })
    } else {
        None
    };

    Ok(PreludeValue::Selectors {
        root,
        limit,
        span: Span { start, end },
    })
}

/// The byte length of the `@scope` limit clause's `to` keyword at the current token, or `None`
/// when the token is not one.
///
/// `to` is ASCII case-insensitive, and it ends where a boundary run begins: `to<NBSP>` is one
/// identifier to the lexer (and to css-syntax-3, which reads the run as identifier content),
/// but the keyword the prelude reader is looking for is the `to` ahead of the run, which
/// `parseCss` stores in its raw prelude either way. Reading it there is what keeps
/// `(.a) to<NBSP>(.b)` a limit clause — the printer spells the run back glued to the keyword,
/// as authored. The split is `whitespace::boundary_split_offset`, the attribute value's.
fn scope_to_keyword_len(parser: &CssParser<'_, '_>) -> Option<usize> {
    if !parser.check(TokenKind::Identifier) {
        return None;
    }
    if parser.current_identifier().eq_ignore_ascii_case("to") {
        return Some(parser.current_end() - parser.current_start());
    }
    let text = &parser.source()[parser.current_start()..parser.current_end()];
    let split = crate::whitespace::boundary_split_offset(text)?;
    text[..split].eq_ignore_ascii_case("to").then_some(split)
}

/// Parse a `@custom-selector` prelude into a `PreludeValue::CustomSelector`, or fall back
/// to the verbatim raw prelude when it is not one.
///
/// css-extensions-1: `@custom-selector = @custom-selector <custom-selector> <selector-list> ;`
/// with `<custom-selector> = <custom-arg>? : <extension-name> [ ( <custom-arg>+# ) ]?` and
/// "no whitespace between `:` and `<extension-name>`". tsv structures the shape that is
/// implemented (postcss-preset-env) and that prettier routes: a `:` glued to a `--`-led
/// ident, a whitespace or comment gap, then a strict `<complex-selector-list>` — the
/// gap is what separates the name from a list that begins with a pseudo-class, since
/// `:--x:hover` would otherwise read as one compound. Prettier's arm is the same split
/// (`params.match(/:--\S+\s+/)`, the rest to `parseSelector`); the `$arg` forms are
/// draft-only and take the fallback.
///
/// The fallback is a **rewind and replay** of the raw reader, not a reconsume: the
/// selector parser registers the comments it steps over, and a comment registered by an
/// abandoned parse would print twice (once from the raw `content`, once from the gap
/// sweep — `rewind_to`'s own contract). Nothing here rejects: an at-rule prelude is
/// consumed as component values whatever they are (CSS Syntax 3) and `parseCss` stores
/// any prelude raw, so a name with nothing after it (`@custom-selector :--a;`), a list
/// with no name, or a list the strict parser rejects is kept verbatim. The span is the
/// raw reader's in both arms — first token to the terminator — so the wire prelude is the
/// same bytes either way.
pub(super) fn parse_custom_selector_prelude<'arena>(
    parser: &mut CssParser<'_, 'arena>,
) -> Result<PreludeValue<'arena>, Error> {
    // The raw offset the replay restarts from, and the registrations it discards.
    let prelude_start_raw = parser.current_start();
    let comments_len = parser.comments.len();
    let span_start = parser.span_pos(prelude_start_raw);

    if let Some((name, list)) = parse_custom_selector_head_and_list(parser)? {
        // Trailing gap: `h2 /* c */;` — the selector parser leaves a comment before the
        // terminator unconsumed (a rule's pre-brace comment is its caller's), so register
        // it here for the printer's trailing sweep.
        parser.skip_whitespace_registering_comments()?;
        if parser.at_prelude_end() {
            let span = Span {
                start: span_start,
                end: parser.span_pos(parser.current_start()),
            };
            return Ok(PreludeValue::CustomSelector { name, list, span });
        }
    }

    parser.rewind_to(prelude_start_raw, comments_len)?;
    let (content, span) = super::raw::parse_raw_prelude_content(parser, false, false)?;
    Ok(PreludeValue::Raw { content, span })
}

/// The structured half of `parse_custom_selector_prelude`: the `:--name`, its gap, and
/// the list. `None` for any prelude that is not that shape, leaving the parser wherever
/// the mismatch was found — the caller rewinds.
fn parse_custom_selector_head_and_list<'arena>(
    parser: &mut CssParser<'_, 'arena>,
) -> Result<Option<(Span, SelectorList<'arena>)>, Error> {
    // Leading gap: `@custom-selector /* c */ :--a` (the shared name skip in `parse_atrule`
    // is a plain whitespace skip, so a leading comment is the current token on entry). It
    // steps the boundary class like every structural prelude gap, or a run there
    // (`@custom-selector <NBSP> :--a`) is an identifier where the `:` is due and the prelude
    // falls to the verbatim path; the printer claims it back.
    parser.skip_boundary_whitespace_registering_comments()?;

    // `:` glued to a `--`-led identifier. The lexer emits the two as separate tokens, so
    // the glue is the ident starting at the colon's end. The `--` test reads the DECODED
    // ident (an `<extension-name>` is "any identifier that starts with two dashes", and an
    // escape's payload is ident content — `\-\-a` is the name `--a`); the span the printer
    // emits keeps the author's spelling.
    if !parser.check(TokenKind::Colon) {
        return Ok(None);
    }
    let name_start = parser.span_pos(parser.current_start());
    let colon_end = parser.current_end();
    parser.advance()?;
    if !parser.check(TokenKind::Identifier)
        || parser.current_start() != colon_end
        || !parser.current_identifier().starts_with("--")
    {
        return Ok(None);
    }
    let name = Span {
        start: name_start,
        end: parser.span_pos(parser.current_end()),
    };
    parser.advance()?;

    // The name→list gap must hold whitespace or a comment: the list may open with a
    // pseudo-class, and `:--x:hover` is one compound, not a name and a list.
    let before = parser.comments.len();
    let saw_whitespace = parser.skip_boundary_whitespace_registering_comments()?;
    if !saw_whitespace && parser.comments.len() == before {
        return Ok(None);
    }
    if parser.at_prelude_end() {
        return Ok(None);
    }

    // Strict list (`<selector-list>` — not the forgiving production `:is()` takes): a
    // list the selector parser rejects is not structured, it is kept as authored.
    match parse_complex_selector_list(parser) {
        Ok(list) => Ok(Some((name, list))),
        // a depth limit is no verdict on the list (see `parse_forgiving_selector_list`)
        Err(error) if error.kind() == tsv_lang::ErrorKind::TooDeep => Err(error),
        Err(_) => Ok(None),
    }
}

/// Parse an `@import` prelude into structured values.
///
/// CSS Syntax (css-cascade-5 §"Importing Style Sheets"):
/// `@import [ <url> | <string> ] [ layer | layer(<layer-name>) ]? <import-conditions> ;`
///
/// Examples:
/// - `url('styles.css')`
/// - `'styles.css'`
/// - `url('tabs.css') layer(framework)`
/// - `url('override.css') layer`
/// - `url('narrow.css') supports(display: flex) screen`
/// - `url('a.css') screen and (min-width: 5px)` (media-type-led query)
/// - `url('b.css') (max-width: 40px)` (bare `<media-condition>` query)
///
/// The grammar is a guide to what gets *structured*, not to what gets *accepted*. Per
/// CSS Syntax 3 an at-rule prelude is consumed as component values whatever they are —
/// an `@import` that matches no grammar is dropped at cascade, never a parse error — and
/// `parseCss` (the parity oracle) stores any prelude raw. So the reader is in two parts:
/// a **structured head** — a run of functions (`url()`, `layer()`, `supports()`, any
/// other) and the bare `layer` keyword, which may open with a `<string>` or an unquoted
/// `<url-token>` — and one **verbatim tail** from the first token the head does not own to
/// the prelude end (`{`, `;`, EOF), the text recovered from `span` at print time. The tail
/// is where the `<media-query-list>` lives, and it is also where anything else lands: a
/// number, a hex colour, a `url()`, a string, a stray `)`. Prettier reads the whole prelude
/// through `parseValue`, so the printer runs the value reader's normalization over the
/// tail wherever it starts — a prelude with no url/string (`@import 1E3;`) is *all* tail
/// and normalizes exactly as the same token after a url (`@import 'a.css' 1E3;`) or after
/// a media type (`@import 'a.css' screen 1E3;`). Only a prelude with nothing in it but
/// whitespace and comments (`@import;`, `@import /* c */;`) takes the raw fallback, since
/// a tail needs a token to start at.
///
/// A leading `,` starts the tail too: mediaqueries-4 §Syntax parses a `<media-query-list>`
/// by parsing "a comma-separated list of component values, then parsing each entry as a
/// `<media-query>`", so an entry that matches no `<media-query>` — an empty one included —
/// is a grammar mismatch that §"Error Handling" replaces with `not all`, never a parse
/// error.
pub(super) fn parse_import_prelude<'arena>(
    parser: &mut CssParser<'_, 'arena>,
) -> Result<PreludeValue<'arena>, Error> {
    // Raw offset of the prelude's first token, for the raw fallback below.
    let prelude_start_raw = parser.current_start();
    let start = parser.span_pos(parser.current_start());
    let mut values = parser.bvec();

    // Register a leading comment between `@import` and the first value (e.g.
    // `@import /* c */ url(...)`). Svelte strips it from the prelude string; the printer
    // reconstructs it from `self.comments`. This gap, and each one between the head's values
    // below, steps the boundary class: a run there (`@import <NBSP> 'a.css'`) is an
    // identifier to the lexer, and read as one it opened the verbatim tail — the head's
    // string or url then never normalized. The printer claims the run back
    // (`Printer::write_import_gap_comments`).
    parser.skip_boundary_whitespace_registering_comments()?;

    if parser.at_prelude_end() {
        // Nothing but whitespace and comments (`@import;`, `@import /* c */;`): no token
        // for a tail to start at. Reconsume as a raw prelude — zero-width for the empty
        // case (→ `""`), and carrying the comment verbatim otherwise, as `parseCss` does.
        return super::reconsume_prelude_as_raw(parser, prelude_start_raw);
    }

    // The two head openers the loop below does not take: a bare string, and an unquoted
    // url-token. A function opens the head through the loop like any later one.
    if let TokenKind::String { .. } = parser.current_kind() {
        // Bare string — the inner text is recovered verbatim from `span` at print time
        // (span-for-verbatim, zero alloc); the quote char from `source[span.start]`.
        let value_start = parser.span_pos(parser.current_start());
        let value_end = parser.span_pos(parser.current_end());
        values.push(CssValue::String {
            content: StringCooked::Verbatim,
            span: Span {
                start: value_start,
                end: value_end,
            },
        });
        parser.advance()?;
    } else if matches!(parser.current_kind(), TokenKind::Url)
        && !url_token_has_unclosed_paren(
            &parser.source()[parser.current_start()..parser.current_end()],
        )
    {
        // Unquoted `url(...)` — the lexer consumed it as one opaque `<url-token>`. Mirror
        // `parse_function_value`'s empty-args url shape (name + span): the printer and the
        // public-AST conversion reconstruct the verbatim, inner-ws-trimmed `url(...)` from
        // the function span, so structured `@import url(…) layer/supports/media` wrapping
        // still works (unlike the tail, which would keep it as text).
        //
        // A url-token with a *nested* `(` (e.g. `url(a(b))`) is excluded above: the lexer
        // stops the url scan at the first unescaped `)` (css-syntax §4.3.6), truncating the
        // token to `url(a(b)` and leaving a dangling `)`, so the structured split would
        // reject at the trailing `)`. parseCss reads such a prelude raw to `;` (and prettier
        // prints it verbatim), so it goes to the tail below — the same verbatim text
        // `@namespace url(a(b))` takes.
        let value_start = parser.span_pos(parser.current_start());
        let value_end = parser.span_pos(parser.current_end());
        // The name is the token text up to its `(` — the ident that opened the url-token,
        // so the `(` is the first one in it. The printer reads this span only as a
        // url-detection key (`function_name_is(.., "url")`, which decodes an escaped
        // spelling); the emitted text and the public AST both come from `span`, so real
        // casing and content are preserved regardless.
        let name_len = parser
            .current_value()
            .bytes()
            .position(|b| b == b'(')
            .unwrap_or(0);
        // A url-token exists only because the lexer read an ident and then a `(`
        // (`read_identifier`), so the `(` is always there; the `unwrap_or` degrades to an
        // empty name span, which simply fails the url test and prints the span verbatim.
        debug_assert!(
            name_len > 0,
            "a url-token with no `(`: {:?}",
            parser.current_value()
        );
        values.push(CssValue::Function {
            name_span: Span {
                start: value_start,
                end: value_start + name_len as u32,
            },
            args: &[],
            span: Span {
                start: value_start,
                end: value_end,
            },
        });
        parser.advance()?;
    }

    // The structured head: `url()` / `layer()` / `supports()` (any function) and the bare
    // `layer` keyword. The first token that is neither starts the tail.
    parser.skip_boundary_whitespace_registering_comments()?;
    while !parser.at_prelude_end() {
        if is_function_token(parser) {
            values.push(parse_function_value(parser)?);
        } else if parser.check(TokenKind::Identifier) && parser.current_identifier() == "layer" {
            // Bare "layer" keyword (without function call); text recovered from
            // `span` at print time (span-for-verbatim).
            let value_start = parser.span_pos(parser.current_start());
            let value_end = parser.span_pos(parser.current_end());
            values.push(CssValue::Identifier {
                span: Span {
                    start: value_start,
                    end: value_end,
                },
            });
            parser.advance()?;
        } else {
            break;
        }
        parser.skip_boundary_whitespace_registering_comments()?;
    }

    // The tail: everything from here to the prelude end, verbatim, with its original
    // whitespace — one `Identifier` value the printer normalizes as a whole (the media
    // condition is the common content; see the doc comment). Its end is the last
    // non-whitespace token's, so the value's span (and the wire prelude read from it)
    // is outer-trimmed like every other prelude.
    if !parser.at_prelude_end() {
        let tail_local_start = parser.current_start();
        let tail_start = parser.span_pos(tail_local_start);
        let mut tail_local_end = parser.current_end();

        while !parser.at_prelude_end() {
            if !parser.check(TokenKind::Whitespace) {
                tail_local_end = parser.current_end();
            }
            parser.advance()?;
        }

        values.push(CssValue::Identifier {
            span: Span {
                start: tail_start,
                end: parser.span_pos(tail_local_end),
            },
        });
    }

    let end = values.last().map_or(start, |v| v.span().end);

    Ok(PreludeValue::Values {
        values: values.into_bump_slice(),
        span: Span { start, end },
    })
}

/// Whether an unquoted `<url-token>`'s text has an unclosed `(` — i.e. the lexer stopped
/// the url scan at the first unescaped `)` (css-syntax §4.3.6) *inside* a nested group, so
/// the token is a truncated `url(a(b)` rather than a balanced `url(...)`. Escape-aware: a
/// `\(` / `\)` is literal url content, not a paren delimiter (matching the lexer's own
/// scan), so `url(a\(b)` (balanced) and `url(a\)b)` (escaped close) both read as closed.
fn url_token_has_unclosed_paren(text: &str) -> bool {
    let mut depth: u32 = 0;
    let mut chars = text.chars();
    while let Some(c) = chars.next() {
        match c {
            '\\' => {
                chars.next(); // the escaped code point is content, never a delimiter
            }
            '(' => depth += 1,
            ')' => depth = depth.saturating_sub(1),
            _ => {}
        }
    }
    depth > 0
}

/// Consume a run of whitespace and comments, returning the run's comments as one
/// outer-trimmed span (`None` when it held none, which is the overwhelmingly common case
/// and leaves this a plain `skip_whitespace`).
///
/// The span is handed to a `CssValue::Identifier`, whose printer runs the comment-aware
/// `normalize_css_whitespace` over it — so a two-comment run comes back single-spaced like
/// every other CSS comment run. The comments are deliberately **not** registered (see
/// [`CssParser::skip_boundary_whitespace_and_comments`]): the span re-emits them verbatim, and
/// registering would additionally offer them to the `@import` prelude's gap emitters, which
/// print between the parsed values — outside this function, where they would print twice.
fn take_comment_run(parser: &mut CssParser<'_, '_>) -> Result<Option<Span>, Error> {
    let mut start = None;
    let mut end = 0u32;
    loop {
        if parser.check(TokenKind::Whitespace) {
            parser.advance()?;
        } else if parser.check(TokenKind::Comment) {
            start.get_or_insert_with(|| parser.span_pos(parser.current_start()));
            end = parser.span_pos(parser.current_end());
            parser.advance()?;
        } else {
            break;
        }
    }
    Ok(start.map(|start| Span { start, end }))
}

/// Consume a function's argument list up to — but not including — its **matching** `)`,
/// returning the arguments' outer-trimmed span (`None` when the region held nothing but
/// whitespace).
///
/// Per CSS Syntax 3 §"consume a function" the contents are a component-value list, so a
/// nested `(…)`/`fn(…)` must not end the list at its first inner `)` — hence the depth
/// count. Whitespace is trimmed off both ends; a **comment** is not, because it is content
/// this region re-emits rather than a separator: §4.3.2 `consume comments` returns nothing,
/// which makes a comment transparent to the *grammar* while it still occupies the text.
///
/// Those comments are deliberately left **unregistered** (see
/// [`CssParser::skip_boundary_whitespace_and_comments`], whose doc states the rule): the span
/// re-emits them verbatim, and registering would additionally offer them to the `@import`
/// prelude's gap emitters, which print *between* the parsed values — outside this
/// function, where they would print a second time.
///
/// The single definition of how far a prelude function's arguments reach — the `layer()`
/// arm reads the span, the `<general-enclosed>` arm only needs the seek.
fn consume_function_args(parser: &mut CssParser<'_, '_>) -> Result<Option<Span>, Error> {
    let mut start = None;
    let mut end = 0u32;
    let mut depth: u32 = 0;
    while !parser.check(TokenKind::Eof) {
        match parser.current_kind() {
            TokenKind::RightParen if depth == 0 => break,
            TokenKind::LeftParen => depth += 1,
            TokenKind::RightParen => depth -= 1,
            _ => {}
        }
        if !parser.check(TokenKind::Whitespace) {
            start.get_or_insert_with(|| parser.span_pos(parser.current_start()));
            end = parser.span_pos(parser.current_end());
        }
        parser.advance()?;
    }
    Ok(start.map(|start| Span { start, end }))
}

/// Parse a function value (e.g., url(), layer(), supports())
fn parse_function_value<'arena>(
    parser: &mut CssParser<'_, 'arena>,
) -> Result<CssValue<'arena>, Error> {
    let value_start = parser.span_pos(parser.current_start());

    // Get function name (current token should be identifier). Kept verbatim from
    // source so the author's case survives to output; every *recognition* test below
    // is ASCII case-insensitive instead ("like keywords, function names are ASCII
    // case-insensitive" — css-values-4 §"Functional Notations"), so `SUPPORTS(a:b)`
    // and `LAYER( a )` normalize like their lowercase spellings rather than falling
    // through to the opaque unknown-function path.
    let name = if parser.check(TokenKind::Identifier) {
        parser.current_identifier_in_arena()
    } else {
        return Err(parser.error_expected("function name"));
    };
    // Recognition below is on the DECODED `name` (`\6c ayer(` is a `layer()`), but what
    // reaches the output is the author's own bytes: the value subtree is source-faithful,
    // so the stored name is this span, never the decoded text (prettier preserves the
    // escape too).
    let name_span = Span {
        start: parser.span_pos(parser.current_start()),
        end: parser.span_pos(parser.current_end()),
    };
    // `supports()` keeps a text name (its printer prints the condition, not a span), so
    // the same fact reaches it as the verbatim token slice — the copy is an `@import`
    // prelude's alone.
    let name_verbatim = parser.alloc_str_in(parser.current_value());

    parser.advance()?; // consume function name

    // Expect '('
    if !parser.check(TokenKind::LeftParen) {
        return Err(parser.error_expected_after("'('", "function name"));
    }

    // `supports()` is read *before* the `(` is consumed: that paren is the condition
    // part's own opening paren (see `parse_supports_function_condition`), which is what
    // lets the bare `<declaration>` alternative reuse the parenthesized-part grammar.
    if name.eq_ignore_ascii_case("supports") {
        let Some((condition, condition_span)) = parse_supports_function_condition(parser)? else {
            return Err(parser.error_expected("')' to close function"));
        };
        return Ok(CssValue::SupportsCondition {
            name: name_verbatim,
            condition,
            span: Span {
                start: value_start,
                end: condition_span.end,
            },
        });
    }

    parser.advance()?; // consume '('

    // For @import functions (url, layer, supports), parse arguments based on function type
    let mut args = parser.bvec();

    if name.eq_ignore_ascii_case("url") {
        // url() - parse the URL argument (string or bare URL)
        parser.skip_whitespace()?;
        if let TokenKind::String { .. } = parser.current_kind() {
            let arg_start = parser.span_pos(parser.current_start());
            let arg_end = parser.span_pos(parser.current_end());
            // Bare string arg — inner text recovered verbatim from `span` at print
            // time (span-for-verbatim, zero alloc); quote char from `source[span.start]`.
            args.push(CssValue::String {
                content: StringCooked::Verbatim,
                span: Span {
                    start: arg_start,
                    end: arg_end,
                },
            });
            parser.advance()?;
            // A comment may TRAIL the quoted argument (CSS Syntax 3 §4.3.2: a comment
            // yields no token, so it is transparent to the grammar). It is carried as its
            // own region rather than skipped, which keeps the argument on the structured
            // string path — and with it the quote normalization (`"a.css"` → `'a.css'`)
            // that the opaque bare-URL path would have lost. Before this it reached no arm
            // at all: it fell past the argument into the `)` check below and rejected the
            // whole stylesheet.
            //
            // Only the trailing side needs this. A *leading* comment never arrives here:
            // `consume_url_token` classifies `url(` as a function-token only when a QUOTE
            // follows (past whitespace — a comment is not whitespace, css-syntax §4.3.4),
            // so a leading comment makes the whole thing an opaque `<url-token>` whose
            // contents this function never sees.
            args.extend(take_comment_run(parser)?.map(|span| CssValue::Identifier { span }));
        } else {
            // Unquoted bare URL (`url(a.css)`, `url(a.css?x=1)`): an opaque token run
            // up to ')'. Leave args empty — both the public-AST conversion and the
            // printer reconstruct the `url(...)` verbatim from the function span.
            while !parser.check(TokenKind::RightParen) && !parser.check(TokenKind::Eof) {
                parser.advance()?;
            }
        }
    } else if name.eq_ignore_ascii_case("layer") {
        // `layer(<layer-name>)` — css-cascade-5 §layer-names spells the argument
        // `<ident> [ '.' <ident> ]*`, so the DOTTED form is the primary one and a single
        // identifier token cannot bound it. Reading one and stopping made every other
        // spelling a parse ERROR — `layer(a.b)` among them — rejecting the whole stylesheet
        // where `parseCss` and prettier both accept.
        //
        // The argument is therefore one region (`consume_function_args`, which owns the
        // reach rule), carried as a single `Identifier`. That routes it through
        // `build_identifier_doc`'s comment-aware `normalize_css_whitespace`, which is where
        // `layer(  a.b  )` → `layer(a.b)` comes from and which spaces a glued `a./* c */b`
        // to `a. /* c */ b` — prettier's value-parse answer, so this whole family matches.
        // A whitespace-only argument (`layer()`) yields `None`, leaving `args` empty and
        // routing the printer to its verbatim function span, the form this arm already
        // produced.
        args.extend(consume_function_args(parser)?.map(|span| CssValue::Identifier { span }));
    } else {
        // Other unknown functions (e.g. `scope((.a) to (.b))`, css-cascade-6 scoped
        // `@import`) — consume the args opaquely. Args stay empty: the printer and the
        // public-AST conversion both reconstruct the function verbatim from its span, so
        // the region's bounds are needed only to find the closing `)`.
        consume_function_args(parser)?;
    }

    if !parser.check(TokenKind::RightParen) {
        return Err(parser.error_expected("')' to close function"));
    }

    let value_end = parser.span_pos(parser.current_end());
    parser.advance()?; // consume ')'

    Ok(CssValue::Function {
        name_span,
        args: args.into_bump_slice(),
        span: Span {
            start: value_start,
            end: value_end,
        },
    })
}