Skip to main content

parsec_css/
deep.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! A whole stylesheet at once: each `{}` block's contents parsed straight
5//! from the tokenizer as the parser reaches it, rather than kept as
6//! component values and walked a second time. That's how the current
7//! draft's "consume an at-rule" and "consume a qualified rule" read, with
8//! every block parsed as declarations and rules.
9//!
10//! A declaration is tried first wherever an ident starts one, as the spec
11//! says. When it isn't one (`a:hover { … }` nested is a rule), the
12//! tokenizer goes back to the ident and the text is read again as a rule:
13//! the spec's "put back", with a position instead of a list.
14//!
15//! The open blocks are a stack, as in [`Values`], so nesting doesn't
16//! recurse; their items share one buffer, so each block's list is
17//! allocated once, at its size, when it closes.
18
19use std::borrow::Cow;
20
21use crate::parser::{
22    AtRule, Block, ComponentValue, Declaration, ErrorKind, Item, ParseError, QualifiedRule, Rule,
23    Stylesheet, Values, looks_like_custom_property, take_tail, unicode_range_tokens, value_plan,
24};
25use crate::tokenizer::{Span, Token, Tokenizer};
26
27/// A rule whose block is open: what goes before the block.
28enum Head<'a> {
29    At {
30        name: Cow<'a, str>,
31        prelude: Vec<ComponentValue<'a>>,
32        start: usize,
33    },
34    Qualified {
35        prelude: Vec<ComponentValue<'a>>,
36        start: usize,
37    },
38}
39
40struct Open<'a> {
41    head: Head<'a>,
42    /// Where the `{` is.
43    start: usize,
44    /// Where its items start in the shared buffer.
45    at: usize,
46}
47
48struct Deep<'a> {
49    src: &'a str,
50    values: Values<'a>,
51    open: Vec<Open<'a>>,
52    items: Vec<Item<'a, Block<'a>>>,
53    rules: Vec<Rule<'a, Block<'a>>>,
54    /// Where a prelude or a value collects, reused from one to the next.
55    scratch: Vec<ComponentValue<'a>>,
56    errors: Vec<ParseError>,
57}
58
59impl<'a> Deep<'a> {
60    fn next_token(&mut self) -> Option<(Token<'a>, Span)> {
61        self.values.tokens.next_token()
62    }
63
64    /// Goes back to `position`, to read what's there again.
65    fn back_to(&mut self, position: usize) {
66        self.values.tokens.reset(position);
67    }
68
69    fn error(&mut self, kind: ErrorKind, start: usize, end: usize) {
70        self.errors.push(ParseError {
71            kind,
72            span: Span::new(start, end.max(start)),
73        });
74    }
75
76    fn place(&mut self, rule: Rule<'a, Block<'a>>) {
77        if self.open.is_empty() {
78            self.rules.push(rule);
79        } else {
80            self.items.push(Item::Rule(rule));
81        }
82    }
83
84    fn run(mut self) -> Stylesheet<'a, Block<'a>> {
85        while let Some((token, span)) = self.next_token() {
86            if self.open.is_empty() {
87                // A stylesheet's contents, with `<!--` and `-->` skipped.
88                match token {
89                    Token::Whitespace | Token::Cdo | Token::Cdc => {}
90                    Token::AtKeyword(name) => self.at_rule(name, span, false),
91                    token => self.qualified_rule(token, span, false),
92                }
93                continue;
94            }
95            // A block's contents.
96            match token {
97                Token::Whitespace | Token::Semicolon => {}
98                Token::RightBrace => self.close(span.end),
99                Token::AtKeyword(name) => self.at_rule(name, span, true),
100                Token::Ident(name) => {
101                    if !self.declaration(name, span) {
102                        self.back_to(span.start);
103                        let (token, span) = self.next_token().unwrap();
104                        self.qualified_rule(token, span, true);
105                    }
106                }
107                token => self.qualified_rule(token, span, true),
108            }
109        }
110        // Everything still open closes at the end of the input.
111        while !self.open.is_empty() {
112            self.close(self.src.len());
113        }
114        Stylesheet {
115            rules: self.rules,
116            errors: self.errors,
117        }
118    }
119
120    /// The innermost open block ends at `end`, and its rule with it.
121    fn close(&mut self, end: usize) {
122        let open = self.open.pop().unwrap();
123        let block = Block {
124            items: take_tail(&mut self.items, open.at),
125            span: Span::new(open.start, end),
126        };
127        let rule = match open.head {
128            Head::At {
129                name,
130                prelude,
131                start,
132            } => Rule::At(AtRule {
133                name,
134                prelude,
135                block: Some(block),
136                span: Span::new(start, end),
137            }),
138            Head::Qualified { prelude, start } => Rule::Qualified(QualifiedRule {
139                prelude,
140                block,
141                span: Span::new(start, end),
142            }),
143        };
144        self.place(rule);
145    }
146
147    fn open_block(&mut self, head: Head<'a>, brace: Span) {
148        self.open.push(Open {
149            head,
150            start: brace.start,
151            at: self.items.len(),
152        });
153    }
154
155    /// An at-rule, after its at-keyword: to a `;`, or a block it opens.
156    fn at_rule(&mut self, name: Cow<'a, str>, keyword: Span, nested: bool) {
157        let mut end = keyword.end;
158        self.scratch.clear();
159        while let Some((token, span)) = self.next_token() {
160            match token {
161                Token::Semicolon => break,
162                Token::RightBrace if nested => {
163                    self.back_to(span.start);
164                    break;
165                }
166                Token::LeftBrace => {
167                    let prelude = take_tail(&mut self.scratch, 0);
168                    let head = Head::At {
169                        name,
170                        prelude,
171                        start: keyword.start,
172                    };
173                    return self.open_block(head, span);
174                }
175                token => {
176                    let value = self.values.whole(token, span);
177                    end = value.span().end;
178                    self.scratch.push(value);
179                }
180            }
181        }
182        let rule = Rule::At(AtRule {
183            name,
184            prelude: take_tail(&mut self.scratch, 0),
185            block: None,
186            span: Span::new(keyword.start, end),
187        });
188        self.place(rule);
189    }
190
191    /// A qualified rule from its first token. Nested, a `;` ends it as a
192    /// broken declaration, and a `}` ends it with the block it's in.
193    fn qualified_rule(&mut self, token: Token<'a>, span: Span, nested: bool) {
194        let start = span.start;
195        let mut end = start;
196        self.scratch.clear();
197        let mut next = Some((token, span));
198        loop {
199            let Some((token, span)) = next.take().or_else(|| self.next_token()) else {
200                self.scratch.clear();
201                return self.error(ErrorKind::InvalidRule, start, end);
202            };
203            match token {
204                Token::Semicolon if nested => {
205                    self.scratch.clear();
206                    return self.error(ErrorKind::InvalidRule, start, end);
207                }
208                Token::RightBrace if nested => {
209                    self.back_to(span.start);
210                    self.scratch.clear();
211                    return self.error(ErrorKind::InvalidRule, start, end);
212                }
213                Token::LeftBrace => {
214                    let prelude = take_tail(&mut self.scratch, 0);
215                    if looks_like_custom_property(&prelude) {
216                        // `--x:hover {…}` is a custom property gone wrong,
217                        // never a rule; nested, the property runs to its `;`.
218                        let end = self.values.whole(Token::LeftBrace, span).span().end;
219                        if nested {
220                            self.bad_declaration_remnants();
221                        }
222                        return self.error(ErrorKind::InvalidRule, start, end);
223                    }
224                    return self.open_block(Head::Qualified { prelude, start }, span);
225                }
226                token => {
227                    let value = self.values.whole(token, span);
228                    end = value.span().end;
229                    self.scratch.push(value);
230                }
231            }
232        }
233    }
234
235    /// Past the next `;`, or up to the `}` that ends the block.
236    fn bad_declaration_remnants(&mut self) {
237        while let Some((token, span)) = self.next_token() {
238            match token {
239                Token::Semicolon => return,
240                Token::RightBrace => return self.back_to(span.start),
241                token => drop(self.values.whole(token, span)),
242            }
243        }
244    }
245
246    /// A declaration in a block, after the ident that may be its name.
247    /// False if it isn't one, with the tokenizer anywhere.
248    fn declaration(&mut self, name: Cow<'a, str>, ident: Span) -> bool {
249        let colon_end = loop {
250            match self.next_token() {
251                Some((Token::Whitespace, _)) => {}
252                Some((Token::Colon, span)) => break span.end,
253                _ => return false,
254            }
255        };
256        self.scratch.clear();
257        while let Some((token, span)) = self.next_token() {
258            match token {
259                Token::Semicolon => break,
260                Token::RightBrace => {
261                    self.back_to(span.start);
262                    break;
263                }
264                token => {
265                    let value = self.values.whole(token, span);
266                    self.scratch.push(value);
267                }
268            }
269        }
270        let Some(plan) = value_plan(&name, &self.scratch) else {
271            self.scratch.clear();
272            return false;
273        };
274        let mut value: Vec<_> = self.scratch.drain(plan.start..plan.end).collect();
275        self.scratch.clear();
276        if name.eq_ignore_ascii_case("unicode-range") && !value.is_empty() {
277            // The one place the spec retokenizes: `U+0-7F` is a range here.
278            let from = value[0].span().start;
279            let to = value[value.len() - 1].span().end;
280            value = Values::new(unicode_range_tokens(self.src, from, to)).collect();
281        }
282        self.items.push(Item::Declaration(Declaration {
283            name,
284            value,
285            important: plan.important,
286            span: Span::new(ident.start, plan.last_end.unwrap_or(colon_end)),
287        }));
288        true
289    }
290}
291
292/// Parse a stylesheet with every rule's `{}` block parsed too, as
293/// declarations and nested rules, to any depth: what
294/// [`parse_stylesheet`](crate::parse_stylesheet) and
295/// [`SimpleBlock::contents`](crate::SimpleBlock::contents) on each block
296/// make, in one pass and
297/// about 70% of the time. The errors are all in the
298/// stylesheet's list, in the order they were found.
299///
300/// ```
301/// use parsec_css::{Item, Rule};
302///
303/// let sheet = parsec_css::parse_stylesheet_deep("a { color: red; &:hover { color: blue } }");
304/// let Rule::Qualified(rule) = &sheet.rules[0] else { unreachable!() };
305/// assert!(matches!(&rule.block.items[0], Item::Declaration(d) if d.name == "color"));
306/// let Item::Rule(Rule::Qualified(hover)) = &rule.block.items[1] else { unreachable!() };
307/// assert_eq!(parsec_css::to_css(&hover.prelude), "&:hover ");
308/// ```
309pub fn parse_stylesheet_deep(css: &str) -> Stylesheet<'_, Block<'_>> {
310    Deep {
311        src: css,
312        values: Values::new(Tokenizer::new(css)),
313        open: Vec::new(),
314        items: Vec::new(),
315        rules: Vec::new(),
316        scratch: Vec::new(),
317        errors: Vec::new(),
318    }
319    .run()
320}
321
322#[cfg(test)]
323mod tests {
324    use super::*;
325
326    #[test]
327    fn deep_nesting_parses_writes_and_drops() {
328        let css = format!("{}color: red", "a{".repeat(300_000));
329        let sheet = parse_stylesheet_deep(&css);
330        assert_eq!(sheet.rules.len(), 1);
331        let written = sheet.to_string();
332        assert!(written.ends_with(&"}".repeat(300_000)));
333        drop(sheet);
334    }
335
336    #[test]
337    fn an_ident_that_starts_a_rule_is_read_again_as_one() {
338        let css = "a { b:hover { c: d } e: f; --x:y { g } h }";
339        let sheet = parse_stylesheet_deep(css);
340        let Rule::Qualified(a) = &sheet.rules[0] else {
341            panic!()
342        };
343        let kinds: Vec<_> = a
344            .block
345            .items
346            .iter()
347            .map(|i| match i {
348                Item::Declaration(d) => d.span.text(css),
349                Item::Rule(r) => r.span().text(css),
350            })
351            .collect();
352        assert_eq!(kinds, ["b:hover { c: d }", "e: f", "--x:y { g } h"]);
353    }
354}