muskitty_css_parser/token_stream.rs
1//! Token stream (§5.3 L1722-1814).
2//!
3//! A token stream is a struct representing a stream of tokens and/or
4//! component values. It has three fields: `tokens` (a list), `index`
5//! (current position), and `marked_indexes` (a stack of saved positions
6//! for backtracking).
7
8use crate::types::ParseError;
9use muskitty_css_tokenizer::{CssTokenizer, Token, Tokenizer};
10use std::cell::{Cell, RefCell};
11
12/// §5.5 解析器最大嵌套深度。
13///
14/// `consume_a_simple_block` / `consume_a_function` 通过
15/// `consume_a_component_value` 间接递归;恶意 CSS(如 10,000 层
16/// `{{{{...}}}}` 或 `((((...))))`)可触发栈溢出。此上限用于在
17/// 递归到达危险深度前停止下降,记录 [`ParseError::NestingTooDeep`]。
18///
19/// 参考实现(上界,留足余量):
20/// - Chromium `kMaxCSSTokenizerNestingLevel = 100`
21/// - Firefox `kMaxNesting = 200`
22/// - Servo `MAX_PARSER_NESTING_DEPTH = 100`
23///
24/// [`ParseError::NestingTooDeep`]: crate::types::ParseError::NestingTooDeep
25pub const MAX_NESTING_DEPTH: u32 = 1024;
26
27/// §5.3 L1725-1754: A token stream.
28#[derive(Debug, Clone)]
29pub struct TokenStream {
30 /// §5.3 L1730-1738: A list of tokens and/or component values. We
31 /// model component values as `Token`s here for simplicity; the
32 /// §5.5 algorithms that consume "component values" wrap tokens
33 /// into [`crate::types::ComponentValue`] at the boundary.
34 pub tokens: Vec<Token>,
35 /// §5.3 L1740-1748: An index into `tokens`, representing parsing
36 /// progress. Starts at 0. Never decreases except via
37 /// [`Self::restore_mark`].
38 pub index: usize,
39 /// §5.3 L1750-1753: A stack of index values for backtracking.
40 /// Starts empty.
41 marked_indexes: Vec<usize>,
42 /// 与 `tokens` 平行的 byte ranges。空 Vec 表示无 source tracking
43 /// (`new()` 构造的 stream 无 source)。由 [`Self::with_source`] 填充。
44 token_spans: Vec<std::ops::Range<usize>>,
45 /// 原始 source text。`None` 表示无 source tracking。
46 source: Option<String>,
47 /// §5.5 递归保护:当前嵌套深度(`consume_a_simple_block` /
48 /// `consume_a_function` 的递归深度)。进入 +1,退出 -1。
49 depth: Cell<u32>,
50 /// 嵌套深度超限时记录的错误。解析继续(按 §5.5 错误恢复语义
51 /// 停止下降),调用方可通过 [`Self::nesting_error`] 读取。
52 nesting_error: RefCell<Option<ParseError>>,
53}
54
55impl TokenStream {
56 /// §5.3: Construct a new token stream over `tokens`. The stream
57 /// implicitly appends an EOF token (§5.3 L1811-1813); we model
58 /// it by returning `Token::Eof` from [`Self::next_token`] when
59 /// index is out of bounds, rather than storing a sentinel.
60 ///
61 /// 构造的 stream **不带** source-text tracking。如需追踪原始 source
62 /// (用于 §5.5.6 `original_text`),请用 [`Self::with_source`]。
63 pub fn new(mut tokens: Vec<Token>) -> Self {
64 // Ensure an EOF token is present at the end (§5.3 L1811-1813).
65 // The tokenizer already emits one, but be defensive.
66 if tokens.last().is_none_or(|t| !matches!(t, Token::Eof)) {
67 tokens.push(Token::Eof);
68 }
69 Self {
70 tokens,
71 index: 0,
72 marked_indexes: Vec::new(),
73 token_spans: Vec::new(),
74 source: None,
75 depth: Cell::new(0),
76 nesting_error: RefCell::new(None),
77 }
78 }
79
80 /// 构造一个带 source-text tracking 的 TokenStream。
81 ///
82 /// tokenize `source` 并记录每个 token 的 byte range,使
83 /// [`Self::source_slice`] 能返回原始 source 片段。供 §5.5.6
84 /// `original_text`(custom property)使用。
85 pub fn with_source(source: &str) -> Self {
86 let mut tz = CssTokenizer::new(source);
87 // 建立 char-index → byte-offset 映射(tokenizer 内部用 char 索引)
88 let char_to_byte: Vec<usize> = source.char_indices().map(|(i, _)| i).collect();
89 let source_len = source.len();
90
91 let mut tokens = Vec::new();
92 let mut spans = Vec::new();
93 while let Some((token, char_range)) = tz.next_token_with_span() {
94 let start_byte = char_to_byte
95 .get(char_range.start)
96 .copied()
97 .unwrap_or(source_len);
98 let end_byte = char_to_byte
99 .get(char_range.end)
100 .copied()
101 .unwrap_or(source_len);
102 let is_eof = matches!(token, Token::Eof);
103 tokens.push(token);
104 spans.push(start_byte..end_byte);
105 if is_eof {
106 break;
107 }
108 }
109 // 防御:确保 EOF 存在(与 new() 一致)
110 if tokens.last().is_none_or(|t| !matches!(t, Token::Eof)) {
111 tokens.push(Token::Eof);
112 spans.push(source_len..source_len);
113 }
114 Self {
115 tokens,
116 index: 0,
117 marked_indexes: Vec::new(),
118 token_spans: spans,
119 source: Some(source.to_string()),
120 depth: Cell::new(0),
121 nesting_error: RefCell::new(None),
122 }
123 }
124
125 /// 记录嵌套深度超限错误(仅首次覆盖,保留最早的超限点)。
126 pub fn record_nesting_error(&self, depth: u32) {
127 if self.nesting_error.borrow().is_none() {
128 self.nesting_error.replace(Some(ParseError::NestingTooDeep {
129 depth,
130 limit: MAX_NESTING_DEPTH,
131 }));
132 }
133 }
134
135 /// 返回解析过程中记录的第一个嵌套深度超限错误。
136 pub fn nesting_error(&self) -> Option<ParseError> {
137 self.nesting_error.borrow().clone()
138 }
139
140 /// 进入一层嵌套(`consume_a_simple_block` / `consume_a_function`
141 /// 入口调用)。
142 ///
143 /// 返回 `Some(depth)` 表示该层已超过 [`MAX_NESTING_DEPTH`]:
144 /// 错误已被记录,调用方应停止下降(不再递归)并返回空结果。
145 /// 返回 `None` 表示正常进入。
146 pub fn enter_nesting(&self) -> Option<u32> {
147 let depth = self.depth.get() + 1;
148 self.depth.set(depth);
149 if depth > MAX_NESTING_DEPTH {
150 self.record_nesting_error(depth);
151 Some(depth)
152 } else {
153 None
154 }
155 }
156
157 /// 退出一层嵌套(与 [`Self::enter_nesting`] 成对调用)。
158 pub fn leave_nesting(&self) {
159 self.depth.set(self.depth.get().saturating_sub(1));
160 }
161
162 /// 返回 `tokens[start_index..end_index]` 对应的原始 source text。
163 ///
164 /// 参数是 **token 索引**(不是 char/byte 索引)。
165 /// 返回 `None` 如果无 source tracking 或 index 越界。
166 pub fn source_slice(&self, start_index: usize, end_index: usize) -> Option<&str> {
167 let source = self.source.as_ref()?;
168 if end_index == 0 || start_index >= end_index {
169 return Some("");
170 }
171 let start = self.token_spans.get(start_index)?.start;
172 let end = self.token_spans.get(end_index - 1)?.end;
173 source.get(start..end)
174 }
175
176 /// §5.3 L1769-1773: The item of `tokens` at `index`. If
177 /// out-of-bounds, return `Token::Eof`.
178 pub fn next_token(&self) -> Token {
179 self.tokens.get(self.index).cloned().unwrap_or(Token::Eof)
180 }
181
182 /// §5.3 L1775-1777: A token stream is empty if the next token is
183 /// `<EOF-token>`.
184 pub fn is_empty(&self) -> bool {
185 matches!(self.next_token(), Token::Eof)
186 }
187
188 /// §5.3 L1779-1782: Let `token` be the next token. Increment
189 /// `index`, then return `token`.
190 pub fn consume_token(&mut self) -> Token {
191 let token = self.next_token();
192 if !matches!(token, Token::Eof) {
193 self.index += 1;
194 }
195 token
196 }
197
198 /// §5.3 L1784-1786: If not empty, increment `index`.
199 pub fn discard_token(&mut self) {
200 if !self.is_empty() {
201 self.index += 1;
202 }
203 }
204
205 /// §5.3 L1788-1789: Append `index` to `marked_indexes`.
206 pub fn mark(&mut self) {
207 self.marked_indexes.push(self.index);
208 }
209
210 /// §5.3 L1791-1793: Pop from `marked_indexes` and set `index` to
211 /// the popped value. No-op if stack is empty (defensive).
212 pub fn restore_mark(&mut self) {
213 if let Some(idx) = self.marked_indexes.pop() {
214 self.index = idx;
215 }
216 }
217
218 /// §5.3 L1795-1797: Pop from `marked_indexes` and discard.
219 pub fn discard_mark(&mut self) {
220 let _ = self.marked_indexes.pop();
221 }
222
223 /// §5.3 L1799-1801: While the next token is a
224 /// `<whitespace-token>`, discard a token.
225 pub fn discard_whitespace(&mut self) {
226 while matches!(self.next_token(), Token::Whitespace) {
227 self.discard_token();
228 }
229 }
230}