Skip to main content

rust_css_parser/parser/
parse.rs

1//! Port of `src/parser/parse.ts`.
2//!
3//! `doParse()` / `doParseSync()`: see `parse_main.rs`. this module holds the statement parsers (`parseNode()`,
4//! `parseAtRule()`), the token parsers (`parseString()`, `parseTokens()`) and their helpers.
5
6use crate::ast::arena::{AstArena, StrOrId, TokenField, TokenValue};
7use crate::ast::types::{EnumAstNodeStatus, EnumToken};
8use crate::options::{ConvertColor, ParserOptions};
9use crate::parser::input::CssInput;
10use crate::parser::source::SourceFile;
11use crate::parser::tokenize::{create_parse_info, TokenValueField, Tokenizer};
12use crate::parser::utils::at_rule::{match_at_rule_syntax, parse_at_rule_font_feature_values};
13use crate::parser::utils::at_rule_container::parse_at_rule_container_query_list;
14use crate::parser::utils::at_rule_generic::match_generic_syntax;
15use crate::parser::utils::at_rule_import::match_at_rule_import_syntax;
16use crate::parser::utils::at_rule_media::parse_mediaquery_list;
17use crate::parser::utils::at_rule_support::parse_at_rule_support_syntax;
18use crate::parser::utils::at_rule_when_else::match_at_rule_when_else_syntax;
19use crate::parser::utils::declaration::parse_declaration;
20use crate::parser::utils::selector::{is_trim_white_space, parse_selector};
21use crate::parser::utils::text::{camelize, dasherize, equals_ignore_case};
22use crate::parser::utils::token::trim_white_space_tokens;
23use crate::printer::render::{render_value, render_value_default};
24use crate::syntax::constants::{is_function_def_type, tokens_func_def_map, PAGE_MARGIN_BOX_TYPE};
25use crate::syntax::syntax::{is_color, parse_color};
26use crate::types::ErrorDescription;
27use crate::validation::config::get_syntax_rule;
28use crate::validation::match_::{create_validation_context, drop_error, match_all_syntaxes, match_selector_syntax, token_location, trim_array};
29use crate::validation::parser::typedef::ValidationSyntaxGroupEnum;
30use std::rc::Rc;
31
32pub use super::parse_main::*;
33
34/// `ParseResultStats`
35#[derive(Clone, Debug, Default, PartialEq)]
36pub struct ParseResultStats {
37    pub src: String,
38    pub bytes_in: u64,
39    pub imported_bytes_in: u64,
40    pub tokenize: String,
41    pub parse: String,
42    pub minify: String,
43    pub module: Option<String>,
44    pub total: String,
45    pub imports: Vec<ParseResultStats>,
46    pub nodes_count: u64,
47    pub tokens_count: u64,
48}
49
50impl ParseResultStats {
51    pub fn new(src: &str) -> Self {
52        Self {
53            src: src.to_string(),
54            tokenize: "0ms".into(),
55            parse: "0ms".into(),
56            minify: "0ms".into(),
57            total: "0ms".into(),
58            ..Default::default()
59        }
60    }
61}
62
63/// render tokens (`renderTokens()`)
64pub fn render_tokens(arena: &AstArena, tokens: &[u32], options: Option<&ParserOptions>) -> String {
65    tokens
66        .iter()
67        .map(|&t| match options {
68            Some(o) => render_value(arena, t, o),
69            None => render_value_default(arena, t),
70        })
71        .collect()
72}
73
74/// allocate an at-rule node from an at-rule token
75#[allow(clippy::too_many_arguments)]
76pub fn create_at_rule_node(
77    arena: &AstArena,
78    at_rule: u32,
79    typ: u8,
80    tokens: &[u32],
81    state: u32,
82    errors: Vec<ErrorDescription>,
83    end: u32,
84    val: &str,
85    block: bool,
86) -> u32 {
87    let node = arena.create_at_rule(typ, StrOrId::Id(arena.name.get(at_rule)), StrOrId::Str(val), block, Some(tokens), state, Some(errors));
88    arena.span_location(node, at_rule, end);
89    node
90}
91
92/// allocate a comment node from a comment token
93pub fn create_comment_node(arena: &AstArena, token: u32) -> u32 {
94    let node = arena.create_comment(arena.data_types.get(token), StrOrId::Id(arena.string_value.get(token)));
95    arena.copy_location(node, token);
96    node
97}
98
99/// initial arena capacity: one node for every 4 bytes of css
100pub fn arena_capacity(tokenizer: &Tokenizer) -> usize {
101    let length = tokenizer.stream_length();
102    if length == 0 {
103        4096
104    } else {
105        (1usize << 25).min(length.div_ceil(4) + 1024)
106    }
107}
108
109/// allocate the current tokenizer token in the arena
110pub fn allocate_token(arena: &AstArena, tokenizer: &mut Tokenizer, source_index: i32) -> u32 {
111    let item = arena.allocate();
112    let typ = tokenizer.typ.unwrap_or(0);
113    arena.data_types.set(item, typ);
114    match tokenizer.field {
115        TokenValueField::Unit => {
116            arena.numeric_value.set(item, tokenizer.num);
117            let id = tokenizer.intern_value(arena, source_index);
118            arena.unit.set(item, id);
119        }
120        TokenValueField::Name => {
121            let id = tokenizer.intern_value(arena, source_index);
122            arena.name.set(item, id);
123        }
124        TokenValueField::Number => arena.numeric_value.set(item, tokenizer.num),
125        TokenValueField::Value => {
126            if typ != EnumToken::WhitespaceTokenType {
127                let id = tokenizer.intern_value(arena, source_index);
128                arena.string_value.set(item, id);
129            }
130            if let Some(kin) = tokenizer.kin {
131                arena.color_type.set(item, kin);
132            }
133        }
134        TokenValueField::None => {}
135    }
136    if source_index >= 0 {
137        arena.set_token_location(item, source_index as u32, tokenizer.sta.unwrap_or(0) as u32, tokenizer.end.unwrap_or(0) as u32);
138    }
139    item
140}
141
142/// recycle the tokens of a statement that were not attached to the tree
143pub fn recycle_statement_tokens(
144    arena: &AstArena,
145    tokens: &[u32],
146    errors: &[ErrorDescription],
147    error_start: usize,
148    invalid_nodes: &[u32],
149    invalid_start: usize,
150) {
151    for &token in tokens {
152        if arena.data_types.get(token) == 0 || arena.parents.get(token) != 0 || arena.first_child.get(token) != 0 || arena.first_token.get(token) != 0 {
153            continue;
154        }
155        let mut referenced = invalid_nodes.get(invalid_start..).is_some_and(|v| v.contains(&token));
156        if !referenced {
157            referenced = errors.get(error_start..).is_some_and(|e| e.iter().any(|e| e.node == Some(token)));
158        }
159        if !referenced {
160            arena.recycle(token);
161        }
162    }
163}
164
165/// bad comment, cdo, url or string token
166pub fn is_bad_token(t: u8) -> bool {
167    matches!(t, EnumToken::BadCommentTokenType | EnumToken::BadCdoTokenType | EnumToken::BadUrlTokenType | EnumToken::BadStringTokenType)
168}
169
170/// transform the case of a key name (`getKeyName()`)
171pub fn get_key_name(key: &str, how: u32) -> String {
172    use crate::ast::types::ModuleCaseTransformEnum as M;
173    // the case transforms are flags
174    if how & (M::CamelCase | M::CamelCaseOnly) != 0 {
175        camelize(key)
176    } else if how & (M::DashCase | M::DashCaseOnly) != 0 {
177        dasherize(key)
178    } else {
179        key.to_string()
180    }
181}
182
183const INVALID_STATES: u32 = EnumAstNodeStatus::Invalid
184    | EnumAstNodeStatus::Disallowed
185    | EnumAstNodeStatus::Unknown
186    | EnumAstNodeStatus::Unparsed
187    | EnumAstNodeStatus::Malformed;
188
189/// parse a statement: an at-rule, a rule or a declaration
190#[allow(clippy::too_many_arguments)]
191pub fn parse_node(
192    arena: &AstArena,
193    tokens: &mut Vec<u32>,
194    context: u32,
195    options: &ParserOptions,
196    errors: &mut Vec<ErrorDescription>,
197    stats: &mut ParseResultStats,
198    invalid_nodes: &mut Vec<u32>,
199    parens_match: i32,
200) -> Option<u32> {
201    let t = |x: u32| arena.data_types.get(x);
202    let context_type = t(context);
203    if tokens.last().is_some_and(|&l| t(l) == EnumToken::EOFTokenType) {
204        tokens.pop();
205        let mut match_count = parens_match;
206        if match_count > 0 {
207            let mut k = tokens.len() as isize;
208            loop {
209                let cont = k > 0;
210                k -= 1;
211                if !(cont && matches!(t(tokens[k as usize]), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType)) {
212                    break;
213                }
214            }
215            if k >= 0 && t(tokens[k as usize]) == EnumToken::SemiColonTokenType {
216                match_count = 0;
217            }
218            while match_count > 0 {
219                let closing = arena.create_token(EnumToken::EndParensTokenType, TokenValue::None, None);
220                if k >= 0 {
221                    arena.copy_location(closing, tokens[k as usize]);
222                }
223                tokens.push(closing);
224                match_count -= 1;
225            }
226        }
227    }
228    let cdo_error = |errors: &mut Vec<ErrorDescription>, token: u32| {
229        errors.push(drop_error(arena, format!("CDOCOMM not allowed here {}", token), token, options));
230        arena.data_types.set(token, EnumToken::BadCdoTokenType);
231    };
232    let mut i = 0usize;
233    while i < tokens.len() {
234        let tk = tokens[i];
235        if t(tk) == EnumToken::CDOCOMMTokenType && context_type != EnumToken::StyleSheetNodeType {
236            cdo_error(errors, tk);
237            i += 1;
238            continue;
239        }
240        if matches!(t(tk), EnumToken::CommentTokenType | EnumToken::CDOCOMMTokenType | EnumToken::WhitespaceTokenType) {
241            i += 1;
242            continue;
243        }
244        break;
245    }
246    if i > 0 {
247        for k in 0..i {
248            if t(tokens[k]) != EnumToken::WhitespaceTokenType {
249                let comment = create_comment_node(arena, tokens[k]);
250                arena.append_child_list(context, &[comment]);
251            }
252        }
253        tokens.drain(..i);
254    }
255    let mut i = 0usize;
256    while i < tokens.len() {
257        let tk = tokens[i];
258        if matches!(t(tk), EnumToken::CommentTokenType | EnumToken::CDOCOMMTokenType) {
259            if t(tk) == EnumToken::CDOCOMMTokenType && context_type != EnumToken::StyleSheetNodeType {
260                cdo_error(errors, tk);
261                i += 1;
262                continue;
263            }
264            let comment = create_comment_node(arena, tk);
265            arena.append_child_list(context, &[comment]);
266            stats.nodes_count += 1;
267        } else if t(tk) != EnumToken::WhitespaceTokenType {
268            break;
269        }
270        i += 1;
271    }
272    let delim = *tokens.last()?;
273    if matches!(t(delim), EnumToken::SemiColonTokenType | EnumToken::BlockStartTokenType | EnumToken::BlockEndTokenType) {
274        tokens.pop();
275    }
276    if tokens.is_empty() {
277        return None;
278    }
279    if t(tokens[0]) == EnumToken::AtRuleTokenType {
280        let mut nested_rule = false;
281        let mut parent = context;
282        while parent != 0 {
283            if t(parent) == EnumToken::RuleNodeType {
284                nested_rule = true;
285                break;
286            }
287            parent = arena.parents.get(parent);
288        }
289        let at_options = ParserOptions { nested_rule: Some(nested_rule), ..options.clone() };
290        let node = parse_at_rule(arena, tokens, context, &at_options, errors, Some(t(delim) == EnumToken::BlockStartTokenType))?;
291        if arena.flags.get(node) & INVALID_STATES != 0 {
292            invalid_nodes.push(node);
293        }
294        stats.nodes_count += 1;
295        arena.append_child_list(context, &[node]);
296        return Some(node);
297    }
298    stats.nodes_count += 1;
299    if t(delim) == EnumToken::BlockStartTokenType {
300        let node = parse_selector(arena, tokens, Some(context), options, errors);
301        arena.append_child_list(context, &[node]);
302        if arena.flags.get(node) & INVALID_STATES != 0 {
303            invalid_nodes.push(node);
304        }
305        return Some(node);
306    }
307    let node = parse_declaration(arena, tokens, Some(context), options, errors);
308    if context_type == EnumToken::StyleSheetNodeType && t(node) == EnumToken::DeclarationNodeType {
309        arena.flags.set(node, arena.flags.get(node) | EnumAstNodeStatus::Invalid);
310        let mut error = ErrorDescription::drop("<declaration> not allowed in <stylesheet>").with_node(node);
311        error.location = token_location(arena, node, options);
312        errors.push(error);
313    } else if options.lenient == Some(true) || t(node) == EnumToken::DeclarationNodeType {
314        arena.append_child_list(context, &[node]);
315    }
316    if arena.flags.get(node) & INVALID_STATES != 0 {
317        invalid_nodes.push(node);
318    }
319    None
320}
321
322/// detach the invalid nodes. the unknown nodes are kept in lenient mode
323pub fn drop_invalid_nodes(arena: &AstArena, invalid_nodes: &[u32], options: &ParserOptions) {
324    for &node in invalid_nodes {
325        if options.lenient == Some(true) && arena.flags.get(node) & EnumAstNodeStatus::Unknown != 0 {
326            continue;
327        }
328        if arena.flags.get(node) & INVALID_STATES != 0 {
329            arena.detach(node);
330        }
331    }
332}
333
334/// true if the node is an at-rule whose block is kept when it is empty: `@apply`, `@mixin`, `@function`
335pub fn is_definition_block(arena: &AstArena, node: u32) -> bool {
336    arena.data_types.get(node) == EnumToken::AtRuleNodeType
337        && (arena.string_equals(arena.name.get(node), "apply")
338            || arena.string_equals(arena.name.get(node), "mixin")
339            || arena.string_equals(arena.name.get(node), "function"))
340}
341
342/// true if a mixin can be defined in the node
343fn is_mixin_scope(arena: &AstArena, mut node: u32) -> bool {
344    while node != 0 && arena.data_types.get(node) != EnumToken::StyleSheetNodeType {
345        if arena.data_types.get(node) != EnumToken::AtRuleNodeType
346            || !arena.with_string(arena.name.get(node), |n| matches!(n, "media" | "supports" | "container" | "layer" | "when" | "else"))
347        {
348            return false;
349        }
350        node = arena.parents.get(node);
351    }
352    true
353}
354
355/// `/^-[a-z]+-/` removed, lowercase
356fn unprefixed_at_rule_name(nam: &str) -> String {
357    if let Some(rest) = nam.strip_prefix('-') {
358        let letters = rest.bytes().take_while(|b| b.is_ascii_lowercase()).count();
359        if letters > 0 && rest.as_bytes().get(letters) == Some(&b'-') {
360            return rest[letters + 1..].to_lowercase();
361        }
362    }
363    nam.to_lowercase()
364}
365
366fn last_or(stream: &[u32], default: u32) -> u32 {
367    stream.last().copied().unwrap_or(default)
368}
369
370/// render the tokens of `@namespace` / `@import`: the comments and the whitespace before a comment are dropped
371fn render_skip_comments(arena: &AstArena, stream: &[u32], options: &ParserOptions) -> String {
372    let t = |x: u32| arena.data_types.get(x);
373    let mut acc = String::new();
374    for (index, &tk) in stream.iter().enumerate() {
375        let skip = t(tk) == EnumToken::CommentTokenType
376            || (t(tk) == EnumToken::WhitespaceTokenType
377                && stream.get(index + 1).is_some_and(|&n| t(n) == EnumToken::CommentTokenType)
378                && (stream.len() < index + 3 || stream.get(index + 2).is_some_and(|&n| t(n) == EnumToken::WhitespaceTokenType)));
379        if !skip {
380            acc.push_str(&render_value(arena, tk, options));
381        }
382    }
383    acc
384}
385
386/// parse an at-rule
387pub fn parse_at_rule(
388    arena: &AstArena,
389    stream: &mut Vec<u32>,
390    context: u32,
391    options: &ParserOptions,
392    errors: &mut Vec<ErrorDescription>,
393    parse_as_block: Option<bool>,
394) -> Option<u32> {
395    let t = |x: u32| arena.data_types.get(x);
396    let mut success = true;
397    let context_type = t(context);
398    let context_name: Option<String> = (context_type == EnumToken::AtRuleNodeType).then(|| arena.get_name(context).to_string());
399    let at_rule = stream.remove(0);
400    let nam = arena.get_name(at_rule).to_string();
401    let at_rule_name = if nam.starts_with('-') { unprefixed_at_rule_name(&nam) } else { nam.clone() };
402    let mut at_rule_end = at_rule;
403    let last_error = |errors: &Vec<ErrorDescription>| errors.last().cloned().into_iter().collect::<Vec<_>>();
404    let syntax_rules = get_syntax_rule(ValidationSyntaxGroupEnum::AtRules, &format!("@{}", nam));
405    let syntax: Option<Vec<_>> = syntax_rules.as_ref().and_then(|r| r.get_prelude_rules()).map(|p| p.iter().skip(1).cloned().collect());
406    let block_allowed = syntax_rules.as_ref().is_some_and(|r| r.get_block_rules().is_some());
407    let as_block = |p: Option<bool>| p.unwrap_or(false);
408    let Some(syntax_rules) = syntax_rules else {
409        errors.push(drop_error(arena, "unknown at-rule".into(), at_rule, options));
410        let (ok, result_errors) = match_generic_syntax(arena, stream, options);
411        parse_tokens(arena, stream, None, None);
412        let state = if ok { EnumAstNodeStatus::Unknown } else { EnumAstNodeStatus::Invalid };
413        let mut node_errors = last_error(errors);
414        if !ok {
415            node_errors.extend(result_errors);
416        }
417        trim_array(arena, stream);
418        let val = render_tokens(arena, stream, Some(options));
419        return Some(create_at_rule_node(arena, at_rule, EnumToken::AtRuleNodeType, stream, state, node_errors, at_rule_end, &val, as_block(parse_as_block)));
420    };
421    if context_name.as_deref() == Some("page") && PAGE_MARGIN_BOX_TYPE.contains(&at_rule_name.to_lowercase().as_str()) {
422        let invalid = |stream: &mut Vec<u32>, errors: &mut Vec<ErrorDescription>| {
423            parse_tokens(arena, stream, None, None);
424            let node_errors = last_error(errors);
425            trim_array(arena, stream);
426            let val = render_tokens(arena, stream, Some(options));
427            Some(create_at_rule_node(arena, at_rule, EnumToken::AtRuleNodeType, stream, EnumAstNodeStatus::Invalid, node_errors, at_rule, &val, as_block(parse_as_block)))
428        };
429        if parse_as_block == Some(false) && !syntax_rules.optional_body {
430            errors.push(drop_error(arena, "at-rule block is required".into(), at_rule, options));
431            return invalid(stream, errors);
432        }
433        if let Some(token) = stream.iter().copied().find(|&x| t(x) != EnumToken::WhitespaceTokenType && t(x) == EnumToken::CommentTokenType) {
434            errors.push(drop_error(arena, "unexpected token".into(), token, options));
435            return invalid(stream, errors);
436        }
437    }
438    let parse_as_block = parse_as_block.unwrap_or(block_allowed);
439    if syntax.is_some() && nam != "layer" && parse_as_block != block_allowed && !syntax_rules.optional_body {
440        errors.push(drop_error(arena, if parse_as_block { "at-rule block not supported" } else { "at-rule block is required" }.into(), at_rule, options));
441        parse_tokens(arena, stream, None, None);
442        let node_errors = last_error(errors);
443        trim_array(arena, stream);
444        let val = render_tokens(arena, stream, Some(options));
445        return Some(create_at_rule_node(arena, at_rule, EnumToken::AtRuleNodeType, stream, EnumAstNodeStatus::Invalid, node_errors, at_rule_end, &val, parse_as_block));
446    }
447    let no_color = |o: &ParserOptions| ParserOptions { convert_color: Some(ConvertColor::Bool(false)), ..o.clone() };
448    match at_rule_name.as_str() {
449        "charset" => {
450            let mut ok = true;
451            let first = stream.first().copied();
452            let is_single_space = first.is_some_and(|f| {
453                t(f) == EnumToken::WhitespaceTokenType
454                    && arena.get_span_end(f) - arena.get_span_start(f) == 1
455                    && arena.source_text(arena.get_source_id(f) as usize).is_some_and(|c| c.at(arena.get_span_start(f) as usize) == 0x20)
456            });
457            if !is_single_space {
458                ok = false;
459                errors.push(drop_error(arena, "expecting <space>".into(), first.unwrap_or(at_rule), options));
460            } else if stream.get(1).is_none_or(|&s| t(s) != EnumToken::StringTokenType) {
461                ok = false;
462                errors.push(drop_error(arena, "expecting <string>".into(), stream.get(1).copied().unwrap_or(at_rule), options));
463            }
464            if ok && !arena.string_starts_with(arena.string_value.get(stream[1]), "\"") {
465                ok = false;
466                errors.push(drop_error(arena, "expecting double-quoted string".into(), stream[1], options));
467            }
468            if !ok {
469                let node_errors = last_error(errors);
470                at_rule_end = last_or(stream, at_rule);
471                trim_array(arena, stream);
472                let val = render_tokens(arena, stream, Some(options));
473                return Some(create_at_rule_node(arena, at_rule, EnumToken::AtRuleNodeType, stream, EnumAstNodeStatus::Invalid, node_errors, at_rule_end, &val, false));
474            }
475            if options.remove_charset == Some(true) {
476                return None;
477            }
478            at_rule_end = last_or(stream, at_rule);
479            trim_array(arena, stream);
480            let val = render_tokens(arena, stream, Some(options));
481            Some(create_at_rule_node(arena, at_rule, EnumToken::AtRuleNodeType, stream, EnumAstNodeStatus::Validated, Vec::new(), at_rule_end, &val, false))
482        }
483        "font-feature-values" => {
484            let (ok, result_errors) = parse_at_rule_font_feature_values(arena, stream, at_rule, options);
485            errors.extend(result_errors.iter().cloned());
486            at_rule_end = last_or(stream, at_rule);
487            trim_white_space_tokens(arena, stream);
488            let val = render_tokens(arena, stream, Some(options));
489            let state = if ok { EnumAstNodeStatus::Validated } else { EnumAstNodeStatus::Invalid };
490            Some(create_at_rule_node(arena, at_rule, EnumToken::AtRuleNodeType, stream, state, if ok { Vec::new() } else { result_errors }, at_rule_end, &val, true))
491        }
492        "stylistic" | "historical-forms" | "character-variant" | "swash" | "ornaments" | "annotation" => {
493            let mut ok = context_name.as_deref() == Some("font-feature-values");
494            if !ok {
495                errors.push(drop_error(arena, format!("unexpected at-rule {}", nam), at_rule, options));
496            }
497            if ok {
498                for &token in stream.iter() {
499                    if !matches!(t(token), EnumToken::CommentTokenType | EnumToken::WhitespaceTokenType) {
500                        ok = false;
501                        errors.push(drop_error(arena, "unexpected token".into(), token, options));
502                    }
503                }
504            }
505            at_rule_end = last_or(stream, at_rule);
506            let node_errors = last_error(errors);
507            trim_white_space_tokens(arena, stream);
508            let val = render_tokens(arena, stream, Some(options));
509            let state = if ok { EnumAstNodeStatus::Validated } else { EnumAstNodeStatus::Invalid };
510            Some(create_at_rule_node(arena, at_rule, EnumToken::AtRuleNodeType, stream, state, node_errors, at_rule_end, &val, true))
511        }
512        "container" => {
513            let (ok, result_errors) = parse_at_rule_container_query_list(arena, stream, at_rule, options);
514            errors.extend(result_errors.iter().cloned());
515            at_rule_end = last_or(stream, at_rule);
516            trim_white_space_tokens(arena, stream);
517            let val = render_tokens(arena, stream, Some(options));
518            let state = if ok { EnumAstNodeStatus::Validated } else { EnumAstNodeStatus::Invalid };
519            Some(create_at_rule_node(arena, at_rule, EnumToken::AtRuleNodeType, stream, state, if ok { Vec::new() } else { result_errors }, at_rule_end, &val, true))
520        }
521        "custom-media" => {
522            let mut tokens: Vec<u32> = stream.iter().skip(1).copied().collect();
523            trim_array(arena, &mut tokens);
524            let result = match_all_syntaxes(arena, syntax.as_deref(), &create_validation_context(arena, &tokens), options);
525            errors.extend(result.errors.iter().cloned());
526            let options = no_color(options);
527            at_rule_end = last_or(&tokens, at_rule);
528            let state = if success { EnumAstNodeStatus::Validated } else { EnumAstNodeStatus::ValidationFailed };
529            let node_errors = if result.success { Vec::new() } else { result.errors };
530            trim_white_space_tokens(arena, &mut tokens);
531            let val = render_tokens(arena, &tokens, Some(&options));
532            Some(create_at_rule_node(arena, at_rule, EnumToken::AtRuleNodeType, &tokens, state, node_errors, at_rule_end, &val, false))
533        }
534        "keyframes" => {
535            let mut tokens: Vec<u32> = stream.iter().skip(1).copied().collect();
536            trim_array(arena, &mut tokens);
537            let filtered: Vec<u32> = stream.iter().copied().filter(|&x| !matches!(t(x), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType)).collect();
538            if filtered.len() != 1 || !matches!(t(filtered[0]), EnumToken::IdenTokenType | EnumToken::StringTokenType | EnumToken::DashedIdenTokenType) {
539                errors.push(drop_error(arena, "expected <keyframe-name>".into(), at_rule, options));
540                success = false;
541            }
542            let options = no_color(options);
543            at_rule_end = last_or(&tokens, at_rule);
544            let state = if success { EnumAstNodeStatus::Validated } else { EnumAstNodeStatus::Invalid };
545            let node_errors = if success { Vec::new() } else { last_error(errors) };
546            let val = render_tokens(arena, &tokens, Some(&options));
547            Some(create_at_rule_node(arena, at_rule, EnumToken::KeyframesAtRuleNodeType, &tokens, state, node_errors, at_rule_end, &val, true))
548        }
549        "namespace" => {
550            let result = match_all_syntaxes(arena, syntax.as_deref(), &create_validation_context(arena, stream), options);
551            if !result.success {
552                errors.extend(result.errors.iter().cloned());
553            }
554            let valid = block_allowed == parse_as_block && result.success;
555            if valid {
556                let mut start = 0usize;
557                let mut end: isize = -1;
558                let mut has_string = false;
559                while start < stream.len() {
560                    if t(stream[start]) == EnumToken::UrlFunctionTokenDefType {
561                        start += 1;
562                        end = start as isize;
563                        while (end as usize) < stream.len() {
564                            if t(stream[end as usize]) == EnumToken::EndParensTokenType {
565                                break;
566                            }
567                            if t(stream[end as usize]) == EnumToken::StringTokenType {
568                                has_string = true;
569                            }
570                            end += 1;
571                        }
572                        break;
573                    }
574                    start += 1;
575                }
576                if has_string {
577                    let inner: Vec<u32> = stream[start..(end as usize).min(stream.len())].to_vec();
578                    let remove_end = ((end + 1) as usize).min(stream.len());
579                    stream.splice(start - 1..remove_end, inner);
580                }
581            }
582            at_rule_end = last_or(stream, at_rule);
583            let at_rule_tokens = stream.clone();
584            trim_array(arena, stream);
585            let val = render_skip_comments(arena, stream, options);
586            let state = if valid { EnumAstNodeStatus::Validated } else { EnumAstNodeStatus::Invalid };
587            Some(create_at_rule_node(arena, at_rule, EnumToken::AtRuleNodeType, &at_rule_tokens, state, if valid { Vec::new() } else { result.errors }, at_rule_end, &val, parse_as_block))
588        }
589        "import" => {
590            let (ok, result_errors) = match_at_rule_import_syntax(arena, at_rule, stream, options);
591            if !result_errors.is_empty() {
592                errors.extend(result_errors.iter().cloned());
593            } else if stream.first().is_some_and(|&f| {
594                t(f) == EnumToken::UrlFunctionTokenType
595                    && arena.token_iter(f).any(|x| matches!(t(x), EnumToken::StringTokenType | EnumToken::UrlTokenTokenType))
596            }) {
597                let inner = arena.tokens(stream[0]);
598                stream.splice(0..1, inner);
599            }
600            at_rule_end = last_or(stream, at_rule);
601            let state = if ok { EnumAstNodeStatus::Validated } else { EnumAstNodeStatus::Invalid };
602            let val = render_skip_comments(arena, stream, options);
603            Some(create_at_rule_node(arena, at_rule, EnumToken::AtRuleNodeType, stream, state, if ok { Vec::new() } else { result_errors }, at_rule_end, &val, false))
604        }
605        "supports" | "when" | "else" => {
606            trim_white_space_tokens(arena, stream);
607            let (result_success, result_errors) = if at_rule_name == "supports" {
608                parse_at_rule_support_syntax(arena, stream, at_rule, options)
609            } else {
610                match_at_rule_when_else_syntax(arena, stream, at_rule, options)
611            };
612            errors.extend(result_errors.iter().cloned());
613            let mut ok = result_success;
614            if nam == "else" {
615                let mut sibling = arena.last_child.get(context);
616                while sibling != 0 && matches!(t(sibling), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType | EnumToken::CDOCOMMTokenType) {
617                    sibling = arena.previous_sibling.get(sibling);
618                }
619                let mut missing_when = false;
620                let mut defined_after_last_else = false;
621                if sibling == 0 || t(sibling) != EnumToken::AtRuleNodeType {
622                    missing_when = true;
623                } else if !arena.string_equals(arena.name.get(sibling), "when") {
624                    if !arena.string_equals(arena.name.get(sibling), "else") {
625                        missing_when = true;
626                    } else if arena.string_value.get(sibling) == 0 {
627                        defined_after_last_else = true;
628                    }
629                }
630                if missing_when {
631                    ok = false;
632                    errors.push(drop_error(arena, "at-rule @when is required before @else block".into(), at_rule, options));
633                } else if defined_after_last_else {
634                    ok = false;
635                    errors.push(drop_error(arena, "at-rule @else block is defined after last @else block".into(), at_rule, options));
636                }
637            }
638            let options = ParserOptions { minify: Some(false), convert_color: Some(ConvertColor::Bool(false)), ..options.clone() };
639            at_rule_end = last_or(stream, at_rule);
640            let state = if ok { EnumAstNodeStatus::Validated } else { EnumAstNodeStatus::Invalid };
641            let node_errors = if result_success {
642                Vec::new()
643            } else {
644                let mut e = last_error(errors);
645                e.extend(result_errors);
646                e
647            };
648            let val = render_tokens(arena, stream, Some(&options));
649            Some(create_at_rule_node(arena, at_rule, EnumToken::AtRuleNodeType, stream, state, node_errors, at_rule_end, &val, true))
650        }
651        "media" => {
652            let options = ParserOptions { parse_color: Some(false), ..options.clone() };
653            let (ok, result_errors) = parse_mediaquery_list(arena, stream, &options);
654            errors.extend(result_errors.iter().cloned());
655            at_rule_end = last_or(stream, at_rule);
656            let state = if ok { EnumAstNodeStatus::Validated } else { EnumAstNodeStatus::Invalid };
657            let val = render_tokens(arena, stream, Some(&options));
658            Some(create_at_rule_node(arena, at_rule, EnumToken::AtRuleNodeType, stream, state, if ok { Vec::new() } else { result_errors }, at_rule_end, &val, true))
659        }
660        "scope" => {
661            trim_array(arena, stream);
662            let context_v = create_validation_context(arena, stream);
663            // typescript passes a function as the closing token type: it never matches
664            let mut range = context_v.borrow().peek_range(arena, 0, 0);
665            let mut ok = true;
666            if range.first().is_none_or(|&r| t(r) != EnumToken::StartParensTokenType) {
667                errors.push(drop_error(arena, "expected '(' at start of @scope block".into(), range.first().copied().unwrap_or(at_rule), options));
668                ok = false;
669            } else if range.last().is_none_or(|&r| t(r) != EnumToken::EndParensTokenType) {
670                errors.push(drop_error(arena, "expected ')' at end of @scope block".into(), range.last().copied().unwrap_or(at_rule), options));
671                ok = false;
672            } else {
673                let mut srange: Vec<u32> = range[1..range.len() - 1].to_vec();
674                let (selector_ok, _) = match_selector_syntax(arena, &mut srange, errors, options, true);
675                if !selector_ok {
676                    ok = false;
677                } else {
678                    let start = stream.iter().position(|&x| x == range[0]).map_or(0, |p| p + 1);
679                    trim_white_space_tokens(arena, &mut srange);
680                    let end = (start + range.len() - 2).min(stream.len());
681                    stream.splice(start..end, srange);
682                }
683            }
684            let mut index = stream.iter().position(|&x| Some(x) == range.last().copied()).map_or(-1, |p| p as isize);
685            if stream.len() as isize > index + 1 {
686                let skip_ws = |index: &mut isize, stream: &Vec<u32>| loop {
687                    *index += 1;
688                    if !stream.get(*index as usize).is_some_and(|&x| matches!(t(x), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType)) {
689                        break;
690                    }
691                };
692                skip_ws(&mut index, stream);
693                if (index as usize) < stream.len() {
694                    let tk = stream[index as usize];
695                    if t(tk) != EnumToken::IdenTokenType || !arena.with_string(arena.string_value.get(tk), |v| v.eq_ignore_ascii_case("to")) {
696                        errors.push(drop_error(arena, "expected 'to' at end of @scope block".into(), tk, options));
697                        ok = false;
698                    } else {
699                        skip_ws(&mut index, stream);
700                        let tk = stream.get(index as usize).copied();
701                        if tk.is_none_or(|x| t(x) != EnumToken::StartParensTokenType) {
702                            errors.push(drop_error(arena, "expected 'to' at end of @scope block".into(), tk.unwrap_or(0), options));
703                            ok = false;
704                        } else {
705                            let context_v = create_validation_context(arena, &stream[index as usize..]);
706                            range = context_v.borrow().peek_range(arena, 0, 0);
707                            if range.last().is_none_or(|&r| t(r) != EnumToken::EndParensTokenType) {
708                                errors.push(drop_error(arena, "expected ')' at end of @scope block".into(), range.last().copied().unwrap_or(at_rule), options));
709                                ok = false;
710                            } else {
711                                let mut srange: Vec<u32> = range[1..range.len() - 1].to_vec();
712                                let (selector_ok, _) = match_selector_syntax(arena, &mut srange, errors, options, true);
713                                if !selector_ok {
714                                    ok = false;
715                                } else {
716                                    let start = stream.iter().position(|&x| x == range[0]).map_or(0, |p| p + 1);
717                                    trim_white_space_tokens(arena, &mut srange);
718                                    let end = (start + range.len() - 2).min(stream.len());
719                                    stream.splice(start..end, srange);
720                                }
721                            }
722                        }
723                    }
724                }
725            }
726            at_rule_end = last_or(stream, at_rule);
727            let state = if ok { EnumAstNodeStatus::Validated } else { EnumAstNodeStatus::Invalid };
728            let node_errors = if ok { Vec::new() } else { last_error(errors) };
729            let val = render_tokens(arena, stream, Some(options));
730            Some(create_at_rule_node(arena, at_rule, EnumToken::AtRuleNodeType, stream, state, node_errors, at_rule_end, &val, true))
731        }
732        "page" => {
733            trim_array(arena, stream);
734            at_rule_end = last_or(stream, at_rule);
735            let state = if success { EnumAstNodeStatus::Validated } else { EnumAstNodeStatus::Invalid };
736            let val = render_tokens(arena, stream, Some(options));
737            Some(create_at_rule_node(arena, at_rule, EnumToken::AtRuleNodeType, stream, state, Vec::new(), at_rule_end, &val, true))
738        }
739        "top-left-corner" | "top-left" | "top-center" | "top-right" | "top-right-corner" | "bottom-left-corner" | "bottom-left"
740        | "bottom-right" | "bottom-right-corner" | "left-top" | "left-middle" | "left-bottom" | "right-top" | "right-middle"
741        | "right-bottom" => {
742            if context_name.as_deref() != Some("page") {
743                success = false;
744                errors.push(drop_error(arena, "node is allowed only in @page rule".into(), at_rule, options));
745            } else {
746                trim_array(arena, stream);
747                if let Some(&tk) = stream.iter().find(|&&x| !matches!(t(x), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType)) {
748                    success = false;
749                    errors.push(drop_error(arena, "expected whitespace or comment".into(), tk, options));
750                }
751            }
752            at_rule_end = last_or(stream, at_rule);
753            let state = if success { EnumAstNodeStatus::Validated } else { EnumAstNodeStatus::Invalid };
754            let node_errors = if success { Vec::new() } else { last_error(errors) };
755            let val = render_tokens(arena, stream, Some(options));
756            Some(create_at_rule_node(arena, at_rule, EnumToken::AtRuleNodeType, stream, state, node_errors, at_rule_end, &val, true))
757        }
758        "value" => {
759            let mut index = 0usize;
760            let mut is_var_declaration = false;
761            while index < stream.len() {
762                let tk = stream[index];
763                if t(tk) == EnumToken::PseudoClassTokenType {
764                    let colon = arena.create_token(EnumToken::ColonTokenType, TokenValue::None, None);
765                    arena.copy_location(colon, tk);
766                    let value = arena.resolve_string(arena.string_value.get(tk));
767                    let rest: String = value.chars().skip(1).collect();
768                    arena.string_value.set(tk, arena.intern_string(&rest));
769                    arena.data_types.set(tk, EnumToken::IdenTokenType);
770                    stream.insert(index, colon);
771                    is_var_declaration = true;
772                    break;
773                } else if t(tk) == EnumToken::ColonTokenType {
774                    is_var_declaration = true;
775                    break;
776                } else if t(tk) == EnumToken::IdenTokenType && arena.string_equals_ignore_case(arena.string_value.get(tk), "from") {
777                    break;
778                }
779                index += 1;
780            }
781            let result = match_all_syntaxes(arena, syntax.as_deref(), &create_validation_context(arena, stream), options);
782            at_rule_end = last_or(stream, at_rule);
783            if !result.success {
784                errors.extend(result.errors.iter().cloned());
785                let val = render_tokens(arena, stream, Some(options));
786                return Some(create_at_rule_node(arena, at_rule, EnumToken::AtRuleNodeType, stream, EnumAstNodeStatus::Invalid, result.errors, at_rule_end, &val, false));
787            }
788            if is_var_declaration {
789                let nam_token = stream.iter().copied().find(|&x| t(x) == EnumToken::IdenTokenType).unwrap_or(0);
790                let mut value: Vec<u32> = stream.iter().skip(index + 1).copied().filter(|&x| t(x) != EnumToken::CommentTokenType).collect();
791                trim_array(arena, &mut value);
792                let typ = if value.len() == 1 && t(value[0]) == EnumToken::StringTokenType {
793                    EnumToken::CssVariableImportTokenType
794                } else {
795                    EnumToken::CssVariableTokenType
796                };
797                let node = arena.create_declaration(typ, StrOrId::Id(arena.string_value.get(nam_token)), Some(&value), EnumAstNodeStatus::Validated, Some(Vec::new()));
798                arena.span_location(node, at_rule, at_rule_end);
799                return Some(node);
800            }
801            let mut names: Vec<u32> = stream[..index.min(stream.len())].to_vec();
802            trim_array(arena, &mut names);
803            let node = arena.create_declaration(EnumToken::CssVariableDeclarationMapTokenType, StrOrId::Str(&nam), Some(&names), EnumAstNodeStatus::Validated, Some(Vec::new()));
804            let alias: Vec<u32> = stream.iter().skip(index + 1).copied().collect();
805            arena.set_token_list(arena.field_list(node, TokenField::L), &alias);
806            arena.span_location(node, at_rule, at_rule_end);
807            Some(node)
808        }
809        _ => {
810            let options = ParserOptions { parse_color: Some(false), ..options.clone() };
811            let (result_success, mut result_errors) = if syntax.is_none() {
812                let r = match_generic_syntax(arena, stream, &options);
813                errors.extend(r.1.iter().cloned());
814                r
815            } else {
816                let r = match_at_rule_syntax(arena, at_rule, stream, &options);
817                errors.extend(r.1.iter().cloned());
818                if r.0 {
819                    let mut stack: Vec<u32> = Vec::new();
820                    let mut i = 0usize;
821                    while i < stream.len() {
822                        let tk = stream[i];
823                        if t(tk) == EnumToken::StartParensTokenType || is_function_def_type(t(tk)) {
824                            stack.push(tk);
825                            i += 1;
826                            continue;
827                        }
828                        if t(tk) == EnumToken::EndParensTokenType && !stack.is_empty() {
829                            let index = stream.iter().position(|&x| x == *stack.last().unwrap()).unwrap();
830                            let func = stream[index];
831                            arena.set_span(func, arena.get_source_id(func), arena.get_span_start(func), arena.get_span_end(tk));
832                            arena.data_types.set(func, tokens_func_def_map(t(func)).unwrap_or(0));
833                            let mut inner: Vec<u32> = stream.drain(index + 1..i).collect();
834                            trim_white_space_tokens(arena, &mut inner);
835                            arena.set_token_list(func, &inner);
836                            i = index;
837                            if index + 1 < stream.len() {
838                                stream.remove(index + 1);
839                            }
840                            stack.pop();
841                        }
842                        i += 1;
843                    }
844                }
845                r
846            };
847            at_rule_end = last_or(stream, at_rule);
848            let at_rule_tokens = stream.clone();
849            let mut state = if result_success { EnumAstNodeStatus::Validated } else { EnumAstNodeStatus::Invalid };
850            let location = || token_location(arena, at_rule, &options);
851            match nam.as_str() {
852                "mixin" => {
853                    if !is_mixin_scope(arena, context) {
854                        state |= EnumAstNodeStatus::Disallowed;
855                        let mut e = ErrorDescription::drop("mixin rule cannot be a nested group rule or rule style body");
856                        e.location = location();
857                        result_errors.push(e);
858                    }
859                }
860                "contents" | "result" => {
861                    let mut parent = context;
862                    let mut valid = false;
863                    while parent != 0 {
864                        if t(parent) == EnumToken::AtRuleNodeType && arena.string_equals(arena.name.get(parent), "mixin") {
865                            valid = true;
866                            break;
867                        }
868                        parent = arena.parents.get(parent);
869                    }
870                    if !valid {
871                        state |= EnumAstNodeStatus::Disallowed;
872                        let mut e = ErrorDescription::drop(format!("{} rule cannot be used outside mixin rule", nam));
873                        e.location = location();
874                        result_errors.push(e);
875                    }
876                }
877                "layer" => {
878                    if context_type != EnumToken::StyleSheetNodeType {
879                        let mut parent = context;
880                        while parent != 0 {
881                            if t(parent) == EnumToken::AtRuleNodeType && arena.string_equals(arena.name.get(parent), "mixin") {
882                                state |= EnumAstNodeStatus::Disallowed;
883                                let mut e = ErrorDescription::drop("at-rule layer is not allowed inside mixin rule");
884                                e.location = location();
885                                result_errors.push(e);
886                                break;
887                            }
888                            parent = arena.parents.get(parent);
889                        }
890                    }
891                }
892                _ => {}
893            }
894            trim_white_space_tokens(arena, stream);
895            let val = render_tokens(arena, stream, Some(&options));
896            Some(create_at_rule_node(arena, at_rule, EnumToken::AtRuleNodeType, &at_rule_tokens, state, result_errors, at_rule_end, &val, parse_as_block))
897        }
898    }
899}
900
901/// parse a string as declaration nodes (detached). a new arena is created when none is given
902pub fn parse_declarations(declaration: &str, arena: Option<Rc<AstArena>>) -> (Rc<AstArena>, Vec<u32>) {
903    let stream = format!(".x{{{}}}", declaration);
904    let source = SourceFile::new(Rc::from(""), Vec::new(), Some(Rc::from("")));
905    let sources = crate::options::SourcesMap::default();
906    sources.borrow_mut().insert(source.id, source.clone());
907    let options = ParserOptions {
908        set_parent: Some(false),
909        minify: Some(false),
910        validation: Some(false),
911        source: Some(source.clone()),
912        sources_map: Some(sources),
913        ..Default::default()
914    };
915    let tokenizer = Tokenizer::new(create_parse_info(Some(&CssInput::from(stream)), source));
916    let result = do_parse_sync(tokenizer, options, arena, Rc::new(crate::host::NoHost)).expect("parse declarations");
917    let arena = result.arena.clone();
918    let rule = arena.first_child.get(result.ast);
919    let mut nodes = Vec::new();
920    let mut node = if rule == 0 { 0 } else { arena.first_child.get(rule) };
921    while node != 0 {
922        let next = arena.next_sibling.get(node);
923        if matches!(arena.data_types.get(node), EnumToken::DeclarationNodeType | EnumToken::CommentNodeType) {
924            arena.detach(node);
925            nodes.push(node);
926        }
927        node = next;
928    }
929    (arena, nodes)
930}
931
932/// parse a string as the content of a style rule (detached nodes, the comments are dropped)
933pub fn parse_rule_content(content: &str, arena: Rc<AstArena>, parse_color: Option<bool>) -> Vec<u32> {
934    let source = SourceFile::new(Rc::from(""), Vec::new(), Some(Rc::from("")));
935    let sources = crate::options::SourcesMap::default();
936    sources.borrow_mut().insert(source.id, source.clone());
937    let options = ParserOptions {
938        set_parent: Some(false),
939        minify: Some(false),
940        validation: Some(false),
941        lenient: Some(true),
942        nesting_rules: Some(true),
943        expand_nesting_rules: Some(false),
944        evaluate_mixins: Some(false),
945        parse_color: Some(parse_color.unwrap_or(true)),
946        source: Some(source.clone()),
947        sources_map: Some(sources),
948        ..Default::default()
949    };
950    let tokenizer = Tokenizer::new(create_parse_info(Some(&CssInput::from(format!(".x{{{}}}", content))), source));
951    let result = do_parse_sync(tokenizer, options, Some(arena.clone()), Rc::new(crate::host::NoHost)).expect("parse rule content");
952    let rule = arena.first_child.get(result.ast);
953    let mut nodes = Vec::new();
954    let mut node = if rule == 0 { 0 } else { arena.first_child.get(rule) };
955    while node != 0 {
956        let next = arena.next_sibling.get(node);
957        if arena.data_types.get(node) != EnumToken::CommentNodeType {
958            arena.detach(node);
959            nodes.push(node);
960        }
961        node = next;
962    }
963    nodes
964}
965
966/// parse a css string into tokens (`parseString(arena, src)` with `{ parseColor: true }`)
967pub fn parse_string(arena: &AstArena, src: &str) -> Vec<u32> {
968    let options = ParserOptions { parse_color: Some(true), ..Default::default() };
969    parse_string_with(arena, src, Some(&options), None)
970}
971
972/// parse a css string into tokens. `options`: `src` and `parseColor`; `None` is `null` (the colors are parsed)
973pub fn parse_string_with(arena: &AstArena, src: &str, options: Option<&ParserOptions>, errors: Option<&mut Vec<ErrorDescription>>) -> Vec<u32> {
974    let file = options.and_then(|o| o.src.clone()).unwrap_or_default();
975    let source = SourceFile::new(Rc::from(""), Vec::new(), Some(Rc::from(file.as_str())));
976    let mut tokenizer = Tokenizer::new(create_parse_info(Some(&CssInput::from(src)), source));
977    let mut mapped: Vec<u32> = Vec::new();
978    while tokenizer.typ != Some(EnumToken::EOF) {
979        tokenizer.next();
980        mapped.push(allocate_token(arena, &mut tokenizer, -1));
981    }
982    parse_tokens(arena, &mut mapped, options, errors);
983    let len = mapped.len();
984    let start = len.saturating_sub(if len >= 2 && arena.data_types.get(mapped[len - 2]) == EnumToken::WhitespaceTokenType { 2 } else { 1 });
985    let removed: Vec<u32> = mapped.drain(start..(start + 2).min(len)).collect();
986    for r in removed {
987        if arena.parents.get(r) == 0 && arena.first_token.get(r) == 0 && arena.first_child.get(r) == 0 {
988            arena.recycle(r);
989        }
990    }
991    mapped
992}
993
994fn parse_error(arena: &AstArena, message: String, node: Option<u32>, options: Option<&ParserOptions>) -> ErrorDescription {
995    let mut error = ErrorDescription::drop(message);
996    error.node = node;
997    error.location = options.and_then(|o| node.and_then(|n| token_location(arena, n, o)));
998    error
999}
1000
1001/// parse the function, parentheses and attribute tokens of a token list (in place). `None` options: `{ parseColor:
1002/// true }`
1003pub fn parse_tokens(arena: &AstArena, tokens: &mut Vec<u32>, options: Option<&ParserOptions>, mut errors: Option<&mut Vec<ErrorDescription>>) {
1004    let t = |x: u32| arena.data_types.get(x);
1005    let parse_colors = options.map_or(true, |o| o.parse_color == Some(true));
1006    let mut stack: Vec<u32> = Vec::new();
1007    let mut i: isize = 0;
1008    while (i as usize) < tokens.len() {
1009        let iu = i as usize;
1010        let mut tk = tokens[iu];
1011        let mut typ = t(tk);
1012        if typ == EnumToken::FunctionTokenDefType && iu > 0 && matches!(t(tokens[iu - 1]), EnumToken::ColonTokenType | EnumToken::DoubleColonTokenType) {
1013            let previous = tokens[iu - 1];
1014            let prefix = if t(previous) == EnumToken::ColonTokenType { ":" } else { "::" };
1015            let name = format!("{}{}", prefix, arena.resolve_string(arena.string_value.get(tk)));
1016            arena.string_value.set(previous, arena.intern_string(&name));
1017            arena.data_types.set(previous, EnumToken::PseudoClassFunctionTokenDefType);
1018            arena.set_span(previous, arena.get_source_id(previous), arena.get_span_start(previous), arena.get_span_end(tk));
1019            tokens.remove(iu);
1020            i -= 1;
1021            tk = previous;
1022            typ = EnumToken::PseudoClassFunctionTokenDefType;
1023        }
1024        if typ == EnumToken::AttrStartTokenType || typ == EnumToken::StartParensTokenType || is_function_def_type(typ) {
1025            stack.push(tk);
1026            i += 1;
1027            continue;
1028        }
1029        let iu = i as usize;
1030        if typ == EnumToken::EndParensTokenType {
1031            if stack.last().is_none_or(|&s| t(s) != EnumToken::StartParensTokenType && !is_function_def_type(t(s))) {
1032                if let Some(errors) = errors.as_deref_mut() {
1033                    errors.push(parse_error(arena, "Unbalanced token ')'".into(), stack.last().copied(), options));
1034                }
1035                i += 1;
1036                continue;
1037            }
1038            tokens.remove(iu);
1039            let index = tokens.iter().position(|&x| x == *stack.last().unwrap()).unwrap();
1040            let func = tokens[index];
1041            arena.data_types.set(
1042                func,
1043                if t(func) == EnumToken::StartParensTokenType { EnumToken::ParensTokenType } else { tokens_func_def_map(t(func)).unwrap_or(0) },
1044            );
1045            let mut inner: Vec<u32> = tokens.drain(index + 1..iu).collect();
1046            trim_array(arena, &mut inner);
1047            arena.set_token_list(func, &inner);
1048            arena.set_span(func, arena.get_source_id(func), arena.get_span_start(func), arena.get_span_end(tk));
1049            i = index as isize;
1050            if t(func) == EnumToken::ColorTokenType && parse_colors {
1051                parse_color(arena, func);
1052            }
1053            stack.pop();
1054            i += 1;
1055            continue;
1056        }
1057        if typ == EnumToken::AttrEndTokenType {
1058            if stack.last().is_none_or(|&s| t(s) != EnumToken::AttrStartTokenType) {
1059                if let Some(errors) = errors.as_deref_mut() {
1060                    errors.push(parse_error(arena, "Unbalanced token ']'".into(), stack.last().copied(), options));
1061                }
1062                i += 1;
1063                continue;
1064            }
1065            let attr = *stack.last().unwrap();
1066            let index = tokens.iter().position(|&x| x == attr).unwrap();
1067            arena.set_span(attr, arena.get_source_id(attr), arena.get_span_start(attr), arena.get_span_end(tk));
1068            tokens.remove(iu);
1069            arena.data_types.set(attr, EnumToken::AttrTokenType);
1070            let inner: Vec<u32> = tokens.drain(index + 1..iu).collect();
1071            arena.set_token_list(attr, &inner);
1072            i = index as isize;
1073            stack.pop();
1074            i += 1;
1075            continue;
1076        }
1077        if typ == EnumToken::IdenTokenType {
1078            if arena.string_equals(arena.string_value.get(tk), "from") && iu > 0 {
1079                let mut left: Vec<u32> = Vec::new();
1080                let mut right: Vec<u32> = Vec::new();
1081                let mut found_left = 0;
1082                let mut found_right = 0;
1083                let mut k = iu;
1084                let mut l = iu;
1085                while k > 0 {
1086                    let p = t(tokens[k - 1]);
1087                    if matches!(p, EnumToken::CommentTokenType | EnumToken::WhitespaceTokenType) {
1088                        k -= 1;
1089                        left.push(tokens[k]);
1090                        continue;
1091                    }
1092                    if matches!(p, EnumToken::IdenTokenType | EnumToken::DashedIdenTokenType) {
1093                        found_left += 1;
1094                        k -= 1;
1095                        left.push(tokens[k]);
1096                        continue;
1097                    }
1098                    break;
1099                }
1100                loop {
1101                    l += 1;
1102                    if l >= tokens.len() {
1103                        break;
1104                    }
1105                    let n = t(tokens[l]);
1106                    if matches!(n, EnumToken::CommentTokenType | EnumToken::WhitespaceTokenType) {
1107                        right.push(tokens[l]);
1108                        continue;
1109                    }
1110                    if matches!(n, EnumToken::IdenTokenType | EnumToken::StringTokenType) {
1111                        found_right += 1;
1112                        right.push(tokens[l]);
1113                        continue;
1114                    }
1115                    break;
1116                }
1117                if found_left > 0 && found_right == 1 {
1118                    while left.first().is_some_and(|&x| t(x) == EnumToken::WhitespaceTokenType) {
1119                        left.remove(0);
1120                    }
1121                    while left.last().is_some_and(|&x| t(x) == EnumToken::WhitespaceTokenType) {
1122                        left.pop();
1123                    }
1124                    let composes = arena.create_token(EnumToken::ComposesSelectorNodeType, TokenValue::None, None);
1125                    let mut from = 0u32;
1126                    for &b in &right {
1127                        if from == 0 || matches!(t(b), EnumToken::IdenTokenType | EnumToken::StringTokenType) {
1128                            from = b;
1129                        }
1130                    }
1131                    arena.set_token_list(arena.field_list(composes, TokenField::L), &left);
1132                    if from != 0 {
1133                        arena.set_token_list(arena.field_list(composes, TokenField::R), &[from]);
1134                    }
1135                    let end = (l + 1).min(tokens.len());
1136                    tokens.splice(k..end, [composes]);
1137                    i = k as isize;
1138                    i += 1;
1139                    continue;
1140                }
1141            } else if parse_colors && is_color(arena, tk, None) {
1142                parse_color(arena, tk);
1143            }
1144        }
1145        let iu = i as usize;
1146        if typ == EnumToken::WhitespaceTokenType
1147            && (iu == 0
1148                || iu + 1 == tokens.len()
1149                || tokens.get(iu + 1).is_some_and(|&n| {
1150                    matches!(t(n), EnumToken::CommaTokenType | EnumToken::GteTokenType | EnumToken::LteTokenType | EnumToken::ColumnCombinatorTokenType)
1151                })
1152                || (iu > 0 && is_trim_white_space(t(tokens[iu - 1]))))
1153        {
1154            tokens.remove(iu);
1155            continue;
1156        }
1157        if typ == EnumToken::ColonTokenType {
1158            if let Some(&next_token) = tokens.get(iu + 1) {
1159                let next = t(next_token);
1160                if next == EnumToken::FunctionTokenType {
1161                    arena.data_types.set(next_token, EnumToken::PseudoClassFuncTokenType);
1162                } else if next == EnumToken::IdenTokenType {
1163                    let name = format!(":{}", arena.resolve_string(arena.string_value.get(next_token)));
1164                    arena.string_value.set(next_token, arena.intern_string(&name));
1165                    arena.data_types.set(next_token, EnumToken::PseudoClassTokenType);
1166                }
1167                if next == EnumToken::FunctionTokenType || next == EnumToken::IdenTokenType {
1168                    tokens.remove(iu);
1169                    i -= 1;
1170                }
1171            }
1172        }
1173        if typ == EnumToken::CommaTokenType {
1174            let iu = i as usize;
1175            if iu + 1 < tokens.len() && t(tokens[iu + 1]) == EnumToken::WhitespaceTokenType {
1176                tokens.remove(iu + 1);
1177            }
1178            if iu > 0 && t(tokens[iu - 1]) == EnumToken::WhitespaceTokenType {
1179                tokens.remove(iu - 1);
1180                i -= 1;
1181            }
1182        }
1183        i += 1;
1184    }
1185    if let Some(&node) = stack.last() {
1186        if let Some(errors) = errors {
1187            let expecting = if t(node) == EnumToken::AttrStartTokenType { "']'" } else { ")" };
1188            errors.push(parse_error(arena, format!("Unbalanced token. Expecting {}'", expecting), Some(node), options));
1189        }
1190    }
1191}
1192
1193#[allow(dead_code)]
1194fn _unused(a: &str) -> bool {
1195    equals_ignore_case(a, a)
1196}