oxc-css-parser 0.0.4

Parser for CSS, SCSS, Sass, and Less.
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
use super::{
    Parser,
    state::{ParserState, QualifiedRuleContext},
};
use crate::{
    Parse, Syntax,
    ast::*,
    error::{Error, ErrorKind, PResult},
    pos::Span,
    tokenizer::{Token, TokenWithSpan},
};

impl<'a> Parse<'a> for Declaration<'a> {
    fn parse(input: &mut Parser<'a>) -> PResult<Self> {
        // Legacy IE hacks glued to the property name: `*color: red` targets
        // IE<=7; dart-sass's plain-CSS parser additionally accepts `:x`, `.x`
        // and `#x` prefixes. Keep them as a property-name prefix — but only
        // when glued: `* color` (whitespace or a comment after the sigil) is
        // not the hack, so leave the token for the normal (failing) parse.
        let mut name_prefix = if input.state.allow_ie_star_hack
            && let TokenWithSpan { token, span } = input.cursor.peek()?
            && let Some(prefix) = match token {
                Token::Asterisk(..) => Some('*'),
                Token::Dot(..) if input.syntax == Syntax::Css => Some('.'),
                Token::Colon(..) if input.syntax == Syntax::Css => Some(':'),
                _ => None,
            }
            && input
                .source
                .as_bytes()
                .get(span.end)
                .is_some_and(|b| !b.is_ascii_whitespace() && *b != b'/')
        {
            let start = span.start;
            input.cursor.bump()?;
            Some((start, prefix))
        } else {
            None
        };
        // A css-in-js `${}` placeholder may stand in for the property name
        // (`${foo}: ${bar}`); it is not a real ident, so accept it directly.
        let name = if let Token::Placeholder(..) = input.cursor.peek()?.token {
            let (placeholder, span) = input.cursor.expect_placeholder()?;
            InterpolableIdent::Placeholder((placeholder, span).into())
        } else if input.state.allow_ie_star_hack
            && input.syntax == Syntax::Less
            && let TokenWithSpan { token: Token::Number(number), span } = input.cursor.peek()?
            && number.raw.bytes().all(|b| b.is_ascii_digit())
        {
            let raw = number.raw;
            let span = span.clone();
            input.cursor.bump()?;
            InterpolableIdent::Literal(Ident { name: raw, raw, span })
        } else if name_prefix.is_none()
            && input.state.allow_ie_star_hack
            && input.syntax == Syntax::Css
            && matches!(input.cursor.peek()?.token, Token::Hash(..))
        {
            // `#x: y` — the `#` and the name arrive as one <hash-token>.
            let TokenWithSpan { token: Token::Hash(hash), span } = input.cursor.bump()? else {
                unreachable!()
            };
            name_prefix = Some((span.start, '#'));
            let name = if hash.escaped {
                crate::util::handle_escape_in(hash.raw, input.allocator)
            } else {
                hash.raw
            };
            InterpolableIdent::Literal(Ident {
                name,
                raw: hash.raw,
                span: Span { start: span.start + 1, end: span.end },
            })
        } else {
            input
                .with_state(ParserState {
                    qualified_rule_ctx: Some(QualifiedRuleContext::DeclarationName),
                    ..input.state
                })
                .parse::<InterpolableIdent>()?
        };

        // https://tailwindcss.com/docs/theme#overriding-the-default-theme
        let name_suffix = if let TokenWithSpan { token: Token::Asterisk(..), span } =
            input.cursor.peek()?
            && name.span().end == span.start
        {
            input.cursor.bump()?;
            Some('*')
        } else {
            None
        };

        // Less property merge (`prop+: v`, `prop+_: v`) — also accepted for
        // plain CSS since Less serializes the flag into its output.
        let less_property_merge =
            if matches!(input.syntax, Syntax::Less | Syntax::Css) { input.parse()? } else { None };

        let (_, colon_span) = input.cursor.expect_colon()?;
        let (mut value, mut important) = {
            let mut parser = input.with_state(ParserState {
                qualified_rule_ctx: Some(QualifiedRuleContext::DeclarationValue),
                ..input.state
            });
            match &name {
                InterpolableIdent::Literal(ident)
                    if ident.name.starts_with("--")
                        || matches!(
                            &parser.cursor.peek()?.token,
                            // for IE-compatibility, regardless of the property
                            // name (`filter`, `-ms-filter`, vendor variants...):
                            // filter: progid:DXImageTransform.Microsoft...
                            Token::Ident(ident) if ident.name().eq_ignore_ascii_case("progid")
                        ) =>
                'value: {
                    if parser.options.try_parsing_value_in_custom_property
                        && let Ok(values) = parser.try_parse(Parser::parse_declaration_value)
                    {
                        break 'value (values, None);
                    }
                    (parser.parse_declaration_value_tokens(false)?, None)
                }
                // In CSS, a declaration value is any sequence of component
                // values (CSS Syntax §5): serialized selectors (`b: .c > d`),
                // map-like blocks (`b: (3: 4)`), or stray delimiters are all
                // valid preserved tokens even though the typed grammar has no
                // node for them. Try the typed grammar first; if it fails, or
                // succeeds without accounting for everything up to the
                // declaration terminator, re-parse the whole value as raw
                // tokens. Scss/Sass/Less keep the strict grammar: their
                // dialects assign meaning to these tokens and are expected to
                // reject exactly what their reference compilers reject.
                _ if parser.syntax == Syntax::Css
                    || (parser.state.in_css_function_body
                        && matches!(&name, InterpolableIdent::Literal(..))) =>
                {
                    let typed = parser.try_parse(|p| {
                        let values = p.parse_declaration_value()?;
                        let important = match &p.cursor.peek()?.token {
                            Token::Exclamation(..) => Some(p.parse::<ImportantAnnotation>()?),
                            _ => None,
                        };
                        let next = p.cursor.peek()?;
                        if at_declaration_value_end(&next.token) {
                            Ok((values, important))
                        } else {
                            Err(Error {
                                kind: ErrorKind::ExpectComponentValue,
                                span: next.span.clone(),
                            })
                        }
                    });
                    match typed {
                        Ok(value_and_important) => value_and_important,
                        Err(error) => {
                            // A CSS custom function body holds declarations
                            // only, so a top-level `{}` there is part of the
                            // value; elsewhere it means this construct is
                            // really a qualified rule (CSS Nesting
                            // disambiguation) and the declaration is rejected.
                            let in_fn_body = parser.state.in_css_function_body;
                            let values = parser.parse_declaration_value_tokens(!in_fn_body)?;
                            if !in_fn_body && let Token::LBrace(..) = &parser.cursor.peek()?.token {
                                return Err(error);
                            }
                            (values, None)
                        }
                    }
                }
                _ => (parser.parse_declaration_value()?, None),
            }
        };

        if important.is_none()
            && let Token::Exclamation(..) = &input.cursor.peek()?.token
        {
            important = Some(input.parse::<ImportantAnnotation>()?);
        }
        // dart-sass allows `!important` mid-value (`fludge: foo bar
        // !important hux;`): when more value follows, the annotation is just
        // another component, and only a trailing one is structural.
        while matches!(input.syntax, Syntax::Scss | Syntax::Sass)
            && important.is_some()
            && !at_declaration_value_end(&input.cursor.peek()?.token)
        {
            if let Some(annotation) = important.take() {
                value.push(ComponentValue::ImportantAnnotation(annotation));
            }
            let more = input
                .with_state(ParserState {
                    qualified_rule_ctx: Some(QualifiedRuleContext::DeclarationValue),
                    ..input.state
                })
                .parse_declaration_value()?;
            for component in more {
                value.push(component);
            }
            if let Token::Exclamation(..) = &input.cursor.peek()?.token {
                important = Some(input.parse::<ImportantAnnotation>()?);
            }
        }

        let span = Span {
            start: name_prefix.map_or(name.span().start, |(start, _)| start),
            end: if let Some(important) = &important {
                important.span.end
            } else if let Some(last) = value.last() {
                last.span().end
            } else {
                colon_span.end
            },
        };
        Ok(Declaration {
            name,
            name_prefix: name_prefix.map(|(_, prefix)| prefix),
            name_suffix,
            colon_span,
            value,
            important,
            less_property_merge,
            span,
        })
    }
}

