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