Skip to main content

parsec_css/
parser.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! The parser, CSS Syntax §5, with the entry points of the current
5//! editor's draft.
6//!
7//! Each algorithm reads component values, not tokens: from the tokenizer,
8//! which builds a block or function whole as soon as it starts, or from a
9//! block already parsed. The spec allows either, and it means a rule's
10//! `{}` block can be kept as it is and its contents parsed later, by
11//! [`SimpleBlock::contents`], with the same result as parsing them at once.
12//!
13//! Nothing here recurses on the input's nesting, so `((((…` a million deep
14//! parses, serializes and drops on any stack.
15
16use std::borrow::Cow;
17
18use crate::tokenizer::{Span, Token, Tokenizer};
19
20/// Which bracket a [`SimpleBlock`] was written with.
21#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
22pub enum Bracket {
23    /// `( )`
24    Paren,
25    /// `[ ]`
26    Square,
27    /// `{ }`
28    Curly,
29}
30
31impl Bracket {
32    pub fn open(self) -> char {
33        match self {
34            Bracket::Paren => '(',
35            Bracket::Square => '[',
36            Bracket::Curly => '{',
37        }
38    }
39
40    pub fn close(self) -> char {
41        match self {
42            Bracket::Paren => ')',
43            Bracket::Square => ']',
44            Bracket::Curly => '}',
45        }
46    }
47}
48
49/// A token, a function or a block: what every value, prelude and block in
50/// CSS is a list of.
51#[derive(Clone, Debug, PartialEq)]
52pub enum ComponentValue<'a> {
53    /// Any token but the ones that open a function or a block. `)`, `]` and
54    /// `}` with nothing to close are kept too, as the spec keeps them.
55    Token(Token<'a>, Span),
56    Function(Function<'a>),
57    Block(SimpleBlock<'a>),
58}
59
60impl<'a> ComponentValue<'a> {
61    pub fn span(&self) -> Span {
62        match self {
63            ComponentValue::Token(_, span) => *span,
64            ComponentValue::Function(f) => f.span,
65            ComponentValue::Block(b) => b.span,
66        }
67    }
68
69    pub fn token(&self) -> Option<&Token<'a>> {
70        match self {
71            ComponentValue::Token(t, _) => Some(t),
72            _ => None,
73        }
74    }
75
76    pub fn is_whitespace(&self) -> bool {
77        matches!(self, ComponentValue::Token(Token::Whitespace, _))
78    }
79
80    /// Whether this is `token`, which is one without a value, or a delim.
81    fn is(&self, token: &Token<'_>) -> bool {
82        match (self, token) {
83            (ComponentValue::Token(Token::Delim(a), _), Token::Delim(b)) => a == b,
84            (ComponentValue::Token(t, _), _) => {
85                std::mem::discriminant(t) == std::mem::discriminant(token)
86            }
87            _ => false,
88        }
89    }
90
91    fn is_curly(&self) -> bool {
92        matches!(self, ComponentValue::Block(b) if b.bracket == Bracket::Curly)
93    }
94}
95
96/// `name( … )`.
97#[derive(Clone, Debug, PartialEq)]
98pub struct Function<'a> {
99    pub name: Cow<'a, str>,
100    pub arguments: Vec<ComponentValue<'a>>,
101    /// From the name to the `)`, or to the end of the input if it's missing.
102    pub span: Span,
103}
104
105/// `( … )`, `[ … ]` or `{ … }`.
106#[derive(Clone, Debug, PartialEq)]
107pub struct SimpleBlock<'a> {
108    pub bracket: Bracket,
109    pub contents: Vec<ComponentValue<'a>>,
110    pub span: Span,
111}
112
113/// Dropping a child at a time from a list, rather than letting each list
114/// drop its own children, keeps a deep tree off the stack.
115fn drop_flat(children: &mut Vec<ComponentValue<'_>>) {
116    if children
117        .iter()
118        .all(|c| matches!(c, ComponentValue::Token(..)))
119    {
120        return;
121    }
122    let mut stack = std::mem::take(children);
123    while let Some(child) = stack.pop() {
124        match child {
125            ComponentValue::Function(mut f) => stack.append(&mut f.arguments),
126            ComponentValue::Block(mut b) => stack.append(&mut b.contents),
127            ComponentValue::Token(..) => {}
128        }
129    }
130}
131
132impl Drop for Function<'_> {
133    fn drop(&mut self) {
134        drop_flat(&mut self.arguments);
135    }
136}
137
138impl Drop for SimpleBlock<'_> {
139    fn drop(&mut self) {
140        drop_flat(&mut self.contents);
141    }
142}
143
144impl<'a> SimpleBlock<'a> {
145    /// Parses a `{}` block's contents as declarations and rules, the way
146    /// style rules and nested at-rules hold them. `src` is the text the
147    /// block was parsed from.
148    pub fn contents(mut self, src: &'a str) -> BlockContents<'a> {
149        let values = std::mem::take(&mut self.contents);
150        let mut p = Parser::new(src, values.into_iter());
151        let items = p.block_contents();
152        BlockContents {
153            items,
154            errors: p.errors,
155        }
156    }
157}
158
159/// `@name prelude;` or `@name prelude { block }`.
160///
161/// `B` is what the `{}` block is kept as: a [`SimpleBlock`], unparsed,
162/// from [`parse_stylesheet`] and the other entry points, or a [`Block`],
163/// its contents parsed, from [`parse_stylesheet_deep`].
164#[derive(Clone, Debug, PartialEq)]
165pub struct AtRule<'a, B = SimpleBlock<'a>> {
166    pub name: Cow<'a, str>,
167    pub prelude: Vec<ComponentValue<'a>>,
168    /// The `{}` block. Unparsed, what it holds depends on the rule, so
169    /// [`SimpleBlock::contents`] parses it when the rule calls for that.
170    pub block: Option<B>,
171    pub span: Span,
172}
173
174/// `prelude { block }`: a style rule when the prelude is a selector. `B`
175/// is as for [`AtRule`].
176#[derive(Clone, Debug, PartialEq)]
177pub struct QualifiedRule<'a, B = SimpleBlock<'a>> {
178    pub prelude: Vec<ComponentValue<'a>>,
179    /// The `{}` block. Unparsed, [`SimpleBlock::contents`] gives its
180    /// declarations and nested rules.
181    pub block: B,
182    pub span: Span,
183}
184
185#[derive(Clone, Debug, PartialEq)]
186pub enum Rule<'a, B = SimpleBlock<'a>> {
187    At(AtRule<'a, B>),
188    Qualified(QualifiedRule<'a, B>),
189}
190
191impl<B> Rule<'_, B> {
192    pub fn span(&self) -> Span {
193        match self {
194            Rule::At(r) => r.span,
195            Rule::Qualified(r) => r.span,
196        }
197    }
198}
199
200/// `name: value !important`.
201#[derive(Clone, Debug, PartialEq)]
202pub struct Declaration<'a> {
203    pub name: Cow<'a, str>,
204    /// Without the whitespace at either end or the `!important`.
205    pub value: Vec<ComponentValue<'a>>,
206    pub important: bool,
207    /// From the name to the end of the value or the `important`, not
208    /// including the `;`.
209    pub span: Span,
210}
211
212impl Declaration<'_> {
213    /// The value as it was written, which a custom property keeps:
214    /// comments and all, from `src`, the text it was parsed from.
215    pub fn original_text<'s>(&self, src: &'s str) -> &'s str {
216        match (self.value.first(), self.value.last()) {
217            (Some(first), Some(last)) => &src[first.span().start..last.span().end],
218            _ => "",
219        }
220    }
221}
222
223/// One thing in a block: style rules and the nesting-era at-rules mix
224/// declarations and rules, in order.
225#[derive(Clone, Debug, PartialEq)]
226pub enum Item<'a, B = SimpleBlock<'a>> {
227    Declaration(Declaration<'a>),
228    Rule(Rule<'a, B>),
229}
230
231/// A rule's `{}` block with its contents parsed, as declarations and
232/// rules, and its rules' blocks too: what [`parse_stylesheet_deep`] makes.
233#[derive(Clone, Debug, PartialEq, Default)]
234pub struct Block<'a> {
235    pub items: Vec<Item<'a, Block<'a>>>,
236    /// From the `{` to the `}`, or to the end of the input if it's missing.
237    pub span: Span,
238}
239
240impl Drop for Block<'_> {
241    /// Takes the blocks inside out a level at a time, as [`drop_flat`]
242    /// does for component values, so deep nesting stays off the stack.
243    fn drop(&mut self) {
244        if self.items.iter().all(|i| matches!(i, Item::Declaration(_))) {
245            return;
246        }
247        let mut stack = std::mem::take(&mut self.items);
248        while let Some(item) = stack.pop() {
249            match item {
250                Item::Rule(Rule::Qualified(mut r)) => stack.append(&mut r.block.items),
251                Item::Rule(Rule::At(AtRule {
252                    block: Some(mut b), ..
253                })) => stack.append(&mut b.items),
254                _ => {}
255            }
256        }
257    }
258}
259
260/// What a parse found wrong, and where.
261#[derive(Clone, Copy, Debug, PartialEq, Eq)]
262pub struct ParseError {
263    pub kind: ErrorKind,
264    pub span: Span,
265}
266
267#[derive(Clone, Copy, Debug, PartialEq, Eq)]
268pub enum ErrorKind {
269    /// Nothing but whitespace and comments where one thing was wanted.
270    Empty,
271    /// More after the one thing that was wanted.
272    ExtraInput,
273    /// Something that isn't a declaration where one was wanted, dropped.
274    InvalidDeclaration,
275    /// A rule that didn't parse (a prelude with no block, say), dropped.
276    InvalidRule,
277}
278
279impl std::fmt::Display for ParseError {
280    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
281        let what = match self.kind {
282            ErrorKind::Empty => "nothing to parse",
283            ErrorKind::ExtraInput => "unexpected input after the end",
284            ErrorKind::InvalidDeclaration => "invalid declaration",
285            ErrorKind::InvalidRule => "invalid rule",
286        };
287        write!(f, "{what} at bytes {}..{}", self.span.start, self.span.end)
288    }
289}
290
291impl std::error::Error for ParseError {}
292
293/// A stylesheet's rules, and what was dropped while parsing it.
294#[derive(Clone, Debug, PartialEq)]
295pub struct Stylesheet<'a, B = SimpleBlock<'a>> {
296    pub rules: Vec<Rule<'a, B>>,
297    pub errors: Vec<ParseError>,
298}
299
300impl<B> Default for Stylesheet<'_, B> {
301    fn default() -> Self {
302        Stylesheet {
303            rules: Vec::new(),
304            errors: Vec::new(),
305        }
306    }
307}
308
309/// A block's declarations and rules, and what was dropped while parsing it.
310#[derive(Clone, Debug, PartialEq, Default)]
311pub struct BlockContents<'a> {
312    pub items: Vec<Item<'a>>,
313    pub errors: Vec<ParseError>,
314}
315
316/// Component values straight from the tokenizer. A function or block is
317/// built whole, with a stack of open ones rather than recursion. The
318/// values of every open one share one buffer, so each list is allocated
319/// once, at its final size, when it closes.
320pub(crate) struct Values<'a> {
321    pub(crate) tokens: Tokenizer<'a>,
322    open: Vec<Open<'a>>,
323    buffer: Vec<ComponentValue<'a>>,
324}
325
326impl<'a> Values<'a> {
327    pub(crate) fn new(tokens: Tokenizer<'a>) -> Values<'a> {
328        Values {
329            tokens,
330            open: Vec::new(),
331            buffer: Vec::new(),
332        }
333    }
334}
335
336struct Open<'a> {
337    /// `None` for a function.
338    bracket: Option<Bracket>,
339    name: Cow<'a, str>,
340    start: usize,
341    /// Where its values start in the buffer.
342    at: usize,
343}
344
345/// Moves `buf[at..]` into a list of its own size, by copying the bytes,
346/// and leaves `buf` its room for next time.
347pub(crate) fn take_tail<T>(buf: &mut Vec<T>, at: usize) -> Vec<T> {
348    if at > 0 {
349        return buf.split_off(at);
350    }
351    // `split_off(0)` would hand over the whole buffer, room and all.
352    let mut tail = Vec::with_capacity(buf.len());
353    tail.append(buf);
354    tail
355}
356
357/// What a token opens, if anything.
358#[inline]
359fn opens<'a>(token: Token<'a>, start: usize, at: usize) -> Result<Open<'a>, Token<'a>> {
360    let (bracket, name) = match token {
361        Token::Function(name) => (None, name),
362        Token::LeftParen => (Some(Bracket::Paren), Cow::Borrowed("")),
363        Token::LeftBracket => (Some(Bracket::Square), Cow::Borrowed("")),
364        Token::LeftBrace => (Some(Bracket::Curly), Cow::Borrowed("")),
365        other => return Err(other),
366    };
367    Ok(Open {
368        bracket,
369        name,
370        start,
371        at,
372    })
373}
374
375impl<'a> Open<'a> {
376    fn closes(&self, token: &Token<'_>) -> bool {
377        matches!(
378            (self.bracket, token),
379            (None | Some(Bracket::Paren), Token::RightParen)
380                | (Some(Bracket::Square), Token::RightBracket)
381                | (Some(Bracket::Curly), Token::RightBrace)
382        )
383    }
384
385    fn finish(self, values: Vec<ComponentValue<'a>>, end: usize) -> ComponentValue<'a> {
386        let span = Span::new(self.start, end);
387        match self.bracket {
388            None => ComponentValue::Function(Function {
389                name: self.name,
390                arguments: values,
391                span,
392            }),
393            Some(bracket) => ComponentValue::Block(SimpleBlock {
394                bracket,
395                contents: values,
396                span,
397            }),
398        }
399    }
400}
401
402impl<'a> Iterator for Values<'a> {
403    type Item = ComponentValue<'a>;
404
405    fn next(&mut self) -> Option<ComponentValue<'a>> {
406        let (token, span) = self.tokens.next_token()?;
407        Some(self.whole(token, span))
408    }
409}
410
411impl<'a> Values<'a> {
412    /// The component value `token` starts: the token, or the whole of the
413    /// function or block it opens.
414    #[inline]
415    pub(crate) fn whole(&mut self, token: Token<'a>, span: Span) -> ComponentValue<'a> {
416        match opens(token, span.start, 0) {
417            Ok(open) => self.open.push(open),
418            Err(token) => return ComponentValue::Token(token, span),
419        }
420        self.rest_of_open()
421    }
422
423    fn rest_of_open(&mut self) -> ComponentValue<'a> {
424        loop {
425            let Some((token, span)) = self.tokens.next_token() else {
426                // Everything still open closes at the end of the input.
427                let end = self.tokens.source().len();
428                loop {
429                    let open = self.open.pop().unwrap();
430                    let values = take_tail(&mut self.buffer, open.at);
431                    let done = open.finish(values, end);
432                    if self.open.is_empty() {
433                        return done;
434                    }
435                    self.buffer.push(done);
436                }
437            };
438            if self.open.last().unwrap().closes(&token) {
439                let open = self.open.pop().unwrap();
440                let values = take_tail(&mut self.buffer, open.at);
441                let done = open.finish(values, span.end);
442                if self.open.is_empty() {
443                    return done;
444                }
445                self.buffer.push(done);
446                continue;
447            }
448            if !matches!(
449                token,
450                Token::Function(_) | Token::LeftParen | Token::LeftBracket | Token::LeftBrace
451            ) {
452                self.buffer.push(ComponentValue::Token(token, span));
453                continue;
454            }
455            match opens(token, span.start, self.buffer.len()) {
456                Ok(open) => self.open.push(open),
457                Err(token) => self.buffer.push(ComponentValue::Token(token, span)),
458            }
459        }
460    }
461}
462
463/// Where a parser's values come from. A parsed block's own list can be
464/// looked along, so a declaration's values move out of it in one go.
465trait Source<'a>: Iterator<Item = ComponentValue<'a>> {
466    /// What's left, if it can be seen without taking it.
467    fn rest(&self) -> Option<&[ComponentValue<'a>]> {
468        None
469    }
470}
471
472impl<'a> Source<'a> for Values<'a> {}
473
474impl<'a> Source<'a> for std::vec::IntoIter<ComponentValue<'a>> {
475    fn rest(&self) -> Option<&[ComponentValue<'a>]> {
476        Some(self.as_slice())
477    }
478}
479
480/// How many values come before the next `;` (or, nested, `}`).
481fn before_semicolon(values: &[ComponentValue<'_>], nested: bool) -> usize {
482    values
483        .iter()
484        .position(|v| v.is(&Token::Semicolon) || (nested && v.is(&Token::RightBrace)))
485        .unwrap_or(values.len())
486}
487
488/// A stream of component values with the spec's one item of lookahead,
489/// and room to put back what a failed declaration took.
490struct Parser<'a, I> {
491    src: &'a str,
492    input: I,
493    back: Vec<ComponentValue<'a>>,
494    /// Where a prelude collects, reused from rule to rule.
495    scratch: Vec<ComponentValue<'a>>,
496    errors: Vec<ParseError>,
497}
498
499fn text(src: &str) -> Parser<'_, Values<'_>> {
500    Parser::new(src, Values::new(Tokenizer::new(src)))
501}
502
503impl<'a, I: Source<'a>> Parser<'a, I> {
504    fn new(src: &'a str, input: I) -> Parser<'a, I> {
505        Parser {
506            src,
507            input,
508            back: Vec::new(),
509            scratch: Vec::new(),
510            errors: Vec::new(),
511        }
512    }
513
514    fn peek(&mut self) -> Option<&ComponentValue<'a>> {
515        if self.back.is_empty() {
516            if self.input.rest().is_some() {
517                return self.input.rest().and_then(<[_]>::first);
518            }
519            let next = self.input.next()?;
520            self.back.push(next);
521        }
522        self.back.last()
523    }
524
525    fn next(&mut self) -> Option<ComponentValue<'a>> {
526        self.back.pop().or_else(|| self.input.next())
527    }
528
529    fn put_back(&mut self, values: Vec<ComponentValue<'a>>) {
530        self.back.extend(values.into_iter().rev());
531    }
532
533    fn skip_whitespace(&mut self) {
534        while self.peek().is_some_and(ComponentValue::is_whitespace) {
535            self.next();
536        }
537    }
538
539    fn error(&mut self, kind: ErrorKind, start: usize, end: usize) {
540        self.errors.push(ParseError {
541            kind,
542            span: Span::new(start, end.max(start)),
543        });
544    }
545
546    /// Consume a stylesheet's contents. With `cdo_cdc` false this is the
547    /// 2021 draft's "list of rules", where `<!--` and `-->` aren't skipped.
548    fn rules(&mut self, cdo_cdc: bool) -> Vec<Rule<'a>> {
549        let mut rules = Vec::new();
550        while let Some(next) = self.peek() {
551            match next {
552                ComponentValue::Token(Token::Whitespace, _) => {
553                    self.next();
554                }
555                ComponentValue::Token(Token::Cdo | Token::Cdc, _) if cdo_cdc => {
556                    self.next();
557                }
558                ComponentValue::Token(Token::AtKeyword(_), _) => {
559                    let rule = self.at_rule(false);
560                    rules.push(Rule::At(rule));
561                }
562                _ => {
563                    if let Some(rule) = self.qualified_rule(false, false) {
564                        rules.push(Rule::Qualified(rule));
565                    }
566                }
567            }
568        }
569        rules
570    }
571
572    /// Consume an at-rule; the next value is its at-keyword. Every at-rule
573    /// is valid at this level, so one always comes back.
574    fn at_rule(&mut self, nested: bool) -> AtRule<'a> {
575        let Some(ComponentValue::Token(Token::AtKeyword(name), span)) = self.next() else {
576            unreachable!("at_rule is called on an at-keyword");
577        };
578        let mut rule = AtRule {
579            name,
580            prelude: Vec::new(),
581            block: None,
582            span,
583        };
584        while let Some(next) = self.next() {
585            match next {
586                ComponentValue::Token(Token::Semicolon, _) => break,
587                ComponentValue::Token(Token::RightBrace, _) if nested => {
588                    self.back.push(next);
589                    break;
590                }
591                ComponentValue::Block(block) if block.bracket == Bracket::Curly => {
592                    rule.span.end = block.span.end;
593                    rule.block = Some(block);
594                    break;
595                }
596                other => {
597                    rule.span.end = other.span().end;
598                    self.scratch.push(other);
599                }
600            }
601        }
602        rule.prelude = take_tail(&mut self.scratch, 0);
603        rule
604    }
605
606    /// Consume a qualified rule. `stop` is the nested form's `;`, which
607    /// ends a rule that's really a broken declaration.
608    fn qualified_rule(&mut self, stop: bool, nested: bool) -> Option<QualifiedRule<'a>> {
609        let end_of_input = self.src.len();
610        let start = self.peek().map_or(end_of_input, |v| v.span().start);
611        // The prelude collects in `scratch`, to be allocated once at its size.
612        self.scratch.clear();
613        let mut end = start;
614        loop {
615            let Some(next) = self.next() else {
616                self.scratch.clear();
617                self.error(ErrorKind::InvalidRule, start, end);
618                return None;
619            };
620            match next {
621                ComponentValue::Token(Token::Semicolon, _) if stop => {
622                    self.back.push(next);
623                    self.scratch.clear();
624                    self.error(ErrorKind::InvalidRule, start, end);
625                    return None;
626                }
627                ComponentValue::Token(Token::RightBrace, _) if nested => {
628                    self.back.push(next);
629                    self.scratch.clear();
630                    self.error(ErrorKind::InvalidRule, start, end);
631                    return None;
632                }
633                ComponentValue::Block(block) if block.bracket == Bracket::Curly => {
634                    let end = block.span.end;
635                    let prelude = take_tail(&mut self.scratch, 0);
636                    if looks_like_custom_property(&prelude) {
637                        // `--x:hover {…}` is a custom property gone wrong,
638                        // never a rule; nested, the property runs to its `;`.
639                        if nested {
640                            self.bad_declaration_remnants(true);
641                        }
642                        self.error(ErrorKind::InvalidRule, start, end);
643                        return None;
644                    }
645                    return Some(QualifiedRule {
646                        prelude,
647                        block,
648                        span: Span::new(start, end),
649                    });
650                }
651                other => {
652                    end = other.span().end;
653                    self.scratch.push(other);
654                }
655            }
656        }
657    }
658
659    fn bad_declaration_remnants(&mut self, nested: bool) {
660        while let Some(next) = self.next() {
661            match next {
662                ComponentValue::Token(Token::Semicolon, _) => return,
663                ComponentValue::Token(Token::RightBrace, _) if nested => {
664                    self.back.push(next);
665                    return;
666                }
667                _ => {}
668            }
669        }
670    }
671
672    /// Everything up to the next `;` (or the `}` ending a nested block), the
673    /// most a declaration can be.
674    fn up_to_semicolon(&mut self, nested: bool) -> Vec<ComponentValue<'a>> {
675        let mut values = Vec::new();
676        while let Some(next) = self.peek() {
677            if next.is(&Token::Semicolon) || (nested && next.is(&Token::RightBrace)) {
678                break;
679            }
680            values.push(self.next().unwrap());
681        }
682        values
683    }
684
685    /// Consume a declaration: takes what one could be, and gives it back if
686    /// it isn't one, for the caller to try as a rule.
687    fn declaration(&mut self, nested: bool) -> Result<Declaration<'a>, Vec<ComponentValue<'a>>> {
688        // From a parsed block, look first and move only what's kept.
689        if self.back.is_empty()
690            && let Some(rest) = self.input.rest()
691        {
692            let n = before_semicolon(rest, nested);
693            if let Some(plan) = plan(&rest[..n]) {
694                let name = self.input.next().unwrap();
695                // Not `skip(…).take(…)`: an empty take never runs the skip,
696                // which left the colon behind to be read as a rule.
697                for _ in 1..plan.value_start {
698                    self.input.next();
699                }
700                let value = self
701                    .input
702                    .by_ref()
703                    .take(plan.value_end - plan.value_start)
704                    .collect();
705                // Past the `!important` and trailing whitespace.
706                for _ in plan.value_end.max(plan.value_start)..n {
707                    self.input.next();
708                }
709                return Ok(build(name, value, &plan, self.src));
710            }
711            return Err(self.input.by_ref().take(n).collect());
712        }
713        let values = self.up_to_semicolon(nested);
714        declaration_from(values, self.src)
715    }
716
717    /// Consume a block's contents.
718    fn block_contents(&mut self) -> Vec<Item<'a>> {
719        let mut items = Vec::new();
720        while let Some(next) = self.peek() {
721            match next {
722                ComponentValue::Token(Token::Whitespace | Token::Semicolon, _) => {
723                    self.next();
724                }
725                // Only parsed text can have a `}` here, a block's own never
726                // does: it's dropped, as a stray one is at the top level.
727                ComponentValue::Token(Token::RightBrace, span) => {
728                    let span = *span;
729                    self.next();
730                    self.error(ErrorKind::InvalidRule, span.start, span.end);
731                }
732                ComponentValue::Token(Token::AtKeyword(_), _) => {
733                    let rule = self.at_rule(true);
734                    items.push(Item::Rule(Rule::At(rule)));
735                }
736                // Only an ident can start a declaration.
737                ComponentValue::Token(Token::Ident(_), _) => match self.declaration(true) {
738                    Ok(decl) => items.push(Item::Declaration(decl)),
739                    Err(values) => {
740                        self.put_back(values);
741                        if let Some(rule) = self.qualified_rule(true, true) {
742                            items.push(Item::Rule(Rule::Qualified(rule)));
743                        }
744                    }
745                },
746                _ => {
747                    if let Some(rule) = self.qualified_rule(true, true) {
748                        items.push(Item::Rule(Rule::Qualified(rule)));
749                    }
750                }
751            }
752        }
753        items
754    }
755
756    /// Parse a list of declarations, keeping the at-rules the spec has the
757    /// caller drop, in case the caller wants them.
758    fn declaration_list(&mut self) -> Vec<Item<'a>> {
759        let mut items = Vec::new();
760        while let Some(next) = self.peek() {
761            match next {
762                ComponentValue::Token(Token::Whitespace | Token::Semicolon, _) => {
763                    self.next();
764                }
765                ComponentValue::Token(Token::AtKeyword(_), _) => {
766                    let rule = self.at_rule(false);
767                    items.push(Item::Rule(Rule::At(rule)));
768                }
769                _ => match self.declaration(false) {
770                    Ok(decl) => items.push(Item::Declaration(decl)),
771                    Err(values) => {
772                        let start = values.first().map_or(0, |v| v.span().start);
773                        let end = values.last().map_or(start, |v| v.span().end);
774                        self.error(ErrorKind::InvalidDeclaration, start, end);
775                    }
776                },
777            }
778        }
779        items
780    }
781
782    /// Fails with ExtraInput unless only whitespace is left.
783    fn end<T>(&mut self, value: T) -> Result<T, ParseError> {
784        self.skip_whitespace();
785        match self.peek() {
786            None => Ok(value),
787            Some(v) => {
788                let start = v.span().start;
789                Err(ParseError {
790                    kind: ErrorKind::ExtraInput,
791                    span: Span::new(start, self.src.len()),
792                })
793            }
794        }
795    }
796
797    fn start(&mut self) -> Result<(), ParseError> {
798        self.skip_whitespace();
799        match self.peek() {
800            Some(_) => Ok(()),
801            None => Err(ParseError {
802                kind: ErrorKind::Empty,
803                span: Span::new(0, self.src.len()),
804            }),
805        }
806    }
807}
808
809/// Whether a prelude starts like a custom property: `--name` then `:`.
810pub(crate) fn looks_like_custom_property(prelude: &[ComponentValue<'_>]) -> bool {
811    let mut it = prelude.iter().filter(|v| !v.is_whitespace());
812    matches!(it.next(), Some(ComponentValue::Token(Token::Ident(n), _)) if n.starts_with("--"))
813        && it.next().is_some_and(|v| v.is(&Token::Colon))
814}
815
816/// Where a declaration's parts are in the values `up_to_semicolon` took:
817/// worked out before anything moves, so a failed one costs no moves.
818struct Plan {
819    value_start: usize,
820    value_end: usize,
821    important: bool,
822    unicode_range: bool,
823    span: Span,
824}
825
826/// The plan for `values` as a declaration, or `None` if they aren't one.
827fn plan(values: &[ComponentValue<'_>]) -> Option<Plan> {
828    let Some(ComponentValue::Token(Token::Ident(name), first)) = values.first() else {
829        return None;
830    };
831    let mut colon = 1;
832    while values.get(colon).is_some_and(ComponentValue::is_whitespace) {
833        colon += 1;
834    }
835    let colon_end = match values.get(colon) {
836        Some(ComponentValue::Token(Token::Colon, span)) => span.end,
837        _ => return None,
838    };
839    let after = colon + 1;
840    let v = value_plan(name, &values[after..])?;
841    Some(Plan {
842        value_start: after + v.start,
843        value_end: after + v.end,
844        important: v.important,
845        unicode_range: name.eq_ignore_ascii_case("unicode-range"),
846        span: Span::new(first.start, v.last_end.unwrap_or(colon_end)),
847    })
848}
849
850/// Where a declaration's value is in what follows its colon.
851pub(crate) struct ValuePlan {
852    pub(crate) start: usize,
853    pub(crate) end: usize,
854    pub(crate) important: bool,
855    /// The end of the last thing that isn't whitespace, `!important`
856    /// included: where the declaration's span ends.
857    pub(crate) last_end: Option<usize>,
858}
859
860/// The plan for `values`, all that follows a declaration's colon, or
861/// `None` if a `{}` block where one isn't allowed makes it no declaration.
862pub(crate) fn value_plan(name: &str, values: &[ComponentValue<'_>]) -> Option<ValuePlan> {
863    let mut start = 0;
864    while values.get(start).is_some_and(ComponentValue::is_whitespace) {
865        start += 1;
866    }
867    // The last two non-whitespace values: `!` and `important`?
868    let mut solid = (start..values.len())
869        .rev()
870        .filter(|&i| !values[i].is_whitespace());
871    let last = solid.next();
872    let before = solid.next();
873    let important = match (before, last) {
874        (Some(bang), Some(word))
875            if values[bang].is(&Token::Delim('!'))
876                && matches!(&values[word], ComponentValue::Token(Token::Ident(w), _)
877                    if w.eq_ignore_ascii_case("important")) =>
878        {
879            Some(bang)
880        }
881        _ => None,
882    };
883    let mut end = important.unwrap_or(values.len());
884    while end > start && values[end - 1].is_whitespace() {
885        end -= 1;
886    }
887    if !name.starts_with("--") {
888        // A `{}` block is allowed only as the whole of a property's value.
889        let value = &values[start..end];
890        if value.len() > 1 && value.iter().any(ComponentValue::is_curly) {
891            return None;
892        }
893    }
894    Some(ValuePlan {
895        start,
896        end,
897        important: important.is_some(),
898        last_end: last.map(|i| values[i].span().end),
899    })
900}
901
902/// Builds the planned declaration from its name and value.
903fn build<'a>(
904    name: ComponentValue<'a>,
905    mut value: Vec<ComponentValue<'a>>,
906    plan: &Plan,
907    src: &'a str,
908) -> Declaration<'a> {
909    let ComponentValue::Token(Token::Ident(name), _) = name else {
910        unreachable!("a plan starts with an ident")
911    };
912    if plan.unicode_range && !value.is_empty() {
913        // The one place the spec retokenizes: `U+0-7F` is a range here.
914        let from = value[0].span().start;
915        let to = value[value.len() - 1].span().end;
916        value = Values::new(unicode_range_tokens(src, from, to)).collect();
917    }
918    Declaration {
919        name,
920        value,
921        important: plan.important,
922        span: plan.span,
923    }
924}
925
926/// Builds a declaration from what `up_to_semicolon` took, or hands it back.
927fn declaration_from<'a>(
928    mut values: Vec<ComponentValue<'a>>,
929    src: &'a str,
930) -> Result<Declaration<'a>, Vec<ComponentValue<'a>>> {
931    let Some(plan) = plan(&values) else {
932        return Err(values);
933    };
934    let blank = ComponentValue::Token(Token::Whitespace, Span::default());
935    let name = std::mem::replace(&mut values[0], blank);
936    // The value moves down in place: no new list.
937    values.truncate(plan.value_end);
938    values.drain(..plan.value_start);
939    Ok(build(name, values, &plan, src))
940}
941
942/// A tokenizer over `src[from..to]` making unicode-range tokens, with
943/// spans that still point into `src`.
944pub(crate) fn unicode_range_tokens(src: &str, from: usize, to: usize) -> Tokenizer<'_> {
945    let mut t = Tokenizer::with_unicode_ranges(&src[..to]);
946    t.reset(from);
947    t
948}
949
950/// Parse a stylesheet: its rules, with `<!--` and `-->` skipped between
951/// them as the HTML `<style>` element's history needs.
952///
953/// ```
954/// let sheet = parsec_css::parse_stylesheet("a { color: red } @media print { b {} }");
955/// assert_eq!(sheet.rules.len(), 2);
956/// assert!(sheet.errors.is_empty());
957/// ```
958pub fn parse_stylesheet(css: &str) -> Stylesheet<'_> {
959    let mut p = text(css);
960    let rules = p.rules(true);
961    Stylesheet {
962        rules,
963        errors: p.errors,
964    }
965}
966
967/// Parse a list of rules as the 2021 Candidate Recommendation did, where
968/// `<!--` and `-->` are ordinary tokens. The current draft's "parse a
969/// stylesheet's contents" is [`parse_stylesheet`].
970pub fn parse_rule_list(css: &str) -> Stylesheet<'_> {
971    let mut p = text(css);
972    let rules = p.rules(false);
973    Stylesheet {
974        rules,
975        errors: p.errors,
976    }
977}
978
979/// Parse a block's contents: declarations, at-rules and nested style rules,
980/// in order, the way a style rule's `{}` block holds them since CSS
981/// Nesting. [`SimpleBlock::contents`] does the same for a parsed block.
982///
983/// ```
984/// use parsec_css::Item;
985///
986/// let block = parsec_css::parse_block_contents("color: red; &:hover { color: blue }");
987/// assert!(matches!(&block.items[0], Item::Declaration(d) if d.name == "color"));
988/// assert!(matches!(&block.items[1], Item::Rule(_)));
989/// ```
990pub fn parse_block_contents(css: &str) -> BlockContents<'_> {
991    let mut p = text(css);
992    let items = p.block_contents();
993    BlockContents {
994        items,
995        errors: p.errors,
996    }
997}
998
999/// Parse a list of declarations, as for a `style` attribute. The spec has
1000/// at-rules here parsed and thrown away; they're kept, as
1001/// [`Item::Rule`]s, for you to throw away. Nothing else becomes a rule.
1002pub fn parse_declaration_list(css: &str) -> BlockContents<'_> {
1003    let mut p = text(css);
1004    let items = p.declaration_list();
1005    BlockContents {
1006        items,
1007        errors: p.errors,
1008    }
1009}
1010
1011/// Parse a rule: exactly one, with only whitespace around it.
1012pub fn parse_rule(css: &str) -> Result<Rule<'_>, ParseError> {
1013    let mut p = text(css);
1014    p.start()?;
1015    let rule = if matches!(
1016        p.peek(),
1017        Some(ComponentValue::Token(Token::AtKeyword(_), _))
1018    ) {
1019        Rule::At(p.at_rule(false))
1020    } else {
1021        match p.qualified_rule(false, false) {
1022            Some(rule) => Rule::Qualified(rule),
1023            None => return Err(p.errors.pop().unwrap()),
1024        }
1025    };
1026    p.end(rule)
1027}
1028
1029/// Parse a declaration, as `@supports (…)` does: exactly one.
1030pub fn parse_declaration(css: &str) -> Result<Declaration<'_>, ParseError> {
1031    let mut p = text(css);
1032    p.start()?;
1033    match p.declaration(false) {
1034        Ok(decl) => p.end(decl),
1035        Err(values) => {
1036            let start = values.first().map_or(0, |v| v.span().start);
1037            Err(ParseError {
1038                kind: ErrorKind::InvalidDeclaration,
1039                span: Span::new(start, css.len()),
1040            })
1041        }
1042    }
1043}
1044
1045/// Parse a component value: exactly one, with only whitespace around it.
1046pub fn parse_component_value(css: &str) -> Result<ComponentValue<'_>, ParseError> {
1047    let mut p = text(css);
1048    p.start()?;
1049    let value = p.next().unwrap();
1050    p.end(value)
1051}
1052
1053/// Parse a list of component values: the whole input, as a selector or a
1054/// media query list is read.
1055pub fn parse_component_values(css: &str) -> Vec<ComponentValue<'_>> {
1056    Values::new(Tokenizer::new(css)).collect()
1057}
1058
1059/// Parse a comma-separated list of component values, split at the commas
1060/// outside any block or function.
1061pub fn parse_comma_separated(css: &str) -> Vec<Vec<ComponentValue<'_>>> {
1062    let mut values = Values::new(Tokenizer::new(css)).peekable();
1063    let mut groups = Vec::new();
1064    while values.peek().is_some() {
1065        let mut group = Vec::new();
1066        for v in values.by_ref() {
1067            if v.is(&Token::Comma) {
1068                break;
1069            }
1070            group.push(v);
1071        }
1072        groups.push(group);
1073    }
1074    groups
1075}
1076
1077/// The value of a `unicode-range` descriptor, tokenized with unicode-range
1078/// tokens: the one place CSS makes them.
1079pub fn parse_unicode_range_value(css: &str) -> Vec<ComponentValue<'_>> {
1080    Values::new(Tokenizer::with_unicode_ranges(css)).collect()
1081}
1082
1083#[cfg(test)]
1084mod tests {
1085    use super::*;
1086
1087    #[test]
1088    fn deep_nesting_parses_and_drops() {
1089        let css = "(".repeat(1_000_000);
1090        let values = parse_component_values(&css);
1091        assert_eq!(values.len(), 1);
1092        drop(values);
1093        let css = format!("a{{b:{}}}", "[".repeat(200_000));
1094        let sheet = parse_stylesheet(&css);
1095        let Rule::Qualified(rule) = sheet.rules.into_iter().next().unwrap() else {
1096            panic!()
1097        };
1098        assert_eq!(rule.block.contents(&css).items.len(), 1);
1099    }
1100
1101    #[test]
1102    fn spans_cover_rules_and_declarations() {
1103        let css = "a { color: red !important; } @x y;";
1104        let sheet = parse_stylesheet(css);
1105        assert_eq!(
1106            sheet.rules[0].span().text(css),
1107            "a { color: red !important; }"
1108        );
1109        assert_eq!(
1110            sheet.rules[1].span().text(css),
1111            "@x y;".trim_end_matches(';')
1112        );
1113        let Rule::Qualified(rule) = sheet.rules.into_iter().next().unwrap() else {
1114            panic!()
1115        };
1116        let Item::Declaration(d) = &rule.block.contents(css).items[0] else {
1117            panic!()
1118        };
1119        assert_eq!(d.span.text(css), "color: red !important");
1120        assert_eq!(d.original_text(css), "red");
1121        assert!(d.important);
1122    }
1123
1124    #[test]
1125    fn block_contents_parsed_later_match_parsing_at_once() {
1126        let css = "color: red; &:hover { b: c } --x: {a} b; d:e{f}; @media x { g: h }";
1127        let at_once = parse_block_contents(css);
1128        let wrapped = format!("{{{css}}}");
1129        let Ok(ComponentValue::Block(block)) = parse_component_value(&wrapped) else {
1130            panic!()
1131        };
1132        let later = block.contents(&wrapped);
1133        assert_eq!(at_once.items.len(), later.items.len());
1134        assert_eq!(at_once.errors.len(), later.errors.len());
1135    }
1136
1137    #[test]
1138    fn unicode_range_descriptor_gets_range_tokens() {
1139        let d = parse_declaration("unicode-range: U+0-7F, u+4??").unwrap();
1140        let ranges: Vec<_> = d
1141            .value
1142            .iter()
1143            .filter_map(|v| match v.token() {
1144                Some(Token::UnicodeRange { start, end }) => Some((*start, *end)),
1145                _ => None,
1146            })
1147            .collect();
1148        assert_eq!(ranges, [(0, 0x7f), (0x400, 0x4ff)]);
1149    }
1150}