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 // §5.5.1 (L2246-2248): an at-keyword with value
406 // "charset" is a parse error and the rule is never
407 // emitted (WPT css/css-syntax/charset-is-not-a-rule.html).
408 if rule.name.eq_ignore_ascii_case("charset") {
409 // Parse error is tolerated (errors are not
410 // surfaced); the rule is simply dropped.
411 continue;
412 }
413 rules.push(Rule::AtRule(rule));
414 }
415 }
416 _ => {
417 if let Ok(Some(rule)) = consume_a_qualified_rule(input, None, false) {
418 rules.push(Rule::QualifiedRule(rule));
419 }
420 }
421 }
422 }
423}
424
425/// §5.5.2 (L2281-2337) Consume an at-rule.
426///
427/// `nested`: when true, an unbalanced `}-token` returns the rule
428/// without consuming (caller will close the block); when false,
429/// `}-token` is part of the prelude.
430pub fn consume_an_at_rule(input: &mut TokenStream, nested: bool) -> Option<AtRule> {
431 let name = match input.consume_token() {
432 Token::AtKeyword(name) => name,
433 _ => unreachable!("consume_an_at_rule called on non-at-keyword"),
434 };
435 let mut rule = AtRule {
436 name,
437 prelude: Vec::new(),
438 declarations: None,
439 child_rules: None,
440 };
441 loop {
442 match input.next_token() {
443 Token::Semicolon | Token::Eof => {
444 input.discard_token();
445 return Some(rule);
446 }
447 Token::CloseBrace => {
448 if nested {
449 // §5.5.2 L2307-2310: nested → return rule (caller
450 // handles the closing brace).
451 return Some(rule);
452 }
453 // §5.5.2 L2313-2316: non-nested → consume to prelude
454 // (parse error, but tolerated).
455 let t = input.consume_token();
456 rule.prelude.push(ComponentValue::PreservedToken(t));
457 }
458 Token::OpenBrace => {
459 // §5.5.2 L2317-2331: consume_a_block → split into
460 // declarations + child rules.
461 let block = consume_a_block(input);
462 let (decls, rules) = split_block_contents(block);
463 rule.declarations = Some(decls);
464 rule.child_rules = Some(rules);
465 return Some(rule);
466 }
467 _ => {
468 // §5.5.2 L2333-2336: anything else → consume a
469 // component value, append to prelude.
470 rule.prelude.push(consume_a_component_value(input));
471 }
472 }
473 }
474}
475
476/// §5.5.3 (L2340-2466) Consume a qualified rule.
477///
478/// `stop_token`: optional token that aborts (returns `Ok(None)`).
479/// `nested`: passed down to consume_a_block's contents (controls
480/// `}-token` handling in nested contexts).
481///
482/// # Return values
483///
484/// - `Ok(Some(rule))` — rule successfully consumed.
485/// - `Ok(None)` — "return nothing" (e.g. EOF or stop_token).
486/// - `Err(ParseError)` — "invalid rule error" (e.g. custom-property-in-prelude
487/// at top level after consuming the block).
488pub fn consume_a_qualified_rule(
489 input: &mut TokenStream,
490 stop_token: Option<Token>,
491 nested: bool,
492) -> Result<Option<QualifiedRule>, ParseError> {
493 let mut rule = QualifiedRule {
494 prelude: Vec::new(),
495 declarations: Vec::new(),
496 child_rules: Vec::new(),
497 };
498 loop {
499 let next = input.next_token();
500 // §5.5.3 L2355-2359: EOF or stop_token → parse error, return
501 // nothing.
502 if matches!(next, Token::Eof) {
503 return Ok(None);
504 }
505 if stop_token.as_ref().is_some_and(|s| *s == next) {
506 return Ok(None);
507 }
508 match next {
509 Token::CloseBrace => {
510 // §5.5.3 L2361-2368: parse error.
511 if nested {
512 return Ok(None);
513 }
514 let t = input.consume_token();
515 rule.prelude.push(ComponentValue::PreservedToken(t));
516 }
517 Token::OpenBrace => {
518 // §5.5.3 L2370-2460.
519 // §5.5.3 L2372-2383: check if prelude looks like
520 // `--<ident> :` (custom-property-like). If so:
521 // nested → consume remnants of bad declaration, return
522 // nothing.
523 // non-nested → consume a block, return invalid rule
524 // error.
525 if looks_like_custom_property_in_prelude(&rule.prelude) {
526 if nested {
527 consume_the_remnants_of_a_bad_declaration(input, true);
528 return Ok(None);
529 } else {
530 let _ = consume_a_block(input);
531 return Err(ParseError::new(
532 "qualified rule with custom property in prelude is invalid when not nested",
533 ));
534 }
535 }
536 let block = consume_a_block(input);
537 let (decls, rules) = split_block_contents(block);
538 rule.declarations = decls;
539 rule.child_rules = rules;
540 return Ok(Some(rule));
541 }
542 _ => {
543 // §5.5.3 L2462-2465: anything else → consume a
544 // component value, append to prelude.
545 rule.prelude.push(consume_a_component_value(input));
546 }
547 }
548 }
549}
550
551/// §5.5.4 (L2469-2484) Consume a block.
552///
553/// Precondition: next token is `{-token`. Discard it, consume block
554/// contents, discard `}-token (or EOF), return the contents.
555///
556/// CSS-P1(审计 2026-09-06):规则级嵌套深度守卫。F-3 的
557/// [`MAX_NESTING_DEPTH`] 只挂在 [`consume_a_simple_block`] /
558/// [`consume_a_function`](组件值层);规则级递归环
559/// `consume_a_blocks_contents → consume_an_at_rule /
560/// consume_a_qualified_rule → consume_a_block →
561/// consume_a_blocks_contents` 中本函数直接吞掉 `{` 后递归,从不
562/// `enter_nesting` —— `@x{@x{…`(3 字节/层)或 `a{a{a{…`(2 字节/层)
563/// 约 8k-30k 层即栈溢出,仅需 ~24-60 KB 敌意 CSS,且这是 CSS 最自然的
564/// 嵌套形态(嵌套 style rule / at-rule)。此处统一 enter_nesting 封顶;
565/// 超限时 leave + 吞 token 到匹配 `}` 或 EOF(避免把深层内容泄漏成
566/// 外层兄弟规则),返回空 [`BlockContents`](`NestingTooDeep` 已由
567/// `enter_nesting` 记录在流上,调用方按既有语义处理)。
568pub fn consume_a_block(input: &mut TokenStream) -> BlockContents {
569 debug_assert!(matches!(input.next_token(), Token::OpenBrace));
570 input.discard_token();
571
572 // 超限:停止下降,吞掉本块剩余内容(配平 `{`/`}`),返回空块。
573 if input.enter_nesting().is_some() {
574 input.leave_nesting();
575 skip_to_matching_close_brace(input);
576 return BlockContents::default();
577 }
578
579 let contents = consume_a_blocks_contents(input);
580 // §5.5.4 L2481: discard the closing `}-token (or EOF if implicit).
581 input.discard_token();
582 input.leave_nesting();
583 contents
584}
585
586/// 超限恢复:消费 token 直到配平当前块的 `}`(`{` 已被调用方吞掉,
587/// 深度从 1 起算)或 EOF。深层内容被丢弃而非上提成外层兄弟规则,
588/// 保证流的 `}` 配对与调用方(consume_an_at_rule /
589/// consume_a_qualified_rule 的收尾)一致。
590fn skip_to_matching_close_brace(input: &mut TokenStream) {
591 let mut depth: u32 = 1;
592 loop {
593 match input.next_token() {
594 Token::Eof => return,
595 Token::OpenBrace => {
596 depth += 1;
597 input.discard_token();
598 }
599 Token::CloseBrace => {
600 depth -= 1;
601 input.discard_token();
602 if depth == 0 {
603 return;
604 }
605 }
606 _ => input.discard_token(),
607 }
608 }
609}
610
611/// §5.5.5 (L2486-2636) Consume a block's contents.
612///
613/// Returns a list of rules and lists-of-declarations (modeled as
614/// [`BlockContents`] carrying `Vec<Declaration>` and `Vec<Rule>`).
615/// Algorithm:
616/// - whitespace / `;` → discard.
617/// - EOF / `}` → return.
618/// - at-keyword → flush decls into rules (as `Rule::Declarations`),
619/// then `consume_an_at_rule(nested=true)`.
620/// - else → mark; `consume_a_declaration(nested=true)`; if
621/// `Some(decl)`, append to decls and discard mark. Otherwise
622/// `restore_mark`, then `consume_a_qualified_rule(nested=true,
623/// stop=`;`)`; on `Ok(Some(rule))`, flush decls to rules, append
624/// rule; on `Err(())`, flush decls to rules; on `Ok(None)`, do
625/// nothing.
626pub fn consume_a_blocks_contents(input: &mut TokenStream) -> BlockContents {
627 let mut rules: Vec<Rule> = Vec::new();
628 let mut decls: Vec<Declaration> = Vec::new();
629 loop {
630 match input.next_token() {
631 Token::Whitespace | Token::Semicolon => {
632 input.discard_token();
633 }
634 Token::Eof | Token::CloseBrace => {
635 // §5.5.5 L2514-2517: end of block — flush decls.
636 if !decls.is_empty() {
637 rules.push(Rule::Declarations(std::mem::take(&mut decls)));
638 }
639 return BlockContents { rules };
640 }
641 Token::AtKeyword(_) => {
642 // §5.5.5 L2519-2528: at-keyword flushes decls.
643 if !decls.is_empty() {
644 rules.push(Rule::Declarations(std::mem::take(&mut decls)));
645 }
646 if let Some(at_rule) = consume_an_at_rule(input, true) {
647 rules.push(Rule::AtRule(at_rule));
648 }
649 }
650 _ => {
651 // §5.5.5 L2530-2562: mark + declaration/rule ambiguity.
652 input.mark();
653 if let Some(decl) = consume_a_declaration(input, true) {
654 decls.push(decl);
655 input.discard_mark();
656 } else {
657 input.restore_mark();
658 match consume_a_qualified_rule(input, Some(Token::Semicolon), true) {
659 Ok(Some(rule)) => {
660 // §5.5.5 L2556-2561: rule returned.
661 if !decls.is_empty() {
662 rules.push(Rule::Declarations(std::mem::take(&mut decls)));
663 }
664 rules.push(Rule::QualifiedRule(rule));
665 }
666 Ok(None) => {
667 // §5.5.5 L2546-2547: "If nothing was
668 // returned, do nothing."
669 }
670 Err(_) => {
671 // §5.5.5 L2549-2554: invalid rule error.
672 if !decls.is_empty() {
673 rules.push(Rule::Declarations(std::mem::take(&mut decls)));
674 }
675 }
676 }
677 }
678 }
679 }
680 }
681}
682
683/// Result of `consume_a_block` / `consume_a_blocks_contents`. Combines
684/// a list of declarations (possibly empty) and a list of child rules.
685///
686/// Result of `consume_a_block` / `consume_a_blocks_contents`.
687///
688/// All declarations are already flushed into `rules` as
689/// `Rule::Declarations` variants per §5.5.5 L2514-2562.
690#[derive(Debug, Clone, Default)]
691pub struct BlockContents {
692 pub rules: Vec<Rule>,
693}
694
695/// Split block contents into the AtRule / QualifiedRule's expected shape.
696///
697/// §5.5.5 L2514-2562: `consume_a_blocks_contents` flushes each
698/// declaration run into a `Rule::Declarations` entry interleaved with
699/// child rules. At the AtRule/QualifiedRule boundary we flatten those
700/// runs back into the declarations list (preserving declaration order
701/// across the whole block), leaving AtRules/QualifiedRules as child
702/// rules. Previously declarations were left stranded in `child_rules`,
703/// so `AtRule.declarations` / `QualifiedRule.declarations` were always
704/// empty (P1-5 root cause).
705fn split_block_contents(block: BlockContents) -> (Vec<Declaration>, Vec<Rule>) {
706 let mut decls = Vec::new();
707 let mut rules = Vec::new();
708 for rule in block.rules {
709 match rule {
710 Rule::Declarations(d) => decls.extend(d),
711 other => rules.push(other),
712 }
713 }
714 (decls, rules)
715}
716
717/// §5.5.3 L2372-2383: Detect whether a qualified rule's prelude
718/// looks like `--<ident> :` (a custom property declaration
719/// masquerading as a rule). The first two non-whitespace tokens of
720/// the prelude must be:
721/// - Ident starting with `--`
722/// - Colon
723fn looks_like_custom_property_in_prelude(prelude: &[ComponentValue]) -> bool {
724 let mut iter = prelude
725 .iter()
726 .filter(|v| !matches!(v, ComponentValue::PreservedToken(Token::Whitespace)));
727 let first = iter.next();
728 let second = iter.next();
729 matches!(
730 (first, second),
731 (
732 Some(ComponentValue::PreservedToken(Token::Ident(name))),
733 Some(ComponentValue::PreservedToken(Token::Colon))
734 ) if name.starts_with("--")
735 )
736}
737
738#[cfg(test)]
739mod tests {
740 use super::*;
741
742 /// 构造 `open.repeat(n) + close.repeat(n)` 的输入流并解析单个
743 /// component value,返回是否触发 NestingTooDeep。
744 fn consume_deep_nesting(open: char, close: char, n: usize) -> Option<ParseError> {
745 let mut input = String::with_capacity(2 * n);
746 input.push_str(&open.to_string().repeat(n));
747 input.push_str(&close.to_string().repeat(n));
748 let mut stream = TokenStream::with_source(&input);
749 consume_a_component_value(&mut stream);
750 stream.nesting_error()
751 }
752
753 #[test]
754 fn deep_curly_nesting_records_nesting_too_deep() {
755 // 10,000 层 { 嵌套 → 不栈溢出,记录 NestingTooDeep
756 let err = consume_deep_nesting('{', '}', 10_000);
757 assert!(
758 matches!(err, Some(ParseError::NestingTooDeep { .. })),
759 "expected NestingTooDeep, got {:?}",
760 err
761 );
762 }
763
764 #[test]
765 fn deep_paren_nesting_records_nesting_too_deep() {
766 // 10,000 层 ( 嵌套 → 不栈溢出,记录 NestingTooDeep
767 let err = consume_deep_nesting('(', ')', 10_000);
768 assert!(
769 matches!(err, Some(ParseError::NestingTooDeep { .. })),
770 "expected NestingTooDeep, got {:?}",
771 err
772 );
773 }
774
775 #[test]
776 fn normal_nesting_parses_without_error() {
777 // 正常深度(100 层)→ 无 NestingTooDeep
778 let err = consume_deep_nesting('{', '}', 100);
779 assert!(
780 err.is_none(),
781 "100-level nesting must not exceed the limit, got {:?}",
782 err
783 );
784 }
785
786 #[test]
787 fn nesting_depth_limit_is_200() {
788 // F-3: 上限从 1024 收紧到 200(Firefox 平齐)。201 层触发、
789 // 200 层(≤ 上限,enter 后 depth 最大 200)不触发。
790 let err = consume_deep_nesting('(', ')', 201);
791 assert!(
792 matches!(err, Some(ParseError::NestingTooDeep { .. })),
793 "201-level nesting must exceed the limit, got {:?}",
794 err
795 );
796 let ok = consume_deep_nesting('(', ')', 200);
797 assert!(
798 ok.is_none(),
799 "200-level nesting must remain within the limit, got {:?}",
800 ok
801 );
802 }
803
804 /// CSS-P1:构造规则级嵌套输入(at-rule 或 qualified-rule 形态),
805 /// 走 parse-a-stylesheet 同款的 stylesheets-contents 消费路径,
806 /// 返回 (规则树, 是否触发 NestingTooDeep)。
807 fn rule_level_nesting(prefix: &str, n: usize, close: bool) -> (Vec<Rule>, Option<ParseError>) {
808 let mut input = prefix.repeat(n);
809 if close {
810 input.push_str(&"}".repeat(n));
811 }
812 let mut stream = TokenStream::with_source(&input);
813 let rules = consume_a_stylesheets_contents(&mut stream);
814 (rules, stream.nesting_error())
815 }
816
817 #[test]
818 fn deep_at_rule_block_nesting_records_nesting_too_deep() {
819 // CSS-P1: `@x{@x{…` × 10,000 —— 修复前规则级递归环从不
820 // enter_nesting,约 8k-30k 层即栈溢出 abort;修复后记录
821 // NestingTooDeep 并正常返回。
822 let (rules, err) = rule_level_nesting("@x{", 10_000, false);
823 assert!(
824 matches!(err, Some(ParseError::NestingTooDeep { .. })),
825 "expected NestingTooDeep, got {:?}",
826 err
827 );
828 // 顶层只产出 1 条 @x 规则;深层内容被丢弃而非上提。
829 assert_eq!(rules.len(), 1, "deep nesting must not spill into siblings");
830 }
831
832 #[test]
833 fn deep_qualified_rule_block_nesting_records_nesting_too_deep() {
834 // CSS-P1: `a{a{a{…`(2 字节/层,规则级嵌套的最廉价形态)。
835 let (rules, err) = rule_level_nesting("a{", 10_000, false);
836 assert!(
837 matches!(err, Some(ParseError::NestingTooDeep { .. })),
838 "expected NestingTooDeep, got {:?}",
839 err
840 );
841 assert_eq!(rules.len(), 1, "deep nesting must not spill into siblings");
842 }
843
844 #[test]
845 fn deep_at_rule_nesting_with_balanced_closes_terminates() {
846 // 配平闭合形态:超限块的恢复必须配平 `{`/`}` 吞到匹配的
847 // `}`,不能把深层内容泄漏成外层兄弟规则。
848 let (rules, err) = rule_level_nesting("@x{", 10_000, true);
849 assert!(
850 matches!(err, Some(ParseError::NestingTooDeep { .. })),
851 "expected NestingTooDeep, got {:?}",
852 err
853 );
854 assert_eq!(
855 rules.len(),
856 1,
857 "balanced deep nesting must stay inside the single top rule"
858 );
859 }
860
861 #[test]
862 fn normal_rule_nesting_parses_without_error() {
863 // 正常深度(100 层规则嵌套)→ 不触发 NestingTooDeep,且
864 // 结构完整(每层恰好 1 条子 at-rule)。
865 let (rules, err) = rule_level_nesting("@x{", 100, true);
866 assert!(
867 err.is_none(),
868 "100-level rule nesting must not trip the limit, got {err:?}"
869 );
870 assert_eq!(rules.len(), 1);
871 let mut depth = 0usize;
872 let mut current: Option<&Rule> = rules.first();
873 while let Some(rule) = current {
874 depth += 1;
875 current = match rule {
876 Rule::AtRule(ar) => ar
877 .child_rules
878 .as_ref()
879 .and_then(|kids| kids.first())
880 .map(|r| r as &Rule),
881 _ => None,
882 };
883 }
884 assert_eq!(
885 depth, 100,
886 "expected 100-level nested at-rules, got {depth}"
887 );
888 }
889}