/// End of a declaration's value: the declaration terminator tokens.
fn at_declaration_value_end(token: &Token) -> bool {
    matches!(
        token,
        Token::Semicolon(..)
            | Token::RBrace(..)
            | Token::RParen(..)
            | Token::Dedent(..)
            | Token::Linebreak(..)
            | Token::Eof(..)
    )
}

impl<'a> Parse<'a> for ImportantAnnotation<'a> {
    fn parse(input: &mut Parser<'a>) -> PResult<Self> {
        let (_, span) = input.cursor.expect_exclamation()?;
        input.eat_sass_line_continuation()?;
        let ident: Ident = input.parse::<Ident>()?;
        let span = Span { start: span.start, end: ident.span.end };
        if ident.name.eq_ignore_ascii_case("important") {
            Ok(ImportantAnnotation { ident, span })
        } else {
            Err(Error { kind: ErrorKind::ExpectImportantAnnotation, span })
        }
    }
}

impl<'a> Parse<'a> for QualifiedRule<'a> {
    fn parse(input: &mut Parser<'a>) -> PResult<Self> {
        let selector_list = input
            .with_state(ParserState {
                qualified_rule_ctx: Some(QualifiedRuleContext::Selector),
                ..input.state
            })
            .parse::<SelectorList>()?;
        let block = input.parse::<SimpleBlock>()?;
        let span = Span { start: selector_list.span.start, end: block.span.end };
        Ok(QualifiedRule { selector: selector_list, block, span })
    }
}

