Skip to main content

rust_css_parser/parser/
parse_main.rs

1//! Port of `doParse()` / `doParseSync()` of `src/parser/parse.ts`.
2//!
3//! One `async fn` serves both, with every feature: `do_parse_sync()` runs it to completion (a host that returns its
4//! values synchronously resolves the `@import` rules, the css modules, ...). The restrictions of the typescript
5//! `doParseSync()` (no import resolution, errors instead of loading css modules, `generateSyncScopedName()`) are kept by
6//! the javascript bindings only, with `ParserOptions::sync_api_compat`.
7
8use crate::ast::arena::{AstArena, TokenField};
9use crate::ast::features::mixin::evaluate_mixins;
10use crate::ast::minify::{merge_rules, minify};
11use crate::ast::types::{EnumAstNodeStatus, EnumToken, ModuleCaseTransformEnum as Case, ModuleScopeEnumOptions as Scope, WalkerEvent};
12use crate::ast::walk::{NodeWalker, ValueWalker, WalkerValueOptions, WalkerValueResult};
13use crate::fs::resolve::{dirname, resolve};
14use crate::host::{resolve as await_host, Host, HostDef, HostError, HostValue};
15use crate::ast::types::MergeRulesEnum;
16use crate::options::{ModuleOption, ModuleScoped, ParserOptions, RemoveDuplicateDeclarations, SourceMapOption};
17use crate::parser::input::CssInput;
18use crate::parser::parse::{
19    allocate_token, allocate_whitespace, arena_capacity, drop_invalid_nodes, get_key_name, is_bad_token, is_definition_block, is_statement_end, parse_node, parse_string,
20    recycle_statement_tokens, render_tokens, ParseResultStats,
21};
22use crate::parser::source::SourceFile;
23use crate::parser::tokenize::{create_parse_info, StreamChunk, Tokenizer};
24use crate::parser::utils::codes::CodeUnits;
25use crate::parser::utils::hash::{hash, sync_hash, HASH_ALGORITHMS};
26use crate::parser::utils::text::{camelize, equals_ignore_case};
27use crate::plain::{Plain, PlainObject};
28use crate::printer::render::render_value_default;
29use crate::syntax::constants::is_function_def_type;
30use crate::syntax::syntax::is_ident_color;
31use crate::types::{ErrorDescription, ResponseType};
32use crate::utils::time::{format_ms, now};
33use crate::validation::match_::{drop_error, match_selector_syntax, trim_array};
34use std::cell::RefCell;
35use crate::utils::fx::HashMap;
36use std::future::Future;
37use std::pin::Pin;
38use std::rc::Rc;
39
40/// ordered string map (`Record<string, string>`)
41#[derive(Clone, Debug, Default, PartialEq)]
42pub struct StrMap {
43    entries: Vec<(String, String)>,
44    index: HashMap<String, usize>,
45}
46
47impl StrMap {
48    pub fn get(&self, key: &str) -> Option<&str> {
49        self.index.get(key).map(|&i| self.entries[i].1.as_str())
50    }
51
52    pub fn has(&self, key: &str) -> bool {
53        self.index.contains_key(key)
54    }
55
56    pub fn set(&mut self, key: &str, value: String) {
57        match self.index.get(key) {
58            Some(&i) => self.entries[i].1 = value,
59            None => {
60                self.index.insert(key.to_string(), self.entries.len());
61                self.entries.push((key.to_string(), value));
62            }
63        }
64    }
65
66    pub fn entries(&self) -> &[(String, String)] {
67        &self.entries
68    }
69
70    pub fn len(&self) -> usize {
71        self.entries.len()
72    }
73
74    pub fn is_empty(&self) -> bool {
75        self.entries.is_empty()
76    }
77}
78
79/// `ParseResult`
80#[derive(Clone)]
81pub struct ParseResult {
82    pub ast: u32,
83    pub arena: Rc<AstArena>,
84    pub errors: Vec<ErrorDescription>,
85    pub stats: ParseResultStats,
86    pub mapping: Option<StrMap>,
87    pub css_module_variables: Option<Vec<(String, u32)>>,
88    pub import_mapping: Option<Vec<(String, StrMap)>>,
89    pub rev_mapping: Option<StrMap>,
90}
91
92/// parse css synchronously: [`do_parse()`] run to completion. every feature is available; a host callback that
93/// returns a pending promise is an error
94pub fn do_parse_sync(tokenizer: Tokenizer, options: ParserOptions, arena: Option<Rc<AstArena>>, host: Rc<dyn Host>) -> Result<ParseResult, HostError> {
95    crate::host::block_on(do_parse(tokenizer, options, arena, host))
96}
97
98/// boxed future (recursive parses)
99pub type ParseFuture = Pin<Box<dyn Future<Output = Result<ParseResult, HostError>>>>;
100
101/// parse css (`doParse()`). `arena`: the arena of the parent parse (nested parses share it)
102pub fn do_parse(tokenizer: Tokenizer, options: ParserOptions, arena: Option<Rc<AstArena>>, host: Rc<dyn Host>) -> ParseFuture {
103    Box::pin(do_parse_impl(tokenizer, options, arena, host))
104}
105
106/// the default options of `doParse()`, then the options of the caller
107fn with_defaults(options: ParserOptions) -> ParserOptions {
108    let mut o = options;
109    // the fast mode settings (`fastModeOptions`), an option given explicitly takes precedence
110    if o.fast_mode == Some(true) {
111        o.minify.get_or_insert(false);
112        o.merge_rules.get_or_insert(MergeRulesEnum::None);
113    }
114    o.src.get_or_insert_with(String::new);
115    o.sourcemap.get_or_insert(SourceMapOption::Off);
116    o.minify.get_or_insert(true);
117    o.pass.get_or_insert(1);
118    o.expand_if_syntax.get_or_insert(false);
119    o.parse_color.get_or_insert(true);
120    o.nesting_rules.get_or_insert(true);
121    o.resolve_import.get_or_insert(false);
122    o.resolve_urls.get_or_insert(false);
123    o.remove_charset.get_or_insert(true);
124    o.remove_empty.get_or_insert(true);
125    o.remove_duplicate_declarations.get_or_insert(RemoveDuplicateDeclarations::Bool(true));
126    o.compute_transform.get_or_insert(true);
127    o.compute_shorthand.get_or_insert(true);
128    o.compute_calc_expression.get_or_insert(true);
129    o.inline_css_variables.get_or_insert(false);
130    o.evaluate_mixins.get_or_insert(false);
131    o.keep_mixins.get_or_insert(false);
132    o.set_parent.get_or_insert(true);
133    o.remove_prefix.get_or_insert(false);
134    o.validation.get_or_insert(false);
135    o.lenient.get_or_insert(true);
136    o
137}
138
139fn module_is_set(module: &Option<ModuleOption>) -> bool {
140    match module {
141        None => false,
142        Some(ModuleOption::Bool(b)) => *b,
143        Some(ModuleOption::Flags(f)) => *f != 0,
144        Some(ModuleOption::Options(_)) => true,
145    }
146}
147
148/// read the next chunk of a stream (the `stream` callback of the options) and append it to the code units of the
149/// tokenizer. the strings of the tokens are ranges of the code units read so far: the source text of the arena is set
150/// again
151async fn read_chunk(tokenizer: &mut Tokenizer, arena: &AstArena, source_index: usize, options: &ParserOptions, host: &Rc<dyn Host>) -> Result<(), HostError> {
152    let callback = options.stream.ok_or_else(|| HostError("no stream reader".into()))?;
153    let chunk = match await_host(host.call(callback, None, Vec::new())).await? {
154        HostValue::Bytes(bytes) => Some(StreamChunk::Bytes(bytes)),
155        HostValue::Str(text) => Some(StreamChunk::Text(text)),
156        _ => None,
157    };
158    // the buffer of the tokenizer is written in place when the arena does not hold it
159    arena.set_source_text(source_index, CodeUnits::Bytes(Rc::from(&[][..])));
160    tokenizer.append(chunk);
161    arena.set_source_text(source_index, tokenizer.codes().clone());
162    Ok(())
163}
164
165async fn do_parse_impl(tokenizer: Tokenizer, options: ParserOptions, arena: Option<Rc<AstArena>>, host: Rc<dyn Host>) -> Result<ParseResult, HostError> {
166    let mut options = with_defaults(options);
167    // the restrictions of the typescript sync api (bindings only)
168    let is_sync = options.sync_api_compat;
169    if !is_sync {
170        options.minify_ast = options.minify_ast.or(options.minify);
171    }
172    if module_is_set(&options.module) {
173        options.expand_nesting_rules = Some(true);
174    }
175    if options.expand_nesting_rules == Some(true) {
176        options.nesting_rules = Some(false);
177    }
178    if is_sync {
179        options.minify_ast = options.minify_ast.or(options.minify);
180    } else if options.resolve_import == Some(true) {
181        options.resolve_urls = Some(true);
182    }
183    let start_time = now();
184    let mut errors: Vec<ErrorDescription> = Vec::new();
185    let mut stack: Vec<u32> = Vec::new();
186    let mut stats = ParseResultStats::new(options.src.as_deref().unwrap_or(""));
187    let mut invalid_nodes: Vec<u32> = Vec::new();
188    let mut error_start = 0usize;
189    let mut invalid_start = 0usize;
190    let mut statement: Vec<u32> = Vec::new();
191    let mut tokenizer = tokenizer;
192    let arena = arena.unwrap_or_else(|| AstArena::shared(arena_capacity(&tokenizer)));
193    AstArena::register(&arena);
194    let mut ast = if arena.current() == 1 { arena.root } else { arena.create_style_sheet() };
195    let mut tokens: Vec<u32> = Vec::new();
196    let mut context = ast;
197    let mut imports: Vec<u32> = Vec::new();
198    let mut parens_match = 0i32;
199    let mut curly_bracket_match = 0i32;
200    let mut parens_block_match = 0i32;
201    arena.set_location(ast, Some(tokenizer.source_id()), Some(0), Some(0));
202    let source_index = arena.source_index(tokenizer.source_id());
203    arena.set_source_text(source_index as usize, tokenizer.codes().clone());
204    let a = &*arena;
205    let t = |x: u32| a.data_types.get(x);
206    // whitespace outside of parentheses, at the start of a statement or before ';', '{' and '}' is not significant: it
207    // is not allocated. the whitespace that follows a token is allocated when the next token is read
208    let mut whitespace: Option<(u32, u32)> = None;
209    while tokenizer.typ != Some(EnumToken::EOF) {
210        tokenizer.next();
211        // a stream: the token may continue in the next chunk, the chunk is read and the token is read again
212        if tokenizer.waiting {
213            read_chunk(&mut tokenizer, a, source_index as usize, &options, &host).await?;
214            continue;
215        }
216        let mut item_type = tokenizer.typ.unwrap_or(0);
217        stats.bytes_in = tokenizer.bytes_in.unwrap_or(0) as u64;
218        stats.tokens_count += 1;
219        if parens_match == 0 {
220            if item_type == EnumToken::WhitespaceTokenType {
221                if !tokens.is_empty() {
222                    whitespace = Some((tokenizer.sta.unwrap_or(0) as u32, tokenizer.end.unwrap_or(0) as u32));
223                }
224                continue;
225            }
226            if let Some((start, end)) = whitespace.take() {
227                if !is_statement_end(item_type) {
228                    let ws = allocate_whitespace(a, source_index as u32, start, end);
229                    tokens.push(ws);
230                    statement.push(ws);
231                }
232            }
233        }
234        let mut item = allocate_token(a, &mut tokenizer, source_index as i32);
235        if is_bad_token(item_type) {
236            tokens.push(item);
237            statement.push(item);
238            errors.push(drop_error(a, "Bad token".into(), item, &options));
239            continue;
240        }
241        if item_type == EnumToken::StartParensTokenType || is_function_def_type(item_type) {
242            parens_match += 1;
243        } else if item_type == EnumToken::EndParensTokenType && parens_match > 0 {
244            parens_match -= 1;
245            if parens_match == 0 {
246                parens_block_match = 0;
247            }
248        }
249        let mut parens_block = false;
250        if parens_match > 0 && item_type == EnumToken::BlockStartTokenType {
251            parens_block_match += 1;
252            parens_block = true;
253        } else if parens_match > 0 && parens_block_match > 0 && item_type == EnumToken::BlockEndTokenType {
254            parens_block_match -= 1;
255            parens_block = true;
256        } else if item_type == EnumToken::BlockStartTokenType {
257            curly_bracket_match += 1;
258        } else if item_type == EnumToken::BlockEndTokenType && curly_bracket_match > 0 {
259            curly_bracket_match -= 1;
260        }
261        tokens.push(item);
262        statement.push(item);
263        if parens_match == 0
264            && matches!(item_type, EnumToken::SemiColonTokenType | EnumToken::BlockStartTokenType | EnumToken::EOFTokenType)
265        {
266            let node = parse_node(a, &mut tokens, context, &options, &mut errors, &mut stats, &mut invalid_nodes, parens_match);
267            if let Some(node) = node {
268                if a.flags.get(node) & EnumAstNodeStatus::HasChildren != 0 {
269                    stack.push(node);
270                    context = node;
271                } else if !is_sync && t(node) == EnumToken::AtRuleNodeType && a.string_equals(a.name.get(node), "import") {
272                    imports.push(node);
273                }
274            } else if item_type == EnumToken::BlockStartTokenType {
275                let mut in_block = 1;
276                tokens.clear();
277                tokens.push(item);
278                loop {
279                    tokenizer.next();
280                    if tokenizer.waiting {
281                        read_chunk(&mut tokenizer, a, source_index as usize, &options, &host).await?;
282                        continue;
283                    }
284                    item = allocate_token(a, &mut tokenizer, source_index as i32);
285                    item_type = tokenizer.typ.unwrap_or(0);
286                    tokens.push(item);
287                    statement.push(item);
288                    if item_type == EnumToken::BlockStartTokenType {
289                        in_block += 1;
290                    } else if item_type == EnumToken::BlockEndTokenType {
291                        in_block -= 1;
292                    }
293                    if !(in_block != 0 && tokenizer.typ != Some(EnumToken::EOF)) {
294                        break;
295                    }
296                }
297                if !tokens.is_empty() {
298                    let mut error = ErrorDescription::drop("invalid block");
299                    error.location = crate::validation::match_::token_location(a, tokens[0], &options);
300                    errors.push(error);
301                }
302            }
303            recycle_statement_tokens(a, &statement, &errors, error_start, &invalid_nodes, invalid_start);
304            statement.clear();
305            tokens.clear();
306            error_start = errors.len();
307            invalid_start = invalid_nodes.len();
308        } else if !parens_block && (parens_match == 0 || curly_bracket_match == 0) && item_type == EnumToken::BlockEndTokenType {
309            parse_node(a, &mut tokens, context, &options, &mut errors, &mut stats, &mut invalid_nodes, parens_match);
310            a.set_span(context, a.get_source_id(context), a.get_span_start(context), a.get_span_end(item));
311            let previous_node = stack.pop();
312            context = stack.last().copied().unwrap_or(ast);
313            if options.remove_empty == Some(true) {
314                if let Some(previous) = previous_node {
315                    if a.first_child.get(previous) == 0 && !is_definition_block(a, previous) && a.last_child.get(context) == previous {
316                        a.detach(previous);
317                    }
318                }
319            }
320            recycle_statement_tokens(a, &statement, &errors, error_start, &invalid_nodes, invalid_start);
321            statement.clear();
322            tokens.clear();
323            error_start = errors.len();
324            invalid_start = invalid_nodes.len();
325            parens_match = 0;
326            parens_block_match = 0;
327            curly_bracket_match = 0;
328        }
329    }
330    if !tokens.is_empty() {
331        if let Some(node) = parse_node(a, &mut tokens, context, &options, &mut errors, &mut stats, &mut invalid_nodes, parens_match) {
332            // typescript compares the value (not the name) of the node with "import"
333            if !is_sync && t(node) == EnumToken::AtRuleNodeType && a.string_equals(a.string_value.get(node), "import") {
334                imports.push(node);
335            }
336            if a.flags.get(node) & EnumAstNodeStatus::HasChildren != 0 {
337                stack.push(node);
338            }
339        }
340    }
341    if !imports.is_empty() && options.resolve_import == Some(true) {
342        resolve_imports(&arena, &imports, &options, &host, &mut stats, &mut errors).await;
343    }
344    let end_parse_time = now();
345    let minify_options = if options.evaluate_mixins == Some(true) {
346        ParserOptions { evaluate_mixins: Some(false), ..options.clone() }
347    } else {
348        options.clone()
349    };
350    if options.evaluate_mixins == Some(true) {
351        drop_invalid_nodes(a, &invalid_nodes, &options);
352        evaluate_mixins(a, ast, &options);
353    }
354    if options.expand_nesting_rules == Some(true) {
355        ast = a.expand(ast);
356    }
357    if let Some(visitor) = options.visitor.clone() {
358        apply_visitors(&arena, ast, &visitor, &mut errors, &host, is_sync).await?;
359    }
360    drop_invalid_nodes(a, &invalid_nodes, &options);
361    if options.minify_ast == Some(true) {
362        if a.first_child.get(ast) != 0 {
363            for _ in 0..options.pass.unwrap_or(1) {
364                minify(a, ast, &minify_options, true, Some(&mut errors), false);
365            }
366        }
367    } else if matches!(options.merge_rules, Some(m) if m != MergeRulesEnum::None) && a.first_child.get(ast) != 0 {
368        // the ast is not minified: the adjacent rules are merged
369        merge_rules(a, ast, &minify_options);
370    }
371    stats.bytes_in += stats.imported_bytes_in;
372    a.release_source_codes(source_index as usize);
373    a.input_lengths.borrow_mut().insert(ast, stats.bytes_in as u32);
374    let mut end_time = now();
375    stats.parse = format_ms(end_parse_time - start_time);
376    stats.minify = format_ms(end_time - end_parse_time);
377    stats.total = format_ms(end_time - start_time);
378    let mut result = ParseResult {
379        ast,
380        arena: arena.clone(),
381        errors,
382        stats,
383        mapping: None,
384        css_module_variables: None,
385        import_mapping: None,
386        rev_mapping: None,
387    };
388    if module_is_set(&options.module) {
389        let parse_module_time = now();
390        process_module(&mut result, &options, &host, is_sync).await?;
391        end_time = now();
392        result.stats.module = Some(format_ms(end_time - parse_module_time));
393        result.stats.total = format_ms(end_time - start_time);
394    }
395    Ok(result)
396}
397
398/// load a file with the host loader: the source file and the input
399async fn load_source(host: &Rc<dyn Host>, options: &ParserOptions, absolute: &str, relative: &str, current: &str) -> Result<(Rc<SourceFile>, CssInput), HostError> {
400    let load = options.load.ok_or_else(|| HostError("no loader".into()))?;
401    let mut src = PlainObject::new();
402    src.set("absolute", absolute);
403    src.set("relative", relative);
404    let result = await_host(host.call(load, None, vec![HostValue::Plain(Plain::Object(src)), HostValue::Str(Rc::from(current)), HostValue::Number(ResponseType::ArrayBuffer as f64)])).await?;
405    let (input, text) = match result {
406        HostValue::Str(s) => (CssInput::Str(s.clone()), s),
407        HostValue::Bytes(b) => (CssInput::Bytes(b), Rc::from("")),
408        other => return Err(HostError(format!("unexpected load result {:?}", other))),
409    };
410    let source = SourceFile::new(text, Vec::new(), Some(Rc::from(relative)));
411    if let Some(map) = &options.sources_map {
412        map.borrow_mut().insert(source.id, source.clone());
413    }
414    Ok((source, input))
415}
416
417/// resolve the `@import` rules: the imported stylesheets are parsed in the same arena (concurrently, like
418/// `Promise.all()`)
419async fn resolve_imports(arena: &Rc<AstArena>, imports: &[u32], options: &ParserOptions, host: &Rc<dyn Host>, stats: &mut ParseResultStats, errors: &mut Vec<ErrorDescription>) {
420    let a = &**arena;
421    let mut tasks: Vec<Pin<Box<dyn Future<Output = (u32, Result<ParseResult, HostError>)>>>> = Vec::new();
422    for &node in imports {
423        if a.flags.get(node) & EnumAstNodeStatus::StateMask != EnumAstNodeStatus::Validated {
424            continue;
425        }
426        let token = a.first_token.get(node);
427        let value = a.resolve_string(a.string_value.get(token));
428        let url: String = if a.data_types.get(token) == EnumToken::StringTokenType {
429            let chars: Vec<char> = value.chars().collect();
430            if chars.len() >= 2 { chars[1..chars.len() - 1].iter().collect() } else { String::new() }
431        } else {
432            value.to_string()
433        };
434        let options = options.clone();
435        let host = host.clone();
436        let arena = arena.clone();
437        tasks.push(Box::pin(async move {
438            let base = match options.src.as_deref() {
439                Some(s) if !s.is_empty() => dirname(s),
440                _ => options.cwd.clone().unwrap_or_default(),
441            };
442            let src = resolve(&url, &base, None);
443            let result = async {
444                let (source, input) = load_source(&host, &options, &src.absolute, &src.relative, ".").await?;
445                let parse_info = create_parse_info(Some(&input), source);
446                let child_src = resolve(&url, options.src.as_deref().filter(|s| !s.is_empty()).or(options.cwd.as_deref()).unwrap_or(""), None).relative;
447                let child_options = ParserOptions {
448                    minify: Some(false),
449                    set_parent: Some(false),
450                    evaluate_mixins: Some(false),
451                    src: Some(child_src),
452                    source: None,
453                    ..options.clone()
454                };
455                do_parse(Tokenizer::new(parse_info), child_options, Some(arena), host.clone()).await
456            }
457            .await;
458            (node, result)
459        }));
460    }
461    for (node, result) in join_all(tasks).await {
462        match result {
463            Ok(root) => {
464                stats.imported_bytes_in += root.stats.bytes_in;
465                stats.nodes_count += root.stats.nodes_count;
466                stats.tokens_count += root.stats.tokens_count;
467                stats.imports.push(root.stats.clone());
468                if a.parents.get(node) != 0 {
469                    a.move_children(root.ast, a.parents.get(node), node);
470                    a.detach(node);
471                }
472                errors.extend(root.errors);
473            }
474            Err(error) => {
475                let mut e = ErrorDescription::ignore(format!("doParse: {}", error.0));
476                e.error = Some(error.0);
477                errors.push(e);
478            }
479        }
480    }
481}
482
483/// run futures concurrently: the results are returned in the completion order (`Promise.all()` callbacks)
484async fn join_all<T>(mut futures: Vec<Pin<Box<dyn Future<Output = T>>>>) -> Vec<T> {
485    let mut results: Vec<T> = Vec::new();
486    std::future::poll_fn(move |cx| {
487        let mut i = 0;
488        while i < futures.len() {
489            match futures[i].as_mut().poll(cx) {
490                std::task::Poll::Ready(v) => {
491                    results.push(v);
492                    // the future is complete
493                    drop(futures.remove(i));
494                }
495                std::task::Poll::Pending => i += 1,
496            }
497        }
498        if futures.is_empty() {
499            std::task::Poll::Ready(std::mem::take(&mut results))
500        } else {
501            std::task::Poll::Pending
502        }
503    })
504    .await
505}
506
507// ---------------------------------------------------------------------------------------------------------------------
508// visitors
509// ---------------------------------------------------------------------------------------------------------------------
510
511/// key of a handler map: a generic node name (`Declaration`, `Rule`, ...) or a token type
512#[derive(Clone, Debug, PartialEq)]
513enum MapKey {
514    Name(&'static str),
515    Token(u8),
516}
517
518type HandlerMap = Vec<(MapKey, Vec<HostDef>)>;
519
520fn map_push(map: &mut HandlerMap, key: MapKey, value: HostDef) {
521    match map.iter_mut().find(|(k, _)| *k == key) {
522        Some((_, list)) => list.push(value),
523        None => map.push((key, vec![value])),
524    }
525}
526
527/// `ParsedVisitorHandlers`
528struct ParsedVisitors {
529    all_handlers: Vec<HandlerMap>,
530    include_tokens: bool,
531    all: Vec<HostDef>,
532    pre_all: Vec<HostDef>,
533    post_all: Vec<HostDef>,
534}
535
536/// `typeof value.type == "number" && (value.type & (WalkerEvent.Enter | WalkerEvent.Leave)) != 0`: the events are flags
537fn walker_event(value: &HostDef) -> Option<u32> {
538    match value {
539        HostDef::Number(n) => {
540            let n = *n as i64 as u32;
541            (n & (WalkerEvent::Enter | WalkerEvent::Leave) != 0).then_some(n)
542        }
543        _ => None,
544    }
545}
546
547fn set_add(set: &mut Vec<HostDef>, value: HostDef) {
548    let id = |d: &HostDef| if let HostDef::Fn { id, .. } = d { Some(*id) } else { None };
549    if !set.iter().any(|x| id(x).is_some() && id(x) == id(&value)) {
550        set.push(value);
551    }
552}
553
554const GENERIC_KEYS: [&str; 5] = ["Declaration", "Rule", "AtRule", "KeyframesRule", "KeyframesAtRule"];
555
556fn parse_visitors(def: &HostDef, errors: &mut Vec<ErrorDescription>) -> ParsedVisitors {
557    let mut visitors: Vec<(Rc<str>, HostDef)> = if def.is_fn() { vec![(Rc::from("0"), def.clone())] } else { def.entries() };
558    let mut all: Vec<HostDef> = Vec::new();
559    let mut pre_all: Vec<HostDef> = Vec::new();
560    let mut post_all: Vec<HostDef> = Vec::new();
561    let mut values: HandlerMap = Vec::new();
562    let mut pre_values: HandlerMap = Vec::new();
563    let mut post_values: HandlerMap = Vec::new();
564    let mut visitors_map: HandlerMap = Vec::new();
565    let mut pre_visitors_map: HandlerMap = Vec::new();
566    let mut post_visitors_map: HandlerMap = Vec::new();
567    let mut i = 0;
568    while i < visitors.len() {
569        let (mut key, value) = visitors[i].clone();
570        i += 1;
571        if key.parse::<f64>().is_ok_and(|n| n.fract() == 0.0) {
572            match &value {
573                HostDef::Fn { name, .. } => key = name.clone(),
574                v if v.is_object() => {
575                    visitors.extend(v.entries());
576                    continue;
577                }
578                _ => {}
579            }
580        }
581        let invalid = |errors: &mut Vec<ErrorDescription>| errors.push(ErrorDescription::ignore(format!("doParse: visitor.{} is not a valid key name", key)));
582        if let Some(token) = EnumToken::value(&key) {
583            match &value {
584                HostDef::Fn { .. } => map_push(&mut values, MapKey::Token(token), value.clone()),
585                v if v.is_object() || matches!(v, HostDef::Null) => {
586                    let event = v.get("type").and_then(walker_event);
587                    if let (Some(event), Some(handler)) = (event.filter(|_| v.get("handler").is_some()), v.get("handler")) {
588                        if event & WalkerEvent::Enter != 0 {
589                            map_push(&mut pre_values, MapKey::Token(token), handler.clone());
590                        }
591                        if event & WalkerEvent::Leave != 0 {
592                            map_push(&mut post_values, MapKey::Token(token), handler.clone());
593                        }
594                    } else {
595                        visitors.extend(v.entries());
596                    }
597                }
598                _ => invalid(errors),
599            }
600        } else if let Some(&generic) = GENERIC_KEYS.iter().find(|k| **k == &*key) {
601            match &value {
602                HostDef::Fn { .. } => map_push(&mut visitors_map, MapKey::Name(generic), value.clone()),
603                v if v.is_object() => {
604                    let event = v.get("type").and_then(walker_event);
605                    if let (Some(event), Some(handler)) = (event.filter(|_| v.get("handler").is_some()), v.get("handler")) {
606                        if event & WalkerEvent::Enter != 0 {
607                            map_push(&mut pre_visitors_map, MapKey::Name(generic), handler.clone());
608                        }
609                        if event & WalkerEvent::Leave != 0 {
610                            map_push(&mut post_visitors_map, MapKey::Name(generic), handler.clone());
611                        }
612                    } else {
613                        map_push(&mut visitors_map, MapKey::Name(generic), value.clone());
614                    }
615                }
616                _ => invalid(errors),
617            }
618        } else if &*key == "All" || &*key == "visitor" {
619            match &value {
620                HostDef::Fn { .. } => set_add(&mut all, value.clone()),
621                v if v.is_object() => {
622                    let event = v.get("type").and_then(walker_event);
623                    if let (Some(event), Some(handler)) = (event.filter(|_| v.get("handler").is_some()), v.get("handler")) {
624                        if event & WalkerEvent::Enter != 0 {
625                            set_add(&mut pre_all, handler.clone());
626                        }
627                        if event & WalkerEvent::Leave != 0 {
628                            set_add(&mut post_all, handler.clone());
629                        }
630                    }
631                }
632                _ => {}
633            }
634        } else {
635            invalid(errors);
636        }
637    }
638    let include_tokens = !pre_values.is_empty() || !values.is_empty() || !post_values.is_empty() || !all.is_empty() || !pre_all.is_empty() || !post_all.is_empty();
639    let all_handlers: Vec<HandlerMap> = [pre_visitors_map, pre_values, visitors_map, values, post_visitors_map, post_values]
640        .into_iter()
641        .filter(|m| !m.is_empty())
642        .collect();
643    ParsedVisitors { all_handlers, include_tokens, all, pre_all, post_all }
644}
645
646/// convert a visitor result to node ids
647fn visitor_result(arena: &AstArena, host: &Rc<dyn Host>, replacement: &HostValue) -> Option<Vec<u32>> {
648    let one = |v: &HostValue| -> Option<u32> {
649        match v {
650            HostValue::Number(n) => Some(*n as u32),
651            HostValue::ForeignNode(handle, id) => {
652                let other = host.arena(*handle)?;
653                Some(arena.import(&other, *id, true))
654            }
655            HostValue::Plain(p) if p.as_object().is_some() => Some(arena.from_object(p)),
656            _ => None,
657        }
658    };
659    match replacement {
660        HostValue::Array(items) => items.iter().map(|i| if matches!(i, HostValue::Number(_)) { one(i) } else { one(i) }).collect(),
661        other => one(other).map(|id| vec![id]),
662    }
663}
664
665async fn apply_visitors(arena: &Rc<AstArena>, ast: u32, visitor: &HostDef, errors: &mut Vec<ErrorDescription>, host: &Rc<dyn Host>, is_sync: bool) -> Result<(), HostError> {
666    let a = &**arena;
667    let visitors = parse_visitors(visitor, errors);
668    let mut nodes: Vec<u32> = vec![ast];
669    let enqueue = |node: u32, nodes: &mut Vec<u32>| {
670        if a.flags.get(node) & EnumAstNodeStatus::HasChildren != 0 {
671            let mut child = a.last_child.get(node);
672            while child != 0 {
673                nodes.push(child);
674                child = a.previous_sibling.get(child);
675            }
676        }
677        if visitors.include_tokens && !matches!(a.data_types.get(node), EnumToken::RuleNodeType | EnumToken::KeyframesRuleNodeType) {
678            let values = a.sub_tokens(node);
679            nodes.extend(values.iter().rev());
680        }
681    };
682    while let Some(node) = nodes.pop() {
683        let node_type = a.data_types.get(node);
684        let mut handlers: Vec<u32> = Vec::new();
685        let push_fn = |handlers: &mut Vec<u32>, d: &HostDef| {
686            if let HostDef::Fn { id, .. } = d {
687                handlers.push(*id);
688            }
689        };
690        for h in &visitors.pre_all {
691            push_fn(&mut handlers, h);
692        }
693        let generic_key: Option<&'static str> = match node_type {
694            EnumToken::DeclarationNodeType => Some("Declaration"),
695            EnumToken::AtRuleNodeType => Some("AtRule"),
696            EnumToken::KeyframesAtRuleNodeType => Some("KeyframesAtRule"),
697            EnumToken::KeyframesRuleNodeType => Some("KeyframesRule"),
698            EnumToken::RuleNodeType => Some("Rule"),
699            _ => None,
700        };
701        let key_name: Option<String> = match node_type {
702            EnumToken::DeclarationNodeType | EnumToken::AtRuleNodeType => Some(camelize(&a.get_name(node))),
703            EnumToken::KeyframesAtRuleNodeType => Some(camelize(&a.get_value(node))),
704            _ => None,
705        };
706        for h in &visitors.all {
707            push_fn(&mut handlers, h);
708        }
709        let keyed = |handler: &HostDef| key_name.as_deref().and_then(|k| handler.get(k)).filter(|h| h.is_fn()).cloned();
710        for map in &visitors.all_handlers {
711            if let Some(generic) = generic_key {
712                if let Some((_, list)) = map.iter().find(|(k, _)| *k == MapKey::Name(generic)) {
713                    for handler in list {
714                        if handler.is_fn() {
715                            push_fn(&mut handlers, handler);
716                        } else if let Some(h) = keyed(handler) {
717                            push_fn(&mut handlers, &h);
718                        }
719                    }
720                }
721            }
722            if let Some((_, list)) = map.iter().find(|(k, _)| *k == MapKey::Token(node_type)) {
723                for handler in list {
724                    if handler.is_fn() {
725                        push_fn(&mut handlers, handler);
726                    } else if let HostDef::Array(items) = handler {
727                        for h in items {
728                            push_fn(&mut handlers, h);
729                        }
730                    } else if let Some(h) = handler.get("handler").filter(|h| h.is_fn()) {
731                        push_fn(&mut handlers, h);
732                    } else if let Some(h) = keyed(handler) {
733                        push_fn(&mut handlers, &h);
734                    }
735                }
736            }
737        }
738        for h in &visitors.post_all {
739            push_fn(&mut handlers, h);
740        }
741        let mut replacement = HostValue::Null;
742        let mut replaced: Option<Vec<u32>> = None;
743        if !handlers.is_empty() {
744            for callable in handlers {
745                let result = host.call(callable, Some(arena), vec![HostValue::Number(node as f64)]);
746                replacement = if is_sync { result? } else { await_host(result).await? };
747                if replacement.is_nullish() {
748                    continue;
749                }
750                if matches!(replacement, HostValue::Number(n) if n as u32 == node) {
751                    continue;
752                }
753                if matches!(replacement, HostValue::Array(_)) {
754                    break;
755                }
756            }
757            let same = matches!(replacement, HostValue::Number(n) if n as u32 == node);
758            if !replacement.is_nullish() && !same {
759                match visitor_result(a, host, &replacement) {
760                    Some(ids) if ids.len() == 1 && ids[0] == node && !matches!(replacement, HostValue::Array(_)) => {}
761                    Some(ids) => {
762                        if a.flags.get(node) & (EnumAstNodeStatus::HasChildren | EnumAstNodeStatus::HasValues) != 0 {
763                            a.replace_child(node, &ids);
764                        } else {
765                            a.replace_token(node, &ids);
766                        }
767                        replaced = Some(ids);
768                    }
769                    None => {
770                        errors.push(
771                            ErrorDescription::ignore("doParse: visitor must return node ids, objects or arrays of node ids and objects").with_node(node),
772                        );
773                    }
774                }
775            }
776        }
777        match replaced {
778            None => enqueue(node, &mut nodes),
779            Some(ids) => {
780                for &id in ids.iter().rev() {
781                    enqueue(id, &mut nodes);
782                }
783            }
784        }
785    }
786    Ok(())
787}
788
789// ---------------------------------------------------------------------------------------------------------------------
790// css modules
791// ---------------------------------------------------------------------------------------------------------------------
792
793thread_local! {
794    static SCOPED_NAMES: RefCell<HashMap<(String, String, String, u32, bool), Result<String, String>>> = RefCell::new(HashMap::default());
795    static SHORT_NAMES: RefCell<(u64, HashMap<(String, String, String, u32), String>)> = RefCell::new((0, HashMap::default()));
796}
797
798/// `getShortNameGenerator`: a short name per distinct arguments
799fn short_name(local: &str, file_path: &str, pattern: &str, hash_length: u32) -> String {
800    SHORT_NAMES.with(|s| {
801        let mut s = s.borrow_mut();
802        let key = (local.to_string(), file_path.to_string(), pattern.to_string(), hash_length);
803        if let Some(v) = s.1.get(&key) {
804            return v.clone();
805        }
806        let to36 = |mut n: u64| {
807            if n == 0 {
808                return "0".to_string();
809            }
810            let digits = b"0123456789abcdefghijklmnopqrstuvwxyz";
811            let mut out = Vec::new();
812            while n > 0 {
813                out.push(digits[(n % 36) as usize]);
814                n /= 36;
815            }
816            out.reverse();
817            String::from_utf8(out).unwrap()
818        };
819        let mut value = to36(s.0);
820        s.0 += 1;
821        while value.as_bytes()[0].is_ascii_digit() {
822            value = to36(s.0);
823            s.0 += 1;
824        }
825        s.1.insert(key, value.clone());
826        value
827    })
828}
829
830/// `generateScopedName()` (async: the sha hashes are allowed) and `generateSyncScopedName()`
831pub fn generate_scoped_name(local_name: &str, file_path: &str, pattern: &str, hash_length: u32, sync: bool) -> Result<String, String> {
832    let key = (local_name.to_string(), file_path.to_string(), pattern.to_string(), hash_length, sync);
833    if let Some(v) = SCOPED_NAMES.with(|c| c.borrow().get(&key).cloned()) {
834        return v;
835    }
836    let result = generate_scoped_name_uncached(local_name, file_path, pattern, hash_length, sync);
837    SCOPED_NAMES.with(|c| c.borrow_mut().insert(key, result.clone()));
838    result
839}
840
841fn sanitize(s: &str) -> String {
842    s.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' { c } else { '_' }).collect()
843}
844
845fn generate_scoped_name_uncached(local_name: &str, file_path: &str, pattern: &str, hash_length: u32, sync: bool) -> Result<String, String> {
846    let local_name = local_name.strip_prefix("--").unwrap_or(local_name);
847    // `/.*?(([^/]+)\/)?([^/\\]*?)(\.([^?/]+))?([?].*)?$/`
848    let (folder, file_base, ext) = split_file_path(file_path);
849    let folder = sanitize(&folder);
850    let path = sanitize(file_path);
851    let safe_local = sanitize(local_name);
852    let hash_string = format!("{}::{}", local_name, file_path);
853    let mut result = String::new();
854    let mut in_parens = 0;
855    let mut key = String::new();
856    let mut position = 0usize;
857    for c in pattern.chars() {
858        position += c.len_utf16();
859        if c == '[' {
860            in_parens += 1;
861            if in_parens != 1 {
862                return Err(format!("Unexpected character: '{} at position {}' in pattern '{}'", c, position - 1, pattern));
863            }
864            continue;
865        }
866        if c == ']' {
867            in_parens -= 1;
868            if in_parens != 0 {
869                return Err(format!("Unexpected character: '{}:{}'", c, position - 1));
870            }
871            let mut hash_algo: Option<String> = None;
872            let mut length: Option<String> = None;
873            if key.contains(':') {
874                let parts: Vec<String> = key.split(':').map(String::from).collect();
875                if parts.len() == 2 {
876                    key = parts[0].clone();
877                    length = Some(parts[1].clone());
878                    if key == "hash" && HASH_ALGORITHMS.contains(&parts[1].as_str()) {
879                        hash_algo = length.take();
880                        if sync && hash_algo.as_deref().is_some_and(|h| h.starts_with("sha")) {
881                            return Err(format!(
882                                "Unsupported hash algorithm: '{}'. Not supported by parseSync() or transformSync(). Use parse() or transform().",
883                                hash_algo.unwrap()
884                            ));
885                        }
886                    }
887                }
888                if parts.len() == 3 {
889                    key = parts[0].clone();
890                    hash_algo = Some(parts[1].clone());
891                    length = Some(parts[2].clone());
892                }
893                if let Some(l) = &length {
894                    let n = crate::utils::number::js_parse_number(l);
895                    if !(n.is_finite() && n.fract() == 0.0) {
896                        return Err(format!("Unsupported hash length: '{}'. expecting format [hash:length] or [hash:hash-algo:length]", l));
897                    }
898                }
899            }
900            let length_n: Option<usize> = length.as_deref().map(|l| crate::utils::number::js_parse_number(l) as usize);
901            // `length !== fileBase.length` compares a string with a number: always true when a length is given
902            let slice = length.is_some();
903            let take = |s: &str| -> String {
904                match length_n {
905                    Some(n) if slice => s.chars().take(n).collect(),
906                    _ => s.to_string(),
907                }
908            };
909            match key.as_str() {
910                "hash" => {
911                    let len = length_n.unwrap_or(hash_length as usize);
912                    let h = if sync { sync_hash(&hash_string, len, hash_algo.as_deref()) } else { hash(&hash_string, len, hash_algo.as_deref()) };
913                    result.push_str(&h?);
914                }
915                "name" => result.push_str(&take(&file_base)),
916                "local" => result.push_str(&if slice { take(&safe_local) } else { local_name.to_string() }),
917                "ext" => result.push_str(&take(&ext)),
918                "path" => result.push_str(&take(&path)),
919                "folder" => result.push_str(&take(&folder)),
920                _ => return Err(format!("Unsupported key: '{}'", key)),
921            }
922            key.clear();
923            continue;
924        }
925        if in_parens > 0 {
926            key.push(c);
927        } else {
928            result.push(c);
929        }
930    }
931    Ok(format!("{}{}", if result.starts_with(|c: char| c.is_ascii_digit()) { "_" } else { "" }, result))
932}
933
934/// folder, file base and extension of a path (the groups 2, 3 and 5 of the typescript regular expression)
935fn split_file_path(file_path: &str) -> (String, String, String) {
936    // drop the query (`([?].*)?$`)
937    let without_query = match file_path.find('?') {
938        Some(i) => &file_path[..i],
939        None => file_path,
940    };
941    let (dir, file) = match without_query.rfind('/') {
942        Some(i) => (&without_query[..i], &without_query[i + 1..]),
943        None => ("", without_query),
944    };
945    let folder = match dir.rfind('/') {
946        Some(i) => &dir[i + 1..],
947        None => dir,
948    };
949    // `([^/\\]*?)(\.([^?/]+))?`: the base stops at the first dot, the extension is the rest
950    let (base, ext) = match file.find('.') {
951        Some(i) if i + 1 < file.len() => (&file[..i], &file[i + 1..]),
952        _ => (file, ""),
953    };
954    (folder.to_string(), base.to_string(), ext.to_string())
955}
956
957/// the scoped name generator of the module settings
958#[derive(Clone)]
959enum Generator {
960    Default,
961    Sync,
962    Short,
963    Host(u32),
964}
965
966struct ModuleSettings {
967    hash_length: u32,
968    file_path: String,
969    scoped: u32,
970    naming: u32,
971    pattern: String,
972    generator: Generator,
973}
974
975impl ModuleSettings {
976    async fn scoped_name(&self, host: &Rc<dyn Host>, local: &str, file_path: &str) -> Result<String, HostError> {
977        if self.scoped & Scope::Global != 0 {
978            return Ok(local.to_string());
979        }
980        match self.generator {
981            Generator::Default => Ok(generate_scoped_name(local, file_path, &self.pattern, self.hash_length, false)?),
982            Generator::Sync => Ok(generate_scoped_name(local, file_path, &self.pattern, self.hash_length, true)?),
983            Generator::Short => Ok(short_name(local, file_path, &self.pattern, self.hash_length)),
984            Generator::Host(id) => {
985                let args = vec![
986                    HostValue::Str(Rc::from(local)),
987                    HostValue::Str(Rc::from(file_path)),
988                    HostValue::Str(Rc::from(self.pattern.as_str())),
989                    HostValue::Number(self.hash_length as f64),
990                ];
991                match await_host(host.call(id, None, args)).await? {
992                    HostValue::Str(s) => Ok(s.to_string()),
993                    other => Ok(format!("{:?}", other)),
994                }
995            }
996        }
997    }
998
999    /// `naming & (DashCaseOnly | CamelCaseOnly) ? getKeyName(value, naming) : value`
1000    fn name(&self, value: String) -> String {
1001        if self.naming & Case::DashCaseOnly != 0 || self.naming & Case::CamelCaseOnly != 0 {
1002            get_key_name(&value, self.naming)
1003        } else {
1004            value
1005        }
1006    }
1007}
1008
1009fn unquote(s: &str) -> String {
1010    let chars: Vec<char> = s.chars().collect();
1011    if chars.len() >= 2 {
1012        chars[1..chars.len() - 1].iter().collect()
1013    } else {
1014        String::new()
1015    }
1016}
1017
1018/// `[...new Set([...a.split(" "), ...b])].join(" ")`
1019fn merge_names(current: &str, more: &[String]) -> String {
1020    let mut out: Vec<String> = Vec::new();
1021    for n in current.split(' ').map(String::from).chain(more.iter().cloned()) {
1022        if !out.contains(&n) {
1023            out.push(n);
1024        }
1025    }
1026    out.join(" ")
1027}
1028
1029const ANIMATION_KEYWORDS: [&str; 27] = [
1030    "none", "infinite", "normal", "reverse", "alternate", "alternate-reverse", "forwards", "backwards", "both", "running", "paused",
1031    "linear", "ease", "ease-in", "ease-out", "ease-in-out", "step-start", "step-end", "jump-start", "jump-end", "jump-none",
1032    "jump-both", "start", "end", "inherit", "initial", "unset",
1033];
1034
1035const GRID_PROPERTIES: [&str; 9] = [
1036    "grid-column",
1037    "grid-column-start",
1038    "grid-column-end",
1039    "grid-row",
1040    "grid-row-start",
1041    "grid-row-end",
1042    "grid-template",
1043    "grid-template-columns",
1044    "grid-template-rows",
1045];
1046
1047async fn process_module(result: &mut ParseResult, options: &ParserOptions, host: &Rc<dyn Host>, is_sync: bool) -> Result<(), HostError> {
1048    let arena = result.arena.clone();
1049    let a = &*arena;
1050    let t = |x: u32| a.data_types.get(x);
1051    let s = |id: u32| a.resolve_string(id).to_string();
1052    let module_options = match &options.module {
1053        Some(ModuleOption::Options(o)) => Some(o.clone()),
1054        _ => None,
1055    };
1056    let mut settings = ModuleSettings {
1057        hash_length: module_options.as_ref().and_then(|o| o.hash_length).unwrap_or(5),
1058        file_path: module_options.as_ref().and_then(|o| o.file_path.clone()).unwrap_or_default(),
1059        scoped: Scope::Local,
1060        naming: module_options.as_ref().and_then(|o| o.naming).unwrap_or(Case::IgnoreCase),
1061        pattern: module_options.as_ref().and_then(|o| o.pattern.clone()).unwrap_or_default(),
1062        generator: match module_options.as_ref().and_then(|o| o.generate_scoped_name) {
1063            Some(id) => Generator::Host(id),
1064            None => {
1065                if is_sync {
1066                    Generator::Sync
1067                } else {
1068                    Generator::Default
1069                }
1070            }
1071        },
1072    };
1073    if let Some(scoped) = module_options.as_ref().and_then(|o| o.scoped) {
1074        settings.scoped = match scoped {
1075            ModuleScoped::Bool(b) => {
1076                if b {
1077                    Scope::Local
1078                } else {
1079                    Scope::Global
1080                }
1081            }
1082            ModuleScoped::Flags(f) => f,
1083        };
1084    }
1085    let pattern: Option<String> = match &options.module {
1086        Some(ModuleOption::Bool(_)) => None,
1087        _ => Some(settings.pattern.clone()),
1088    };
1089    let src = options.src.clone().unwrap_or_default();
1090    let cwd = options.cwd.clone().unwrap_or_default();
1091    let mut file_path = match &options.module {
1092        Some(ModuleOption::Bool(_)) => src.clone(),
1093        _ => module_options.as_ref().and_then(|o| o.file_path.clone()).unwrap_or_else(|| src.clone()),
1094    };
1095    file_path = if file_path.is_empty() { resolve(&src, &cwd, None).relative } else { resolve(&file_path, &dirname(&src), Some(&cwd)).relative };
1096    if let Some(ModuleOption::Flags(m)) = &options.module {
1097        let m = *m;
1098        if m & Case::CamelCase != 0 {
1099            settings.naming = Case::CamelCase;
1100        } else if m & Case::CamelCaseOnly != 0 {
1101            settings.naming = Case::CamelCaseOnly;
1102        } else if m & Case::DashCase != 0 {
1103            settings.naming = Case::DashCase;
1104        } else if m & Case::DashCaseOnly != 0 {
1105            settings.naming = Case::DashCaseOnly;
1106        }
1107        if m & Scope::Global != 0 {
1108            settings.scoped = Scope::Global;
1109        }
1110        if m & Scope::Pure != 0 {
1111            settings.scoped |= Scope::Pure;
1112        }
1113        if m & Scope::Shortest != 0 {
1114            settings.scoped |= Scope::Shortest;
1115        }
1116        if m & Scope::ICSS != 0 {
1117            settings.scoped |= Scope::ICSS;
1118        }
1119    }
1120    if settings.scoped & Scope::Shortest != 0 {
1121        settings.generator = if is_sync { Generator::Sync } else { Generator::Short };
1122    }
1123    settings.file_path = file_path.clone();
1124    settings.pattern = match pattern.filter(|p| !p.is_empty()) {
1125        Some(p) => p,
1126        None => {
1127            if file_path.is_empty() {
1128                "[local]_[hash]".into()
1129            } else {
1130                "[local]_[hash]_[name]".into()
1131            }
1132        }
1133    };
1134    let mut global: crate::utils::fx::HashSet<u32> = std::collections::HashSet::default();
1135    let mut processed: crate::utils::fx::HashSet<u32> = std::collections::HashSet::default();
1136    let mut import_mapping: Vec<(String, StrMap)> = Vec::new();
1137    let mut css_variables_map: HashMap<String, Vec<(String, u32)>> = HashMap::default();
1138    let mut imported_css_variables: Vec<(String, u32)> = Vec::new();
1139    let mut mapping = StrMap::default();
1140    let mut rev_mapping = StrMap::default();
1141    let ast = result.ast;
1142    let mut walker = NodeWalker::new(ast, None, false);
1143    while let Some(node) = walker.next(a) {
1144        let parent = a.parents.get(node);
1145        let node_type = t(node);
1146        if node_type == EnumToken::CssVariableImportTokenType {
1147            if is_sync {
1148                let (line, column) = options.source.as_ref().map_or((0, 0), |s| s.line_starts.borrow().get_offsets(a.get_span_start(node)));
1149                let file = options.source.as_ref().and_then(|s| s.file.clone()).map_or(String::new(), |f| f.to_string());
1150                return Err(HostError(format!(
1151                    "css variable import not supported by parseSync() or transformSync(). use parse() or transform() instead.\nat {}:{}:{}",
1152                    file, line, column
1153                )));
1154            }
1155            let string_token = a.find_token(node, |ar, x| ar.data_types.get(x) == EnumToken::StringTokenType).unwrap_or(0);
1156            let url = unquote(&s(a.string_value.get(string_token)));
1157            let resolved = resolve(&url, &dirname(&src), Some(&cwd));
1158            let (source, input) = load_source(host, options, &resolved.absolute, &resolved.relative, "").await?;
1159            let parse_info = create_parse_info(Some(&input), source.clone());
1160            let child_options = ParserOptions {
1161                source: Some(source),
1162                minify: Some(false),
1163                set_parent: Some(false),
1164                evaluate_mixins: Some(false),
1165                src: Some(resolved.relative.clone()),
1166                ..options.clone()
1167            };
1168            let root = do_parse(Tokenizer::new(parse_info), child_options, Some(arena.clone()), host.clone()).await?;
1169            css_variables_map.insert(s(a.name.get(node)), root.css_module_variables.unwrap_or_default());
1170            a.detach(node);
1171            continue;
1172        }
1173        if node_type == EnumToken::CssVariableDeclarationMapTokenType {
1174            let from_token = a.field_tokens(node, TokenField::L).into_iter().find(|&x| t(x) == EnumToken::IdenTokenType || is_ident_color(a, x)).unwrap_or(0);
1175            let from = s(a.string_value.get(from_token));
1176            match css_variables_map.get(&from) {
1177                None => {
1178                    result.errors.push(ErrorDescription::drop(format!("could not resolve @value import from '{}'", from)).with_node(node));
1179                }
1180                Some(vars) => {
1181                    for token in a.token_iter(node) {
1182                        if t(token) == EnumToken::IdenTokenType || is_ident_color(a, token) {
1183                            let name = s(a.string_value.get(token));
1184                            match vars.iter().find(|(k, _)| *k == name) {
1185                                None => {
1186                                    result.errors.push(ErrorDescription::drop(format!("value '{}' is not exported from '{}'", name, from)).with_node(node));
1187                                }
1188                                Some((_, v)) => {
1189                                    let v = *v;
1190                                    let list = result.css_module_variables.get_or_insert_with(Vec::new);
1191                                    set_pair(list, &name, v);
1192                                    set_pair(&mut imported_css_variables, &name, v);
1193                                }
1194                            }
1195                        }
1196                    }
1197                }
1198            }
1199            a.detach(node);
1200            continue;
1201        }
1202        if node_type == EnumToken::CssVariableTokenType {
1203            if parent != 0 && t(parent) == EnumToken::StyleSheetNodeType {
1204                let list = result.css_module_variables.get_or_insert_with(Vec::new);
1205                set_pair(list, &s(a.name.get(node)), node);
1206            }
1207            a.detach(node);
1208            continue;
1209        }
1210        if node_type == EnumToken::DeclarationNodeType {
1211            let name = s(a.name.get(node));
1212            if name.starts_with("--") {
1213                let value = settings.scoped_name(host, &name, &settings.file_path).await?;
1214                mapping.set(&name, format!("--{}", settings.name(value)));
1215                rev_mapping.set(&name, name.clone());
1216                a.name.set(node, a.intern_string(mapping.get(&name).unwrap()));
1217            }
1218            let name = s(a.name.get(node));
1219            if equals_ignore_case("composes", &name) {
1220                let compose_selectors: Vec<u32> = a.token_iter(node).filter(|&x| t(x) == EnumToken::ComposesSelectorNodeType).collect();
1221                let mut parent_rule = parent;
1222                while parent_rule != 0 && t(parent_rule) != EnumToken::RuleNodeType {
1223                    parent_rule = a.parents.get(parent_rule);
1224                }
1225                if compose_selectors.is_empty() {
1226                    result.errors.push(ErrorDescription::drop("composes is empty").with_node(node));
1227                    a.detach(node);
1228                    continue;
1229                }
1230                let resolved_src = resolve(&src, &cwd, None);
1231                for token in compose_selectors {
1232                    if !a.has_field(token, TokenField::R) {
1233                        for rule in a.field_tokens(token, TokenField::L) {
1234                            if matches!(t(rule), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType) {
1235                                continue;
1236                            }
1237                            let rv = s(a.string_value.get(rule));
1238                            if !mapping.has(&rv) {
1239                                let value = settings.scoped_name(host, &rv, &settings.file_path).await?;
1240                                let prefix = if t(rule) == EnumToken::DashedIdenTokenType { "--" } else { "" };
1241                                mapping.set(&rv, format!("{}{}", prefix, settings.name(value)));
1242                                let mapped = mapping.get(&rv).unwrap().to_string();
1243                                rev_mapping.set(&mapped, rv.clone());
1244                            }
1245                            if parent_rule != 0 {
1246                                for tk in a.token_iter(parent_rule) {
1247                                    if t(tk) == EnumToken::ClassSelectorTokenType {
1248                                        let val: String = s(a.string_value.get(tk)).chars().skip(1).collect();
1249                                        if let Some(key) = rev_mapping.get(&val).map(String::from) {
1250                                            let merged = merge_names(mapping.get(&key).unwrap_or(""), &[mapping.get(&rv).unwrap_or("").to_string()]);
1251                                            mapping.set(&key, merged);
1252                                        }
1253                                    }
1254                                }
1255                            }
1256                        }
1257                    } else if t(a.field(token, TokenField::R)) == EnumToken::StringTokenType {
1258                        if is_sync {
1259                            let (line, column) = options.source.as_ref().map_or((0, 0), |s| s.line_starts.borrow().get_offsets(a.get_span_start(node)));
1260                            let file = options.source.as_ref().and_then(|s| s.file.clone()).map_or(String::new(), |f| f.to_string());
1261                            return Err(HostError(format!(
1262                                "composes from file is not supported using parseSync() or transformSync(). Use parse() or transform() instead.\nat {}:{}:{}",
1263                                file, line, column
1264                            )));
1265                        }
1266                        let url = unquote(&s(a.string_value.get(a.field(token, TokenField::R))));
1267                        let resolved = resolve(&url, &dirname(&src), Some(&cwd));
1268                        let (source, input) = load_source(host, options, &resolved.absolute, &resolved.relative, "").await?;
1269                        let child_source = SourceFile::new(Rc::from(""), Vec::new(), Some(Rc::from(resolved.relative.as_str())));
1270                        let _ = source;
1271                        let parse_info = create_parse_info(Some(&input), child_source);
1272                        let child_options = ParserOptions {
1273                            minify: Some(false),
1274                            set_parent: Some(false),
1275                            evaluate_mixins: Some(false),
1276                            src: Some(resolved.relative.clone()),
1277                            ..options.clone()
1278                        };
1279                        let mut root = do_parse(Tokenizer::new(parse_info), child_options, Some(arena.clone()), host.clone()).await?;
1280                        let mut src_index = resolve(&resolved.absolute, &resolved_src.absolute, None).relative;
1281                        if !src_index.starts_with('/') && !src_index.starts_with("../") {
1282                            src_index = format!("./{}", src_index);
1283                        }
1284                        let mut root_mapping = root.mapping.take().unwrap_or_default();
1285                        let mut root_rev = root.rev_mapping.take().unwrap_or_default();
1286                        if !root_mapping.is_empty() && !import_mapping.iter().any(|(k, _)| *k == src_index) {
1287                            import_mapping.push((src_index.clone(), StrMap::default()));
1288                        } else if !root_mapping.is_empty() {
1289                            if let Some(entry) = import_mapping.iter_mut().find(|(k, _)| *k == src_index) {
1290                                entry.1 = StrMap::default();
1291                            }
1292                        }
1293                        if parent_rule != 0 {
1294                            for tk in a.token_iter(parent_rule) {
1295                                if t(tk) == EnumToken::ClassSelectorTokenType {
1296                                    let val: String = s(a.string_value.get(tk)).chars().skip(1).collect();
1297                                    if let Some(key) = rev_mapping.get(&val).map(String::from) {
1298                                        let mut values: Vec<String> = Vec::new();
1299                                        for iden in a.field_tokens(token, TokenField::L) {
1300                                            if !matches!(t(iden), EnumToken::IdenTokenType | EnumToken::DashedIdenTokenType) {
1301                                                continue;
1302                                            }
1303                                            let iv = s(a.string_value.get(iden));
1304                                            if !root_mapping.has(&iv) {
1305                                                let value = settings.scoped_name(host, &iv, &src_index).await?;
1306                                                root_mapping.set(&iv, settings.name(value));
1307                                                let mapped = root_mapping.get(&iv).unwrap().to_string();
1308                                                root_rev.set(&mapped, iv.clone());
1309                                            }
1310                                            let mapped = root_mapping.get(&iv).unwrap().to_string();
1311                                            match import_mapping.iter_mut().find(|(k, _)| *k == src_index) {
1312                                                Some(entry) => entry.1.set(&iv, mapped.clone()),
1313                                                // typescript: `importMapping[srcIndex][...]` throws when the entry is missing
1314                                                None => return Err(HostError("Cannot set properties of undefined".into())),
1315                                            }
1316                                            values.push(mapped);
1317                                        }
1318                                        let merged = merge_names(mapping.get(&key).unwrap_or(""), &values);
1319                                        mapping.set(&key, merged);
1320                                    }
1321                                }
1322                            }
1323                        }
1324                    } else if t(a.field(token, TokenField::R)) == EnumToken::IdenTokenType && parent_rule != 0 {
1325                        let from = a.field(token, TokenField::R);
1326                        if equals_ignore_case("global", &s(a.string_value.get(from))) {
1327                            for tk in a.token_iter(parent_rule) {
1328                                if t(tk) == EnumToken::ClassSelectorTokenType {
1329                                    let val: String = s(a.string_value.get(tk)).chars().skip(1).collect();
1330                                    if let Some(key) = rev_mapping.get(&val).map(String::from) {
1331                                        let composed: Vec<String> = a
1332                                            .field_tokens(token, TokenField::L)
1333                                            .into_iter()
1334                                            .filter(|&c| t(c) == EnumToken::IdenTokenType)
1335                                            .map(|c| s(a.string_value.get(c)))
1336                                            .collect();
1337                                        let merged = merge_names(mapping.get(&key).unwrap_or(""), &composed);
1338                                        mapping.set(&key, merged);
1339                                    }
1340                                }
1341                            }
1342                        } else {
1343                            result.errors.push(ErrorDescription::drop(format!("composes '{}' is not supported", s(a.string_value.get(from)))).with_node(node));
1344                        }
1345                    }
1346                }
1347                a.detach(node);
1348            }
1349            let name = s(a.name.get(node));
1350            if GRID_PROPERTIES.contains(&name.as_str()) {
1351                let mut values = ValueWalker::of_node(a, node, WalkerValueOptions::default(), false);
1352                while let Some(value) = values.next(a) {
1353                    if t(value) != EnumToken::IdenTokenType {
1354                        continue;
1355                    }
1356                    let mut iden = s(a.string_value.get(value));
1357                    let mut suffix = "";
1358                    if let Some(rest) = iden.strip_suffix("-start") {
1359                        suffix = "-start";
1360                        iden = rest.to_string();
1361                    } else if let Some(rest) = iden.strip_suffix("-end") {
1362                        suffix = "-end";
1363                        iden = rest.to_string();
1364                    }
1365                    if !mapping.has(&iden) {
1366                        let generated = settings.scoped_name(host, &iden, &settings.file_path).await?;
1367                        mapping.set(&iden, generated.clone());
1368                        rev_mapping.set(&generated, iden.clone());
1369                        if !suffix.is_empty() {
1370                            iden.push_str(suffix);
1371                            if !mapping.has(&iden) {
1372                                mapping.set(&iden, format!("{}{}", generated, suffix));
1373                                rev_mapping.set(&format!("{}{}", generated, suffix), iden.clone());
1374                            }
1375                        }
1376                    }
1377                    a.string_value.set(value, a.intern_string(mapping.get(&iden).unwrap_or("undefined")));
1378                }
1379            } else if name == "grid-template-areas" || name == "grid-template" {
1380                for token in a.token_iter(node) {
1381                    if t(token) == EnumToken::StringTokenType {
1382                        let str = s(a.string_value.get(token));
1383                        let tokens = parse_string(a, &unquote(&str));
1384                        let mut values = ValueWalker::of_tokens(&tokens, WalkerValueOptions::default(), false);
1385                        while let Some(value) = values.next(a) {
1386                            if matches!(t(value), EnumToken::IdenTokenType | EnumToken::DashedIdenTokenType) {
1387                                let v = s(a.string_value.get(value));
1388                                if let Some(m) = mapping.get(&v).map(String::from) {
1389                                    a.string_value.set(value, a.intern_string(&m));
1390                                } else {
1391                                    let generated = settings.scoped_name(host, &v, &settings.file_path).await?;
1392                                    mapping.set(&v, generated.clone());
1393                                    rev_mapping.set(&generated, v.clone());
1394                                    a.string_value.set(value, a.intern_string(&generated));
1395                                }
1396                            }
1397                        }
1398                        let first = str.chars().next().map(String::from).unwrap_or_default();
1399                        let last = str.chars().last().map(String::from).unwrap_or_default();
1400                        let rendered = format!("{}{}{}", first, render_tokens(a, &tokens, None), last);
1401                        a.string_value.set(token, a.intern_string(&rendered));
1402                    }
1403                }
1404            } else if name == "animation" || name == "animation-name" {
1405                let mut values = ValueWalker::of_node(a, node, WalkerValueOptions::default(), false);
1406                while let Some(value) = values.next(a) {
1407                    let v = s(a.string_value.get(value));
1408                    if t(value) == EnumToken::IdenTokenType && !ANIMATION_KEYWORDS.contains(&v.as_str()) {
1409                        if !mapping.has(&v) {
1410                            let generated = settings.scoped_name(host, &v, &settings.file_path).await?;
1411                            mapping.set(&v, generated.clone());
1412                            rev_mapping.set(&generated, v.clone());
1413                        }
1414                        a.string_value.set(value, a.intern_string(mapping.get(&v).unwrap()));
1415                    }
1416                }
1417            }
1418            let mut values = ValueWalker::of_node(a, node, WalkerValueOptions::default(), false);
1419            while let Some(value) = values.next(a) {
1420                if t(value) == EnumToken::DashedIdenTokenType {
1421                    if let Some(mapped) = mapping.get(&s(a.string_value.get(value))).map(String::from) {
1422                        a.string_value.set(value, a.intern_string(&mapped));
1423                    }
1424                } else if t(value) == EnumToken::IdenTokenType || is_ident_color(a, value) {
1425                    let v = s(a.string_value.get(value));
1426                    if let Some(&(_, var)) = imported_css_variables.iter().find(|(k, _)| *k == v) {
1427                        let copies: Vec<u32> = a.tokens(var).into_iter().map(|tk| a.clone_node_deep(tk, true, None)).collect();
1428                        a.replace_token(value, &copies);
1429                    }
1430                }
1431            }
1432        } else if node_type == EnumToken::RuleNodeType {
1433            let mut tokens = parse_string(a, &s(a.name.get(node)));
1434            let mut ignored = Vec::new();
1435            match_selector_syntax(a, &mut tokens, &mut ignored, options, true);
1436            trim_array(a, &mut tokens);
1437            a.set_token_list(node, &tokens);
1438            let mut has_id_or_class = false;
1439            let mut global_tokens: Vec<u32> = Vec::new();
1440            let mut values = ValueWalker::of_node(
1441                a,
1442                node,
1443                WalkerValueOptions {
1444                    fn_: Some(Box::new(|ar, value, _| {
1445                        let tv = ar.data_types.get(value);
1446                        if tv == EnumToken::PseudoClassTokenType || tv == EnumToken::PseudoElementTokenType {
1447                            let val = ar.resolve_string(ar.string_value.get(value)).to_lowercase();
1448                            if val == ":local" || val == ":global" {
1449                                let next = ar.next_sibling.get(value);
1450                                ar.detach(value);
1451                                if next != 0 && matches!(ar.data_types.get(next), EnumToken::WhitespaceTokenType | EnumToken::DescendantCombinatorTokenType) {
1452                                    ar.detach(next);
1453                                }
1454                            }
1455                        } else if tv == EnumToken::PseudoClassFuncTokenType {
1456                            let val = ar.resolve_string(ar.string_value.get(value)).to_lowercase();
1457                            if val == ":global" || val == ":local" {
1458                                let children = ar.tokens(value);
1459                                if val == ":global" {
1460                                    global_tokens.extend(children.iter().copied());
1461                                }
1462                                a.replace_child(value, &children);
1463                                return WalkerValueResult::Tokens(children);
1464                            }
1465                        }
1466                        WalkerValueResult::None
1467                    })),
1468                    ..Default::default()
1469                },
1470                false,
1471            );
1472            let mut visited: Vec<u32> = Vec::new();
1473            while let Some(value) = values.next(a) {
1474                visited.push(value);
1475            }
1476            drop(values);
1477            global.extend(global_tokens);
1478            for value in visited {
1479                if matches!(t(value), EnumToken::HashTokenType | EnumToken::ClassSelectorTokenType) {
1480                    has_id_or_class = true;
1481                }
1482                if !processed.insert(value) {
1483                    continue;
1484                }
1485                if matches!(t(value), EnumToken::PseudoClassTokenType | EnumToken::PseudoElementTokenType | EnumToken::PseudoClassFuncTokenType) {
1486                    continue;
1487                }
1488                if global.contains(&value) {
1489                    continue;
1490                }
1491                if t(value) == EnumToken::ClassSelectorTokenType {
1492                    let val: String = s(a.string_value.get(value)).chars().skip(1).collect();
1493                    if !mapping.has(&val) {
1494                        let generated = settings.scoped_name(host, &val, &settings.file_path).await?;
1495                        mapping.set(&val, settings.name(generated));
1496                        let mapped = mapping.get(&val).unwrap().to_string();
1497                        rev_mapping.set(&mapped, val.clone());
1498                    }
1499                    a.string_value.set(value, a.intern_string(&format!(".{}", mapping.get(&val).unwrap())));
1500                }
1501            }
1502            if settings.scoped & Scope::Pure != 0 && !has_id_or_class {
1503                let (line, column) = options.source.as_ref().map_or((0, 0), |s| s.line_starts.borrow().get_offsets(a.get_span_start(node)));
1504                return Err(HostError(format!("pure module: No id or class found in selector '{}' at '{}:{}'", s(a.name.get(node)), line, column)));
1505            }
1506            let selector: String = a.tokens(node).iter().map(|&tk| render_value_default(a, tk)).collect();
1507            a.name.set(node, a.intern_string(&selector));
1508        } else if node_type == EnumToken::AtRuleNodeType || node_type == EnumToken::KeyframesAtRuleNodeType {
1509            let val = s(a.name.get(node)).to_lowercase();
1510            if a.first_token.get(node) == 0 {
1511                let tokens = parse_string(a, &s(a.string_value.get(node)));
1512                a.set_token_list(node, &tokens);
1513            }
1514            if val == "property" || val == "keyframes" {
1515                let prefix = if val == "property" { "--" } else { "" };
1516                for value in a.tokens(node) {
1517                    let matches_type = (prefix == "--" && t(value) == EnumToken::DashedIdenTokenType) || (prefix.is_empty() && t(value) == EnumToken::IdenTokenType);
1518                    if matches_type {
1519                        let v = s(a.string_value.get(value));
1520                        if !mapping.has(&v) {
1521                            let generated = settings.scoped_name(host, &v, &settings.file_path).await?;
1522                            mapping.set(&v, format!("{}{}", prefix, settings.name(generated)));
1523                            let mapped = mapping.get(&v).unwrap().to_string();
1524                            rev_mapping.set(&mapped, v.clone());
1525                        }
1526                        a.string_value.set(value, a.intern_string(mapping.get(&v).unwrap()));
1527                    }
1528                }
1529                let rendered = render_tokens(a, &a.tokens(node), None);
1530                a.string_value.set(node, a.intern_string(&rendered));
1531            }
1532        }
1533    }
1534    if settings.naming & Case::IgnoreCase == 0 {
1535        if is_sync {
1536            // typescript (`doParseSync()`): the mapping is reset before it is iterated
1537            rev_mapping = StrMap::default();
1538            mapping = StrMap::default();
1539        } else {
1540            let mut renamed = StrMap::default();
1541            rev_mapping = StrMap::default();
1542            for (key, value) in mapping.entries() {
1543                let key_name = get_key_name(key, settings.naming);
1544                renamed.set(&key_name, value.clone());
1545                rev_mapping.set(value, key_name);
1546            }
1547            mapping = renamed;
1548        }
1549    }
1550    result.mapping = Some(mapping);
1551    result.rev_mapping = Some(rev_mapping);
1552    if settings.scoped & Scope::ICSS != 0 && !import_mapping.is_empty() {
1553        result.import_mapping = Some(import_mapping);
1554    }
1555    Ok(())
1556}
1557
1558fn set_pair(list: &mut Vec<(String, u32)>, key: &str, value: u32) {
1559    match list.iter_mut().find(|(k, _)| k == key) {
1560        Some(entry) => entry.1 = value,
1561        None => list.push((key.to_string(), value)),
1562    }
1563}