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