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