impl<'a> Parse<'a> for SimpleBlock<'a> {
    fn parse(input: &mut Parser<'a>) -> PResult<Self> {
        let is_sass = input.syntax == Syntax::Sass;
        let start = if is_sass {
            // A continuation line deeper than this block's own level leaves a
            // pending indent whose `Dedent` arrives before the block opens
            // (`a,\n    b\n  c: d`); cancel those out first.
            let drained = input.drain_sass_pending_dedents()?;
            if let Some((_, span)) = input.cursor.eat_indent()? {
                span.end
            } else if drained
                && input.sass_pending_indents == 0
                && input.cursor.tokenizer.reopen_indent_level()
            {
                // The block's level sat between two known indents, so its
                // `Indent` was never emitted; re-open it directly.
                input.cursor.peek()?.span.start
            } else if input.sass_pending_indents > 0 {
                // The statement's clause consumed this block's `Indent` as a
                // line continuation (`@each $a in\n  b, c\n  .x\n    ...`);
                // enter the block "virtually" at that depth.
                input.sass_pending_indents -= 1;
                input.cursor.peek()?.span.start
            } else {
                let offset = input.cursor.peek()?.span.start;
                return Ok(SimpleBlock {
                    statements: input.vec(),
                    span: Span { start: offset, end: offset },
                });
            }
        } else {
            input.cursor.expect_l_brace()?.1.start
        };

        let statements = input.parse_statements(/* is_top_level */ false)?;

        // CSS Syntax: EOF closes all open constructs (a parse error, but the
        // tree is valid — browsers accept unclosed blocks at EOF). The
        // dialects' reference compilers reject them.
        if input.syntax == Syntax::Css && matches!(input.cursor.peek()?.token, Token::Eof(..)) {
            let end = input.cursor.peek()?.span.start;
            return Ok(SimpleBlock { statements, span: Span { start, end } });
        }

        if is_sass {
            match input.cursor.bump()? {
                TokenWithSpan { token: Token::Dedent(..) | Token::Eof(..), span } => {
                    let end = statements.last().map_or(span.start, |last| last.span().end);
                    Ok(SimpleBlock { statements, span: Span { start, end } })
                }
                TokenWithSpan { span, .. } => {
                    Err(Error { kind: ErrorKind::ExpectDedentOrEof, span })
                }
            }
        } else {
            let end = input.cursor.expect_r_brace()?.1.end;
            Ok(SimpleBlock { statements, span: Span { start, end } })
        }
    }
}

impl<'a> Parse<'a> for Stylesheet<'a> {
    fn parse(input: &mut Parser<'a>) -> PResult<Self> {
        let statements = input.parse_statements(/* is_top_level */ true)?;
        input.cursor.expect_eof()?;
        Ok(Stylesheet { statements, span: Span { start: 0, end: input.source.len() } })
    }
}

impl<'a> Parser<'a> {
    /// Consume a declaration value as raw tokens (CSS Syntax "preserved
    /// tokens"), balancing `()`/`[]`/`{}` pairs, until a top-level `;`, an
    /// unbalanced closer, or a statement boundary. Used for custom-property
    /// values and as the fallback for CSS values the typed grammar rejects.
    ///
    /// `stop_at_top_level_brace` implements the CSS Nesting disambiguation: a
    /// `{` at the top level of a normal declaration's value means the whole
    /// construct is really a qualified rule, so the value must end there.
    /// Custom properties are exempt (`--foo: {a:b}` is a valid value).
    pub(super) fn parse_declaration_value_tokens(
        &mut self,
        stop_at_top_level_brace: bool,
    ) -> PResult<oxc_allocator::Vec<'a, ComponentValue<'a>>> {
        let mut values = self.vec_with_capacity(3);
        let mut pairs = Vec::with_capacity(1);
        loop {
            match &self.cursor.peek()?.token {
                Token::Dedent(..) | Token::Linebreak(..) | Token::Eof(..) => break,
                Token::Semicolon(..) if pairs.is_empty() => {
                    break;
                }
                Token::LBrace(..) if stop_at_top_level_brace && pairs.is_empty() => {
                    break;
                }
                // An interpolated string (e.g. `'#{$expr}'` inside
                // `filter: progid:...`) must be parsed structurally:
                // the tokenizer needs `scan_string_template` to resume
                // the string after each `#{...}`, so consuming its
                // tokens as a plain stream would mis-lex the rest.
                Token::StrTemplate(..) => {
                    values.push(ComponentValue::InterpolableStr(self.parse()?));
                    continue;
                }
                token => {
                    if !crate::util::track_paired_token(token, &mut pairs) {
                        break;
                    }
                }
            }
            values.push(ComponentValue::TokenWithSpan(self.cursor.bump()?));
        }
        Ok(values)
    }

