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