Skip to main content

muskitty_css_parser/
algorithms.rs

1//! §5.5 Parser Algorithms.
2//!
3//! Implementation of the 11 algorithms defined in CSS Syntax Module
4//! Level 3 §5.5. This module covers:
5//! - CP-3 (lower-level algorithms): §5.5.7-§5.5.11.
6//! - CP-4 (declaration algorithms): §5.5.6.
7//! - CP-5 (stylesheet/rule/block algorithms): §5.5.1-§5.5.5.
8
9use crate::token_stream::TokenStream;
10use crate::types::{
11    AtRule, BlockKind, ComponentValue, Declaration, Function, ParseError, QualifiedRule, Rule,
12    SimpleBlock,
13};
14use muskitty_css_tokenizer::Token;
15
16/// §5.5.8 (L2776-2796) Consume a component value.
17///
18/// Dispatch on the next token:
19/// - `{-token` / `[-token` / `(-token` → consume_a_simple_block
20/// - `function-token` → consume_a_function
21/// - anything else → consume and return the token as PreservedToken
22pub fn consume_a_component_value(input: &mut TokenStream) -> ComponentValue {
23    match input.next_token() {
24        Token::OpenBrace | Token::OpenBracket | Token::OpenParen => {
25            ComponentValue::SimpleBlock(consume_a_simple_block(input))
26        }
27        Token::Function(_) => ComponentValue::Function(consume_a_function(input)),
28        other => {
29            input.consume_token();
30            ComponentValue::PreservedToken(other)
31        }
32    }
33}
34
35/// §5.5.9 (L2799-2829) Consume a simple block.
36///
37/// Precondition: next token is `{-token` / `[-token` / `(-token`. The
38/// mirror variant becomes the ending token (e.g. `[` → `]`).
39/// Repeatedly consume component values until the ending token or EOF.
40pub fn consume_a_simple_block(input: &mut TokenStream) -> SimpleBlock {
41    let opening = input.next_token();
42    let kind = match opening {
43        Token::OpenBrace => BlockKind::Curly,
44        Token::OpenBracket => BlockKind::Square,
45        Token::OpenParen => BlockKind::Paren,
46        _ => unreachable!("consume_a_simple_block called on non-opening token"),
47    };
48    let ending = match kind {
49        BlockKind::Curly => Token::CloseBrace,
50        BlockKind::Square => Token::CloseBracket,
51        BlockKind::Paren => Token::CloseParen,
52    };
53    // §5.5.9 L2818: discard the opening token.
54    input.discard_token();
55
56    // §5.5 递归保护:超过 MAX_NESTING_DEPTH 时记录 NestingTooDeep 并
57    // 停止下降(返回空 block,不再递归),避免恶意 CSS 触发栈溢出。
58    if input.enter_nesting().is_some() {
59        input.leave_nesting();
60        return SimpleBlock {
61            kind,
62            value: Vec::new(),
63        };
64    }
65
66    let mut block = SimpleBlock {
67        kind,
68        value: Vec::new(),
69    };
70    loop {
71        // §5.5.9 L2822-2825: EOF or ending token → discard, return block.
72        let next = input.next_token();
73        if matches!(next, Token::Eof) || next == ending {
74            input.discard_token();
75            input.leave_nesting();
76            return block;
77        }
78        // §5.5.9 L2827-2829: anything else → consume a component value
79        // and append.
80        block.value.push(consume_a_component_value(input));
81    }
82}
83
84/// §5.5.10 (L2832-2854) Consume a function.
85///
86/// Precondition: next token is a `function-token`. Consume the function
87/// token, then consume component values until `)-token` or EOF.
88pub fn consume_a_function(input: &mut TokenStream) -> Function {
89    let name = match input.consume_token() {
90        Token::Function(name) => name,
91        _ => unreachable!("consume_a_function called on non-function token"),
92    };
93    let mut function = Function {
94        name,
95        value: Vec::new(),
96    };
97
98    // §5.5 递归保护:与 consume_a_simple_block 相同,超限即停止下降。
99    if input.enter_nesting().is_some() {
100        input.leave_nesting();
101        return function;
102    }
103
104    loop {
105        // §5.5.10 L2847-2850: EOF or `)-token` → discard, return function.
106        match input.next_token() {
107            Token::Eof | Token::CloseParen => {
108                input.discard_token();
109                input.leave_nesting();
110                return function;
111            }
112            // §5.5.10 L2852-2854: anything else → consume a component
113            // value and append.
114            _ => function.value.push(consume_a_component_value(input)),
115        }
116    }
117}
118
119/// §5.5.7 (L2745-2774) Consume a list of component values.
120///
121/// `stop_token`: optional token that ends the list (e.g. `;` for
122/// declarations). `nested`: when true, an unbalanced `}-token` ends
123/// the list without consuming; when false, `}-token` is a parse
124/// error and is consumed into the list.
125pub fn consume_a_list_of_component_values(
126    input: &mut TokenStream,
127    stop_token: Option<Token>,
128    nested: bool,
129) -> Vec<ComponentValue> {
130    let mut values = Vec::new();
131    loop {
132        let next = input.next_token();
133        // §5.5.7 L2757-2759: EOF → return values.
134        if matches!(next, Token::Eof) {
135            return values;
136        }
137        // §5.5.7 L2757-2759: stop_token → return values.
138        if stop_token.as_ref().is_some_and(|s| *s == next) {
139            return values;
140        }
141        match next {
142            Token::CloseBrace => {
143                if nested {
144                    // §5.5.7 L2761-2764: nested → return values without
145                    // consuming the `}-token (caller handles it).
146                    return values;
147                }
148                // §5.5.7 L2766-2769: parse error. Consume and append.
149                input.consume_token();
150                values.push(ComponentValue::PreservedToken(next));
151            }
152            // §5.5.7 L2771-2773: anything else → consume a component
153            // value and append.
154            _ => values.push(consume_a_component_value(input)),
155        }
156    }
157}
158
159/// §5.5.11 (L2857-2872) Consume the value of a
160/// `@font-face/unicode-range` descriptor.
161///
162/// Tokenize `input_string` with `unicode_ranges_allowed=true`, then
163/// consume a list of component values from the resulting stream.
164///
165/// Per §5.5.11 L2869-2871 note: "The existence of this algorithm is
166/// due to a design mistake in early CSS. It should never be
167/// reproduced."
168pub fn consume_a_unicode_range_value(input_string: &str) -> Vec<ComponentValue> {
169    use muskitty_css_tokenizer::{CssTokenizer, Tokenizer};
170    let mut tz = CssTokenizer::new(input_string);
171    tz.set_unicode_ranges_allowed(true);
172    let mut tokens: Vec<Token> = Vec::new();
173    while let Some(token) = tz.next_token() {
174        let is_eof = matches!(token, Token::Eof);
175        tokens.push(token);
176        if is_eof {
177            break;
178        }
179    }
180    let mut stream = TokenStream::new(tokens);
181    consume_a_list_of_component_values(&mut stream, None, false)
182}
183
184// ─── §5.5.6 Declaration algorithms ───────────────────────────────────
185
186/// §5.5.6 (L2639-2717) Consume a declaration.
187///
188/// `nested`: when true, an unbalanced `}-token` returns `None` without
189/// consuming (caller will handle the closing brace); when false, it
190/// is consumed as part of the declaration's value.
191///
192/// # Algorithm steps
193///
194/// 1. If next token is ident, consume it as the declaration name.
195///    Otherwise, consume remnants of a bad declaration, return `None`.
196/// 2. Discard whitespace.
197/// 3. If next token is `:`, discard it. Otherwise, bad declaration,
198///    return `None`.
199/// 4. Discard whitespace.
200/// 5. Consume a list of component values with `;` as stop token.
201/// 6. If last two non-whitespace values are `!` + `important` (ASCII
202///    case-insensitive), remove them and set `important` flag.
203/// 7. Strip trailing whitespace tokens.
204/// 8. Custom property (`--foo`): set `original_text` to the source text
205///    spanning the value tokens. Otherwise, if value contains a top-level
206///    {}-block AND any other non-ws value, return `None` (only the whole
207///    value may be a {}-block for non-custom properties).
208/// 9. (§5.5.6 L2707-2712: `unicode-range` descriptor handling
209///    deferred — requires source-text tracking.)
210pub fn consume_a_declaration(input: &mut TokenStream, nested: bool) -> Option<Declaration> {
211    // Step 1 (§5.5.6 L2650-2659): ident-token as declaration name.
212    let name = match input.next_token() {
213        Token::Ident(name) => {
214            input.consume_token();
215            name
216        }
217        _ => {
218            consume_the_remnants_of_a_bad_declaration(input, nested);
219            return None;
220        }
221    };
222
223    // Step 2 (§5.5.6 L2661-2662): discard whitespace.
224    input.discard_whitespace();
225
226    // Step 3 (§5.5.6 L2664-2671): colon.
227    match input.next_token() {
228        Token::Colon => input.discard_token(),
229        _ => {
230            consume_the_remnants_of_a_bad_declaration(input, nested);
231            return None;
232        }
233    }
234
235    // Step 4 (§5.5.6 L2673-2674): discard whitespace.
236    input.discard_whitespace();
237
238    // 记录 value 消费前的 token index,供 §5.5.6 original_text 使用。
239    let value_start_index = input.index;
240
241    // Step 5 (§5.5.6 L2676-2680): consume value until `;`.
242    let mut value = consume_a_list_of_component_values(input, Some(Token::Semicolon), nested);
243
244    // value_end_index 指向 `;` 或 EOF(consume_a_list_of_component_values
245    // 消费到 stop token 前停止,不消费 stop token 本身)。
246    let value_end_index = input.index;
247
248    // Step 6 (§5.5.6 L2682-2687): strip !important from the tail.
249    let important = strip_important(&mut value);
250
251    // Step 7 (§5.5.6 L2689-2691): strip trailing whitespace.
252    while matches!(
253        value.last(),
254        Some(ComponentValue::PreservedToken(Token::Whitespace))
255    ) {
256        value.pop();
257    }
258
259    let mut decl = Declaration {
260        name,
261        value,
262        important,
263        original_text: None,
264    };
265
266    // Step 8 (§5.5.6 L2693-2705): custom property original_text +
267    // top-level {}-block validity check.
268    if is_custom_property_name(&decl.name) {
269        // §5.5.6 L2693-2698: set original_text to the source text
270        // spanning the value tokens (colon 后、semicolon/EOF 前)。
271        decl.original_text = input
272            .source_slice(value_start_index, value_end_index)
273            .map(|s| s.to_string());
274    } else {
275        // §5.5.6 L2700-2705: if value contains a top-level {}-block
276        // AND any other non-whitespace value, return nothing.
277        if has_top_level_curly_block_with_other_values(&decl.value) {
278            return None;
279        }
280    }
281
282    // §5.5.6 L2707-2712: `unicode-range` descriptor handling deferred
283    // (requires source-text tracking for re-tokenization).
284
285    // §5.5.6 L2714-2717: if the declaration is valid, return it;
286    // otherwise return nothing. We treat "valid" as "we successfully
287    // parsed a name + colon + value", which is the syntactic validity.
288    // Grammar-level validity is left to higher-level callers (CSSOM).
289    Some(decl)
290}
291
292/// §5.5.6 (L2721-2741) Consume the remnants of a bad declaration.
293///
294/// Repeatedly process input:
295/// - EOF or `;` → discard, return.
296/// - `}-token`: if `nested`, return without consuming; else discard.
297/// - anything else → consume a component value (discard result).
298pub fn consume_the_remnants_of_a_bad_declaration(input: &mut TokenStream, nested: bool) {
299    loop {
300        match input.next_token() {
301            Token::Eof | Token::Semicolon => {
302                input.discard_token();
303                return;
304            }
305            Token::CloseBrace => {
306                if nested {
307                    return;
308                }
309                input.discard_token();
310            }
311            _ => {
312                // Discard the consumed component value.
313                let _ = consume_a_component_value(input);
314            }
315        }
316    }
317}
318
319/// §5.5.6 step 6 (L2682-2687): If the last two non-whitespace values are
320/// a `!` delim token followed by an `important` ident (ASCII
321/// case-insensitive), remove them (and any trailing whitespace
322/// between/after) and return `true`. Otherwise return `false`.
323///
324/// This does NOT strip trailing whitespace after the `!important` —
325/// that is the caller's responsibility (step 7).
326fn strip_important(value: &mut Vec<ComponentValue>) -> bool {
327    // Find the index just past the last non-whitespace value.
328    let mut end = value.len();
329    while end > 0
330        && matches!(
331            value[end - 1],
332            ComponentValue::PreservedToken(Token::Whitespace)
333        )
334    {
335        end -= 1;
336    }
337    if end < 2 {
338        return false;
339    }
340    let last = &value[end - 1];
341    let prev = &value[end - 2];
342    let is_important_ident = |v: &ComponentValue| match v {
343        ComponentValue::PreservedToken(Token::Ident(s)) => s.eq_ignore_ascii_case("important"),
344        _ => false,
345    };
346    let is_bang_delim =
347        |v: &ComponentValue| matches!(v, ComponentValue::PreservedToken(Token::Delim('!')));
348    if is_bang_delim(prev) && is_important_ident(last) {
349        // Truncate to `end - 2`, removing the `!important` (and any
350        // trailing whitespace after it).
351        value.truncate(end - 2);
352        return true;
353    }
354    false
355}
356
357/// §5.5.6 L2693: A "custom property name string" is an ident-token
358/// whose value starts with `--` (two hyphens).
359fn is_custom_property_name(name: &str) -> bool {
360    name.starts_with("--")
361}
362
363/// §5.5.6 L2700-2705: A declaration value contains a top-level
364/// {}-block AND any other non-whitespace value. (Only the whole
365/// value may be a {}-block for non-custom properties.)
366fn has_top_level_curly_block_with_other_values(value: &[ComponentValue]) -> bool {
367    let mut has_curly_block = false;
368    let mut has_other = false;
369    for v in value {
370        match v {
371            ComponentValue::SimpleBlock(SimpleBlock {
372                kind: BlockKind::Curly,
373                ..
374            }) => {
375                has_curly_block = true;
376            }
377            ComponentValue::PreservedToken(Token::Whitespace) => {}
378            _ => {
379                has_other = true;
380            }
381        }
382    }
383    has_curly_block && has_other
384}
385
386// ─── §5.5.1-§5.5.5 Stylesheet/rule/block algorithms ──────────────────
387
388/// §5.5.1 (L2223-2279) Consume a stylesheet's contents.
389///
390/// Repeatedly process input:
391/// - whitespace / CDO / CDC → discard.
392/// - EOF → return rules.
393/// - at-keyword → consume_an_at_rule; if `Some`, append.
394/// - else → consume_a_qualified_rule; if `Some(rule)`, append.
395pub fn consume_a_stylesheets_contents(input: &mut TokenStream) -> Vec<Rule> {
396    let mut rules = Vec::new();
397    loop {
398        match input.next_token() {
399            Token::Whitespace | Token::Cdo | Token::Cdc => {
400                input.discard_token();
401            }
402            Token::Eof => return rules,
403            Token::AtKeyword(_) => {
404                if let Some(rule) = consume_an_at_rule(input, false) {
405                    rules.push(Rule::AtRule(rule));
406                }
407            }
408            _ => {
409                if let Ok(Some(rule)) = consume_a_qualified_rule(input, None, false) {
410                    rules.push(Rule::QualifiedRule(rule));
411                }
412            }
413        }
414    }
415}
416
417/// §5.5.2 (L2281-2337) Consume an at-rule.
418///
419/// `nested`: when true, an unbalanced `}-token` returns the rule
420/// without consuming (caller will close the block); when false,
421/// `}-token` is part of the prelude.
422pub fn consume_an_at_rule(input: &mut TokenStream, nested: bool) -> Option<AtRule> {
423    let name = match input.consume_token() {
424        Token::AtKeyword(name) => name,
425        _ => unreachable!("consume_an_at_rule called on non-at-keyword"),
426    };
427    let mut rule = AtRule {
428        name,
429        prelude: Vec::new(),
430        declarations: None,
431        child_rules: None,
432    };
433    loop {
434        match input.next_token() {
435            Token::Semicolon | Token::Eof => {
436                input.discard_token();
437                return Some(rule);
438            }
439            Token::CloseBrace => {
440                if nested {
441                    // §5.5.2 L2307-2310: nested → return rule (caller
442                    // handles the closing brace).
443                    return Some(rule);
444                }
445                // §5.5.2 L2313-2316: non-nested → consume to prelude
446                // (parse error, but tolerated).
447                let t = input.consume_token();
448                rule.prelude.push(ComponentValue::PreservedToken(t));
449            }
450            Token::OpenBrace => {
451                // §5.5.2 L2317-2331: consume_a_block → split into
452                // declarations + child rules.
453                let block = consume_a_block(input);
454                let (decls, rules) = split_block_contents(block);
455                rule.declarations = Some(decls);
456                rule.child_rules = Some(rules);
457                return Some(rule);
458            }
459            _ => {
460                // §5.5.2 L2333-2336: anything else → consume a
461                // component value, append to prelude.
462                rule.prelude.push(consume_a_component_value(input));
463            }
464        }
465    }
466}
467
468/// §5.5.3 (L2340-2466) Consume a qualified rule.
469///
470/// `stop_token`: optional token that aborts (returns `Ok(None)`).
471/// `nested`: passed down to consume_a_block's contents (controls
472/// `}-token` handling in nested contexts).
473///
474/// # Return values
475///
476/// - `Ok(Some(rule))` — rule successfully consumed.
477/// - `Ok(None)` — "return nothing" (e.g. EOF or stop_token).
478/// - `Err(ParseError)` — "invalid rule error" (e.g. custom-property-in-prelude
479///   at top level after consuming the block).
480pub fn consume_a_qualified_rule(
481    input: &mut TokenStream,
482    stop_token: Option<Token>,
483    nested: bool,
484) -> Result<Option<QualifiedRule>, ParseError> {
485    let mut rule = QualifiedRule {
486        prelude: Vec::new(),
487        declarations: Vec::new(),
488        child_rules: Vec::new(),
489    };
490    loop {
491        let next = input.next_token();
492        // §5.5.3 L2355-2359: EOF or stop_token → parse error, return
493        // nothing.
494        if matches!(next, Token::Eof) {
495            return Ok(None);
496        }
497        if stop_token.as_ref().is_some_and(|s| *s == next) {
498            return Ok(None);
499        }
500        match next {
501            Token::CloseBrace => {
502                // §5.5.3 L2361-2368: parse error.
503                if nested {
504                    return Ok(None);
505                }
506                let t = input.consume_token();
507                rule.prelude.push(ComponentValue::PreservedToken(t));
508            }
509            Token::OpenBrace => {
510                // §5.5.3 L2370-2460.
511                // §5.5.3 L2372-2383: check if prelude looks like
512                // `--<ident> :` (custom-property-like). If so:
513                //   nested → consume remnants of bad declaration, return
514                //           nothing.
515                //   non-nested → consume a block, return invalid rule
516                //                error.
517                if looks_like_custom_property_in_prelude(&rule.prelude) {
518                    if nested {
519                        consume_the_remnants_of_a_bad_declaration(input, true);
520                        return Ok(None);
521                    } else {
522                        let _ = consume_a_block(input);
523                        return Err(ParseError::new(
524                            "qualified rule with custom property in prelude is invalid when not nested",
525                        ));
526                    }
527                }
528                let block = consume_a_block(input);
529                let (decls, rules) = split_block_contents(block);
530                rule.declarations = decls;
531                rule.child_rules = rules;
532                return Ok(Some(rule));
533            }
534            _ => {
535                // §5.5.3 L2462-2465: anything else → consume a
536                // component value, append to prelude.
537                rule.prelude.push(consume_a_component_value(input));
538            }
539        }
540    }
541}
542
543/// §5.5.4 (L2469-2484) Consume a block.
544///
545/// Precondition: next token is `{-token`. Discard it, consume block
546/// contents, discard `}-token (or EOF), return the contents.
547pub fn consume_a_block(input: &mut TokenStream) -> BlockContents {
548    debug_assert!(matches!(input.next_token(), Token::OpenBrace));
549    input.discard_token();
550    let contents = consume_a_blocks_contents(input);
551    // §5.5.4 L2481: discard the closing `}-token (or EOF if implicit).
552    input.discard_token();
553    contents
554}
555
556/// §5.5.5 (L2486-2636) Consume a block's contents.
557///
558/// Returns a list of rules and lists-of-declarations (modeled as
559/// [`BlockContents`] carrying `Vec<Declaration>` and `Vec<Rule>`).
560/// Algorithm:
561/// - whitespace / `;` → discard.
562/// - EOF / `}` → return.
563/// - at-keyword → flush decls into rules (as `Rule::Declarations`),
564///   then `consume_an_at_rule(nested=true)`.
565/// - else → mark; `consume_a_declaration(nested=true)`; if
566///   `Some(decl)`, append to decls and discard mark. Otherwise
567///   `restore_mark`, then `consume_a_qualified_rule(nested=true,
568///   stop=`;`)`; on `Ok(Some(rule))`, flush decls to rules, append
569///   rule; on `Err(())`, flush decls to rules; on `Ok(None)`, do
570///   nothing.
571pub fn consume_a_blocks_contents(input: &mut TokenStream) -> BlockContents {
572    let mut rules: Vec<Rule> = Vec::new();
573    let mut decls: Vec<Declaration> = Vec::new();
574    loop {
575        match input.next_token() {
576            Token::Whitespace | Token::Semicolon => {
577                input.discard_token();
578            }
579            Token::Eof | Token::CloseBrace => {
580                // §5.5.5 L2514-2517: end of block — flush decls.
581                if !decls.is_empty() {
582                    rules.push(Rule::Declarations(std::mem::take(&mut decls)));
583                }
584                return BlockContents { rules };
585            }
586            Token::AtKeyword(_) => {
587                // §5.5.5 L2519-2528: at-keyword flushes decls.
588                if !decls.is_empty() {
589                    rules.push(Rule::Declarations(std::mem::take(&mut decls)));
590                }
591                if let Some(at_rule) = consume_an_at_rule(input, true) {
592                    rules.push(Rule::AtRule(at_rule));
593                }
594            }
595            _ => {
596                // §5.5.5 L2530-2562: mark + declaration/rule ambiguity.
597                input.mark();
598                if let Some(decl) = consume_a_declaration(input, true) {
599                    decls.push(decl);
600                    input.discard_mark();
601                } else {
602                    input.restore_mark();
603                    match consume_a_qualified_rule(input, Some(Token::Semicolon), true) {
604                        Ok(Some(rule)) => {
605                            // §5.5.5 L2556-2561: rule returned.
606                            if !decls.is_empty() {
607                                rules.push(Rule::Declarations(std::mem::take(&mut decls)));
608                            }
609                            rules.push(Rule::QualifiedRule(rule));
610                        }
611                        Ok(None) => {
612                            // §5.5.5 L2546-2547: "If nothing was
613                            // returned, do nothing."
614                        }
615                        Err(_) => {
616                            // §5.5.5 L2549-2554: invalid rule error.
617                            if !decls.is_empty() {
618                                rules.push(Rule::Declarations(std::mem::take(&mut decls)));
619                            }
620                        }
621                    }
622                }
623            }
624        }
625    }
626}
627
628/// Result of `consume_a_block` / `consume_a_blocks_contents`. Combines
629/// a list of declarations (possibly empty) and a list of child rules.
630///
631/// Result of `consume_a_block` / `consume_a_blocks_contents`.
632///
633/// All declarations are already flushed into `rules` as
634/// `Rule::Declarations` variants per §5.5.5 L2514-2562.
635#[derive(Debug, Clone, Default)]
636pub struct BlockContents {
637    pub rules: Vec<Rule>,
638}
639
640/// Split block contents into the AtRule / QualifiedRule's expected shape.
641///
642/// §5.5.5 L2514-2562: `consume_a_blocks_contents` flushes each
643/// declaration run into a `Rule::Declarations` entry interleaved with
644/// child rules. At the AtRule/QualifiedRule boundary we flatten those
645/// runs back into the declarations list (preserving declaration order
646/// across the whole block), leaving AtRules/QualifiedRules as child
647/// rules. Previously declarations were left stranded in `child_rules`,
648/// so `AtRule.declarations` / `QualifiedRule.declarations` were always
649/// empty (P1-5 root cause).
650fn split_block_contents(block: BlockContents) -> (Vec<Declaration>, Vec<Rule>) {
651    let mut decls = Vec::new();
652    let mut rules = Vec::new();
653    for rule in block.rules {
654        match rule {
655            Rule::Declarations(d) => decls.extend(d),
656            other => rules.push(other),
657        }
658    }
659    (decls, rules)
660}
661
662/// §5.5.3 L2372-2383: Detect whether a qualified rule's prelude
663/// looks like `--<ident> :` (a custom property declaration
664/// masquerading as a rule). The first two non-whitespace tokens of
665/// the prelude must be:
666///   - Ident starting with `--`
667///   - Colon
668fn looks_like_custom_property_in_prelude(prelude: &[ComponentValue]) -> bool {
669    let mut iter = prelude
670        .iter()
671        .filter(|v| !matches!(v, ComponentValue::PreservedToken(Token::Whitespace)));
672    let first = iter.next();
673    let second = iter.next();
674    matches!(
675        (first, second),
676        (
677            Some(ComponentValue::PreservedToken(Token::Ident(name))),
678            Some(ComponentValue::PreservedToken(Token::Colon))
679        ) if name.starts_with("--")
680    )
681}
682
683#[cfg(test)]
684mod tests {
685    use super::*;
686
687    /// 构造 `open.repeat(n) + close.repeat(n)` 的输入流并解析单个
688    /// component value,返回是否触发 NestingTooDeep。
689    fn consume_deep_nesting(open: char, close: char, n: usize) -> Option<ParseError> {
690        let mut input = String::with_capacity(2 * n);
691        input.push_str(&open.to_string().repeat(n));
692        input.push_str(&close.to_string().repeat(n));
693        let mut stream = TokenStream::with_source(&input);
694        consume_a_component_value(&mut stream);
695        stream.nesting_error()
696    }
697
698    #[test]
699    fn deep_curly_nesting_records_nesting_too_deep() {
700        // 10,000 层 { 嵌套 → 不栈溢出,记录 NestingTooDeep
701        let err = consume_deep_nesting('{', '}', 10_000);
702        assert!(
703            matches!(err, Some(ParseError::NestingTooDeep { .. })),
704            "expected NestingTooDeep, got {:?}",
705            err
706        );
707    }
708
709    #[test]
710    fn deep_paren_nesting_records_nesting_too_deep() {
711        // 10,000 层 ( 嵌套 → 不栈溢出,记录 NestingTooDeep
712        let err = consume_deep_nesting('(', ')', 10_000);
713        assert!(
714            matches!(err, Some(ParseError::NestingTooDeep { .. })),
715            "expected NestingTooDeep, got {:?}",
716            err
717        );
718    }
719
720    #[test]
721    fn normal_nesting_parses_without_error() {
722        // 正常深度(100 层)→ 无 NestingTooDeep
723        let err = consume_deep_nesting('{', '}', 100);
724        assert!(
725            err.is_none(),
726            "100-level nesting must not exceed the limit, got {:?}",
727            err
728        );
729    }
730}