    pub(super) fn parse_declaration_value(
        &mut self,
    ) -> PResult<oxc_allocator::Vec<'a, ComponentValue<'a>>> {
        let mut values = self.vec_with_capacity(3);
        loop {
            match &self.cursor.peek()?.token {
                Token::RBrace(..)
                | Token::RParen(..)
                | Token::Semicolon(..)
                | Token::Dedent(..)
                | Token::Linebreak(..)
                | Token::Exclamation(..)
                | Token::Eof(..) => break,
                _ => {
                    let value = self.parse::<ComponentValue>()?;
                    match &value {
                        ComponentValue::SassNestingDeclaration(..)
                            if matches!(self.syntax, Syntax::Scss | Syntax::Sass) =>
                        {
                            values.push(value);
                            break;
                        }
                        _ => values.push(value),
                    }
                }
            }
        }
        Ok(values)
    }

    /// In a `@keyframes` body, an ident may start a keyframe block (`from {`)
    /// or — in real-world code — a plain declaration (`blah: blee;`); dart-sass
    /// accepts both. Returns the statement and whether it opened a block.
    fn parse_keyframe_block_or_declaration(&mut self) -> PResult<(Statement<'a>, bool)> {
        if let Ok(block) = self.try_parse(KeyframeBlock::parse) {
            Ok((Statement::KeyframeBlock(block), true))
        } else {
            let decl = self.parse_style_rule_declaration()?;
            Ok((Statement::Declaration(decl), false))
        }
    }

    /// Parse a qualified rule, falling back to a declaration when the `foo: bar`
    /// vs `foo { }` prelude is ambiguous. Returns the statement and whether it
    /// opened a block (for the caller's `is_block_element`).
    fn parse_rule_or_declaration(&mut self, is_top_level: bool) -> PResult<(Statement<'a>, bool)> {
        match self.try_parse(QualifiedRule::parse) {
            Ok(rule) => Ok((Statement::QualifiedRule(rule), true)),
            Err(error_rule) => match self.parse_style_rule_declaration() {
                Ok(decl) => {
                    // Only Scss/Sass produce `SassNestingDeclaration`; in CSS this is
                    // always `false`, matching the previous per-syntax behavior.
                    let is_block_element = matches!(
                        decl.value.last(),
                        Some(ComponentValue::SassNestingDeclaration(..))
                    );
                    if is_top_level {
                        self.recoverable_errors.push(Error {
                            kind: ErrorKind::TopLevelDeclaration,
                            span: decl.span.clone(),
                        });
                    }
                    Ok((Statement::Declaration(decl), is_block_element))
                }
                Err(error_decl) => Err(if is_top_level { error_rule } else { error_decl }),
            },
        }
    }

    /// Parse a declaration that is a statement in a style-rule block, enabling the
    /// IE `*color` hack (see `ParserState::allow_ie_star_hack`). Feature-query
    /// declarations (`@supports`, `@container style()`, `@import supports()`) call
    /// `Declaration::parse` directly and so never enable it.
    fn parse_style_rule_declaration(&mut self) -> PResult<Declaration<'a>> {
        self.with_state(ParserState { allow_ie_star_hack: true, ..self.state.clone() }).parse()
    }

    fn parse_statements(
        &mut self,
        is_top_level: bool,
    ) -> PResult<oxc_allocator::Vec<'a, Statement<'a>>> {
        let mut statements = self.vec_with_capacity(1);
        loop {
            // Set true for braced blocks AND `${}` placeholder statements: both
            // make the trailing terminator optional. A placeholder substitutes a
            // whole statement/declaration and, like postcss, needs no `;`, so the
            // next statement may follow directly (`${mixin}\n@media {...}`,
            // `${a} ${b}`, `${foo}: ${bar}`).
            let mut is_block_element = false;
            let TokenWithSpan { token, span } = self.cursor.peek()?;
            match token {
                Token::Ident(..) | Token::HashLBrace(..) | Token::AtLBraceVar(..) => {
                    match self.syntax {
                        Syntax::Css => {
                            if self.state.in_keyframes_at_rule {
                                let (stmt, is_block) =
                                    self.parse_keyframe_block_or_declaration()?;
                                is_block_element = is_block;
                                statements.push(stmt);
                            } else {
                                let (stmt, is_block) =
                                    self.parse_rule_or_declaration(is_top_level)?;
                                is_block_element = is_block;
                                statements.push(stmt);
                            }
                        }
                        Syntax::Scss | Syntax::Sass => {
                            if let Ok(sass_var_decl) =
                                self.try_parse(SassVariableDeclaration::parse)
                            {
                                statements.push(Statement::SassVariableDeclaration(
                                    self.alloc(sass_var_decl),
                                ));
                            } else if self.state.in_keyframes_at_rule {
                                let (stmt, is_block) =
                                    self.parse_keyframe_block_or_declaration()?;
                                is_block_element = is_block;
                                statements.push(stmt);
                            } else {
                                let (stmt, is_block) =
                                    self.parse_rule_or_declaration(is_top_level)?;
                                is_block_element = is_block;
                                statements.push(stmt);
                            }
                        }
                        Syntax::Less => {
                            if let Ok(stmt) = self.try_parse(Parser::parse_less_qualified_rule) {
                                statements.push(stmt);
                                is_block_element = true;
                            } else if let Ok(decl) =
                                // less.js parses root-level declarations and
                                // only rejects them at eval time.
                                self.try_parse(Declaration::parse)
                            {
                                statements.push(Statement::Declaration(decl));
                            } else if self.state.in_keyframes_at_rule {
                                statements.push(Statement::KeyframeBlock(self.parse()?));
                                is_block_element = true;
                            } else {
                                let fn_call = self.parse::<Function>()?;
                                is_block_element = matches!(
                                    fn_call.args.last(),
                                    Some(ComponentValue::LessDetachedRuleset(..))
                                );
                                statements.push(Statement::LessFunctionCall(fn_call));
                            }
                        }
                    }
                }
                // `5:-` — less.js's ruleProperty regex (`[_a-zA-Z0-9-]+`)
                // allows digit-only declaration names
                Token::Number(..)
                    if self.syntax == Syntax::Less
                        && !is_top_level
                        && self.source.as_bytes().get(span.end) == Some(&b':') =>
                {
                    let decl = self.parse_style_rule_declaration()?;
                    statements.push(Statement::Declaration(decl));
                }
                // `.3D(...)` — less.js allows digit-led mixin names, which
                // arrive as one <dimension-token>; they behave exactly like
                // `.foo` (`.3D ()`, `.3D;`), so only the leading `.` matters
                Token::Dot(..) | Token::Hash(..) | Token::Dimension(..)
                    if self.syntax == Syntax::Less
                        && (!matches!(token, Token::Dimension(..))
                            || self.source.as_bytes().get(span.start) == Some(&b'.')) =>
                {
                    let stmt = if let Ok(stmt) = self.try_parse(Parser::parse_less_qualified_rule) {
                        is_block_element = true;
                        stmt
                    } else if let Ok(mixin_def) = self.try_parse(LessMixinDefinition::parse) {
                        is_block_element = true;
                        Statement::LessMixinDefinition(self.alloc(mixin_def))
                    } else {
                        self.parse().map(Statement::LessMixinCall)?
                    };
                    statements.push(stmt);
                }
                Token::Dot(..) | Token::Hash(..) if !self.state.in_keyframes_at_rule => {
                    if self.syntax == Syntax::Css {
                        let (stmt, is_block) = self.parse_rule_or_declaration(is_top_level)?;
                        is_block_element = is_block;
                        statements.push(stmt);
                    } else {
                        statements.push(Statement::QualifiedRule(self.parse()?));
                        is_block_element = true;
                    }
                }
                Token::Ampersand(..)
                | Token::LBracket(..)
                | Token::Colon(..)
                | Token::ColonColon(..)
                | Token::Asterisk(..)
                | Token::Bar(..)
                | Token::NumberSign(..)
                    if !self.state.in_keyframes_at_rule =>
                {
                    if matches!(self.cursor.peek()?.token, Token::Asterisk(..)) {
                        // `*color: red` / `*zoom: 1` (an IE<=7 hack) looks like a `*`
                        // universal selector but is a declaration; try the rule, then
                        // fall back to a declaration. (A `*` never starts a
                        // `LessExtendRule`, so this can precede the Less split.)
                        if self.syntax == Syntax::Less {
                            match self.try_parse(Parser::parse_less_qualified_rule) {
                                Ok(stmt) => {
                                    statements.push(stmt);
                                    is_block_element = true;
                                }
                                // Less refuses declarations at the top level, like the
                                // ident-led path; keep root-level `*zoom: 1` an error.
                                Err(rule_err) if is_top_level => return Err(rule_err),
                                Err(_) => {
                                    let decl = self.parse_style_rule_declaration()?;
                                    statements.push(Statement::Declaration(decl));
                                }
                            }
                        } else {
                            let (stmt, is_block) = self.parse_rule_or_declaration(is_top_level)?;
                            is_block_element = is_block;
                            statements.push(stmt);
                        }
                    } else if self.syntax == Syntax::Less {
                        if let Ok(extend_rule) = self.try_parse(LessExtendRule::parse) {
                            statements.push(Statement::LessExtendRule(extend_rule));
                        } else {
                            statements.push(self.parse_less_qualified_rule()?);
                            is_block_element = true;
                        }
                    } else if self.syntax == Syntax::Css
                        && matches!(self.cursor.peek()?.token, Token::Colon(..))
                    {
                        let (stmt, is_block) = self.parse_rule_or_declaration(is_top_level)?;
                        is_block_element = is_block;
                        statements.push(stmt);
                    } else {
                        statements.push(Statement::QualifiedRule(self.parse()?));
                        is_block_element = true;
                    }
                }
                Token::AtKeyword(at_keyword) => match self.syntax {
                    Syntax::Css => {
                        let at_rule = self.parse::<AtRule>()?;
                        is_block_element = at_rule.block.is_some();
                        statements.push(Statement::AtRule(at_rule));
                    }
                    Syntax::Scss | Syntax::Sass => {
                        let at_keyword_name = at_keyword.ident.name();
                        match &*at_keyword_name {
                            "if" => {
                                let sass_if_at_rule = self.parse()?;
                                statements
                                    .push(Statement::SassIfAtRule(self.alloc(sass_if_at_rule)));
                                is_block_element = true;
                            }
                            "else" => {
                                return Err(Error {
                                    kind: ErrorKind::UnexpectedSassElseAtRule,
                                    span: self.cursor.bump()?.span,
                                });
                            }
                            _ => {
                                let at_rule = self.parse::<AtRule>()?;
                                is_block_element = at_rule.block.is_some();
                                statements.push(Statement::AtRule(at_rule));
                            }
                        }
                    }
                    Syntax::Less => {
                        if let Ok(less_variable_declaration) =
                            self.try_parse(LessVariableDeclaration::parse)
                        {
                            is_block_element = matches!(
                                less_variable_declaration.value,
                                ComponentValue::LessDetachedRuleset(..)
                            );
                            statements.push(Statement::LessVariableDeclaration(
                                self.alloc(less_variable_declaration),
                            ));
                        } else if let Ok(variable_call) = self.try_parse(LessVariableCall::parse) {
                            statements.push(Statement::LessVariableCall(variable_call));
                        } else {
                            let at_rule = self.parse::<AtRule>()?;
                            is_block_element = at_rule.block.is_some();
                            statements.push(Statement::AtRule(at_rule));
                        }
                    }
                },
                Token::Placeholder(..) => {
                    // A placeholder may start a qualified rule (a substituted
                    // selector, e.g. CSS-in-JS `${Component} { ... }`) or stand
                    // alone as a statement (e.g. `` `PLACEHOLDER-0`; ``).
                    //
                    // A placeholder-led selector must not absorb across a newline:
                    // prettier keeps `${mixin}` on its own line and the following
                    // selector as a separate rule (`${mixin}\n& > .x {}` is two
                    // statements, not one). So only attempt the rule when the block
                    // `{` is reachable without an intervening newline-then-selector.
                    //
                    // A placeholder may also be a declaration property name
                    // (`${foo}: ${bar}`), so try a declaration before falling back
                    // to a bare placeholder statement.
                    let ph_end = self.cursor.peek()?.span.end;
                    if self.placeholder_starts_qualified_rule(ph_end)
                        && let Ok(rule) = self.try_parse(QualifiedRule::parse)
                    {
                        statements.push(Statement::QualifiedRule(rule));
                        is_block_element = true;
                    } else if let Ok(declaration) = self.try_parse(Declaration::parse) {
                        // Reached only via the placeholder token above, so this
                        // is the `${foo}: ${bar}` form (placeholder property name).
                        statements.push(Statement::Declaration(declaration));
                        is_block_element = true;
                    } else {
                        let (placeholder, span) = self.cursor.expect_placeholder()?;
                        statements.push(Statement::Placeholder((placeholder, span).into()));
                        is_block_element = true;
                    }
                }
                Token::Percent(..) if matches!(self.syntax, Syntax::Scss | Syntax::Sass) => {
                    statements.push(Statement::QualifiedRule(self.parse()?));
                    is_block_element = true;
                }
                Token::DollarVar(..) if matches!(self.syntax, Syntax::Scss | Syntax::Sass) => {
                    let declaration = self.parse()?;
                    statements.push(Statement::SassVariableDeclaration(self.alloc(declaration)));
                }
                Token::DollarVar(..)
                    if self.syntax == Syntax::Css && self.options.allow_postcss_simple_vars =>
                {
                    let declaration = self.parse()?;
                    statements
                        .push(Statement::PostcssSimpleVarDeclaration(self.alloc(declaration)));
                }
                // Indented-syntax shorthands: `=name` defines a mixin
                // (`@mixin name`) and `+name` includes one (`@include name`).
                // A spaced `+ b` stays a sibling-combinator selector: `+` is
                // an include only when glued to an identifier.
                Token::Equal(..) if self.syntax == Syntax::Sass => {
                    let eq_span = self.cursor.bump()?.span;
                    self.eat_sass_line_continuation()?;
                    let prelude = self.parse::<SassMixin>()?;
                    let block = self
                        .with_state(ParserState {
                            sass_ctx: self.state.sass_ctx
                                | super::state::SASS_CTX_ALLOW_KEYFRAME_BLOCK,
                            ..self.state.clone()
                        })
                        .parse::<SimpleBlock>()?;
                    let span = Span { start: eq_span.start, end: block.span.end };
                    statements.push(Statement::AtRule(AtRule {
                        name: Ident { name: "mixin", raw: "=", span: eq_span },
                        prelude: Some(AtRulePrelude::SassMixin(self.alloc(prelude))),
                        block: Some(block),
                        span,
                    }));
                    is_block_element = true;
                }
                Token::Plus(..)
                    if self.syntax == Syntax::Sass
                        && crate::tokenizer::ident_starts_at(self.source, span.end) =>
                {
                    let plus_span = self.cursor.bump()?.span;
                    let prelude = self.parse::<SassInclude>()?;
                    let block = if matches!(
                        self.cursor.peek()?.token,
                        Token::LBrace(..) | Token::Indent(..)
                    ) {
                        Some(
                            self.with_state(ParserState {
                                sass_ctx: self.state.sass_ctx
                                    | super::state::SASS_CTX_ALLOW_KEYFRAME_BLOCK,
                                ..self.state.clone()
                            })
                            .parse::<SimpleBlock>()?,
                        )
                    } else {
                        None
                    };
                    let end = block.as_ref().map_or(prelude.span.end, |block| block.span.end);
                    let span = Span { start: plus_span.start, end };
                    is_block_element = block.is_some();
                    statements.push(Statement::AtRule(AtRule {
                        name: Ident { name: "include", raw: "+", span: plus_span },
                        prelude: Some(AtRulePrelude::SassInclude(self.alloc(prelude))),
                        block,
                        span,
                    }));
                }
                Token::GreaterThan(..) | Token::Plus(..) | Token::Tilde(..) | Token::BarBar(..) => {
                    if self.syntax == Syntax::Less {
                        statements.push(self.parse_less_qualified_rule()?);
                    } else {
                        statements.push(Statement::QualifiedRule(self.parse()?));
                    }
                    is_block_element = true;
                }
                Token::DollarLBraceVar(..) if self.syntax == Syntax::Less => {
                    statements.push(self.parse().map(Statement::Declaration)?);
                }
                Token::Cdo(..) | Token::Cdc(..) => {
                    self.cursor.bump()?;
                    continue;
                }
                Token::At(..) if matches!(self.syntax, Syntax::Scss | Syntax::Sass) => {
                    let unknown_sass_at_rule = self.parse::<UnknownSassAtRule>()?;
                    is_block_element = unknown_sass_at_rule.block.is_some();
                    statements.push(Statement::UnknownSassAtRule(self.alloc(unknown_sass_at_rule)));
                }
                Token::Percentage(..)
                    if self.state.in_keyframes_at_rule
                        || self.state.sass_ctx & super::state::SASS_CTX_ALLOW_KEYFRAME_BLOCK
                            != 0
                        || self.state.less_ctx & super::state::LESS_CTX_ALLOW_KEYFRAME_BLOCK
                            != 0 =>
                {
                    statements.push(Statement::KeyframeBlock(self.parse()?));
                    is_block_element = true;
                }
                Token::RBrace(..) | Token::Eof(..) | Token::Dedent(..) => break,
                Token::Semicolon(..) | Token::Linebreak(..) => {
                    self.cursor.bump()?;
                    continue;
                }
                Token::LBrace(..) if self.syntax == Syntax::Css => {
                    // An empty selector (`{}`): postcss parses it as a qualified rule
                    // with no selector, so build one with an empty selector list.
                    let start = span.start;
                    let block = self.parse::<SimpleBlock>()?;
                    let selector = SelectorList {
                        selectors: self.vec(),
                        comma_spans: self.vec(),
                        span: Span { start, end: start },
                    };
                    let span = Span { start, end: block.span.end };
                    statements.push(Statement::QualifiedRule(QualifiedRule {
                        selector,
                        block,
                        span,
                    }));
                    is_block_element = true;
                }
                _ => {
                    return Err(Error {
                        kind: if self.state.in_keyframes_at_rule {
                            ErrorKind::ExpectKeyframeBlock
                        } else {
                            ErrorKind::ExpectRule
                        },
                        span: span.clone(),
                    });
                }
            };
            // Drain continuation indents that never became a block (e.g.
            // `$a\n  : b` — the deeper line belonged to the statement's own
            // clause, so its matching `Dedent` has no block to close). A
            // drained `Dedent` is itself a line boundary, so the statement
            // separator is already satisfied.
            if self.drain_sass_pending_dedents()? {
                continue;
            }
            match &self.cursor.peek()?.token {
                Token::RBrace(..) | Token::Eof(..) | Token::Dedent(..) => break,
                _ => {
                    if self.syntax == Syntax::Sass {
                        // The indented syntax also accepts `;` as a statement
                        // terminator/separator (`a; b`), like a newline.
                        if is_block_element {
                            if self.cursor.eat_semicolon()?.is_none() {
                                self.cursor.eat_linebreak()?;
                            }
                        } else if self.cursor.eat_semicolon()?.is_none() {
                            self.cursor.expect_linebreak()?;
                        }
                    } else if is_block_element {
                        self.cursor.eat_semicolon()?;
                    } else {
                        self.cursor.expect_semicolon()?;
                    }
                }
            }
        }
        Ok(statements)
    }

    /// Whether a statement-position `${}` placeholder (ending at byte `from`)
    /// should be offered to `QualifiedRule::parse`. The css-in-js rule the parser
    /// can't see on its own, matching prettier:
    /// - a bare `{` after the placeholder IS absorbed — the placeholder is the
    ///   selector for that block (`${mixin}\n{ color: red }` is one rule; a bare
    ///   `{...}` is meaningless without a selector, so this is the only valid read)
    /// - a placeholder separated by whitespace from what follows, then a newline,
    ///   then selector content = a separate rule (`${mixin}\n& > .x {}` and
    ///   `${a} ${b}\nhtml {}` are two statements, not one — spaced placeholders
    ///   are typically mixin invocations, not selector pieces)
    /// - but a placeholder IMMEDIATELY glued to non-whitespace (e.g. `${p}:hover`
    ///   or `${p},`) is a compound-selector piece, so a multi-line selector list
    ///   (`${p}:hover &,\n${q}:focus &, { ... }`) is one rule — keep scanning for `{` across newlines.
    ///
    /// The real grammar (strings, comments, `#{...}` interpolations, validity) is
    /// left to `QualifiedRule::parse`, which runs next and rolls back if this guess was wrong.
    /// Deliberately NOT a tokenizer: it never early-exits on `;`/`}`
    /// (those may sit inside an attribute string or comment),
    /// so it can't misclassify a same-line selector containing them.
    fn placeholder_starts_qualified_rule(&self, from: usize) -> bool {
        let bytes = &self.source.as_bytes()[from..];
        // Immediately-adjacent non-whitespace (`${p}:hover`, `${p},`) means the
        // placeholder is a compound-selector piece: only `{` matters from here, regardless of newlines.
        if bytes.first().is_some_and(|b| !b.is_ascii_whitespace()) {
            return bytes.contains(&b'{');
        }
        // Otherwise the placeholder is separated by whitespace from what follows.
        // A `{` on the same line (whitespace-only prefix) still makes the
        // placeholder its selector; any non-whitespace after a newline starts a separate rule.
        let mut newline_seen = false;
        for &b in bytes {
            match b {
                b'{' => return true,
                // `\r`, `\r\n`, and `\n` all count as a newline (the tokenizer
                // treats a bare `\r` as a line break too).
                b'\n' | b'\r' => newline_seen = true,
                _ if b.is_ascii_whitespace() => {}
                _ if newline_seen => return false,
                _ => {}
            }
        }
        // No block at all -> a declaration or a bare placeholder, not a rule.
        false
    }
}