Skip to main content

rust_css_parser/ast/
minify.rs

1//! Port of `src/ast/minify.ts`.
2//!
3//! Selector parts are strings (`Vec<String>` per selector), lengths are utf-16 lengths like the javascript strings.
4//! The typescript minification context (`{ [key]: any }`) is [`MinifyContext`]; the render size cache stored on the
5//! options (`options.cache`) lives in the context: both belong to one `minify()` call.
6
7use super::arena::{AstArena, OptimizedSelector, RawSelector, RawSelectorTokens, TokenValue};
8use super::features::r#type::FeatureWalkMode;
9use super::features::{register_features, FeatureResult, SharedFeature};
10use super::mixins::utils::move_result;
11use super::strings::StringFlag;
12use super::types::{EnumAstNodeStatus, EnumToken};
13use super::walk::{ValueWalker, WalkerValueOptions};
14use crate::options::ParserOptions;
15use crate::parser::parse::parse_string;
16use crate::parser::utils::eq::eq_token;
17use crate::parser::utils::text::equals_ignore_case;
18use crate::printer::render::{render_value_default, NodeRenderer};
19use crate::syntax::constants::COMBINATORS;
20use crate::syntax::syntax::{is_function, is_ident, is_white_space};
21use crate::types::ErrorDescription;
22use crate::validation::match_::trim_array;
23use std::any::Any;
24use std::cell::RefCell;
25use crate::utils::fx::{HashMap, HashSet};
26use std::rc::Rc;
27
28/// state of a minification (`context`)
29#[derive(Default)]
30pub struct MinifyContext {
31    /// the minified nodes
32    pub nodes: HashSet<u32>,
33    /// rendered sizes of the nodes (`options.cache`)
34    pub cache: Option<HashMap<u32, usize>>,
35    /// renderer of the rule sizes
36    pub renderer: Option<NodeRenderer>,
37    /// state of the features (`context.declarations`, `context.lookup`, ...), by key
38    pub data: HashMap<&'static str, Box<dyn Any>>,
39}
40
41impl MinifyContext {
42    /// a feature state, created on demand (`context.key ??= value`)
43    pub fn get_or_insert_with<T: 'static>(&mut self, key: &'static str, f: impl FnOnce() -> T) -> &mut T {
44        self.data.entry(key).or_insert_with(|| Box::new(f())).downcast_mut::<T>().expect("context type")
45    }
46
47    pub fn get_mut<T: 'static>(&mut self, key: &'static str) -> Option<&mut T> {
48        self.data.get_mut(key).and_then(|v| v.downcast_mut::<T>())
49    }
50}
51
52/// options of a minification: the parser options and the registered features (`MinifyFeatureOptions`)
53pub struct MinifyOptions {
54    pub options: ParserOptions,
55    pub features: Vec<SharedFeature>,
56}
57
58/// `["(", "["].concat(combinators)`
59fn not_ending_with(c: char) -> bool {
60    c == '(' || c == '[' || COMBINATORS.iter().any(|x| x.len() == 1 && x.starts_with(c))
61}
62
63fn is_combinator(s: &str) -> bool {
64    COMBINATORS.contains(&s)
65}
66
67/// utf-16 length of a string (`str.length`)
68fn js_len(s: &str) -> usize {
69    s.encode_utf16().count()
70}
71
72/// first character as a string (`str.charAt(0)`)
73fn char_at0(s: &str) -> String {
74    s.chars().next().map(String::from).unwrap_or_default()
75}
76
77/// apply the minification rules to the ast tree
78pub fn minify(arena: &AstArena, ast: u32, options: &ParserOptions, recursive: bool, errors: Option<&mut Vec<ErrorDescription>>, nesting_content: bool) -> u32 {
79    let mut context = MinifyContext::default();
80    minify_with(arena, ast, options, None, recursive, errors, nesting_content, &mut context)
81}
82
83/// [`minify`] with registered features and a context
84#[allow(clippy::too_many_arguments)]
85pub fn minify_with(
86    arena: &AstArena,
87    ast: u32,
88    options: &ParserOptions,
89    features: Option<Vec<SharedFeature>>,
90    recursive: bool,
91    mut errors: Option<&mut Vec<ErrorDescription>>,
92    nesting_content: bool,
93    context: &mut MinifyContext,
94) -> u32 {
95    let mut preprocess = false;
96    let mut postprocess = false;
97    // `let { sourcemap, module, ...options2 } = options`
98    let mut options2 = ParserOptions { sourcemap: None, module: None, ..options.clone() };
99    let features = match features {
100        Some(features) => features,
101        None => {
102            options2.remove_duplicate_declarations.get_or_insert(crate::options::RemoveDuplicateDeclarations::Bool(true));
103            options2.compute_shorthand.get_or_insert(true);
104            options2.compute_calc_expression.get_or_insert(true);
105            options2.remove_prefix.get_or_insert(false);
106            let mut features = Vec::new();
107            register_features(&options2, &mut features);
108            // stable sort, like the typescript sort
109            features.sort_by_key(|f| f.borrow().ordering());
110            features
111        }
112    };
113    for feature in &features {
114        let mode = feature.borrow().process_mode();
115        if mode & FeatureWalkMode::Pre != 0 {
116            preprocess = true;
117        }
118        if mode & FeatureWalkMode::Post != 0 {
119            postprocess = true;
120        }
121    }
122    let run_features = |mode: u32, context: &mut MinifyContext| {
123        // breadth first traversal
124        let mut queue: Vec<u32> = vec![ast];
125        let mut k = 0;
126        while k < queue.len() {
127            let node = queue[k];
128            k += 1;
129            let typ = arena.data_types.get(node);
130            if typ == EnumToken::CommentTokenType || typ == EnumToken::CDOCOMMTokenType {
131                continue;
132            }
133            let mut replacement = FeatureResult::Node(node);
134            for feature in &features {
135                let mut f = feature.borrow_mut();
136                if f.process_mode() & mode == 0 || f.accept().is_some_and(|a| !a.contains(&typ)) {
137                    continue;
138                }
139                let current = match replacement {
140                    FeatureResult::Nodes(_) => break,
141                    FeatureResult::Node(n) => n,
142                    FeatureResult::None => 0,
143                };
144                let parent = if arena.parents.get(node) == 0 { ast } else { arena.parents.get(node) };
145                match f.run(arena, current, &options2, parent, context, mode) {
146                    FeatureResult::None => {}
147                    result => replacement = result,
148                }
149            }
150            match &replacement {
151                FeatureResult::Nodes(nodes) if !nodes.is_empty() && arena.parents.get(node) != 0 => arena.replace_child(node, nodes),
152                FeatureResult::Node(n) if *n != node && arena.parents.get(node) != 0 => arena.replace_child(node, &[*n]),
153                _ => {}
154            }
155            if let FeatureResult::Node(n) = replacement {
156                if arena.flags.get(n) & EnumAstNodeStatus::HasChildren != 0 {
157                    let mut child = arena.first_child.get(n);
158                    while child != 0 {
159                        queue.push(child);
160                        child = arena.next_sibling.get(child);
161                    }
162                }
163            }
164        }
165        for feature in &features {
166            let mut f = feature.borrow_mut();
167            if f.process_mode() & mode != 0 && f.has_cleanup() {
168                f.cleanup(arena, ast, &options2, context, mode);
169            }
170        }
171    };
172    if preprocess {
173        run_features(FeatureWalkMode::Pre, context);
174    }
175    do_minify(arena, ast, &options2, recursive, errors.as_deref_mut(), nesting_content, context);
176    if postprocess {
177        run_features(FeatureWalkMode::Post, context);
178    }
179    ast
180}
181
182/// `@apply --mixin()` is equivalent to `@apply --mixin` (https://drafts.csswg.org/css-mixins-1/#apply-rule)
183fn minify_apply_prelude(arena: &AstArena, node: u32) {
184    let t = |x: u32| arena.data_types.get(x);
185    let mut reference = arena.first_token.get(node);
186    while reference != 0 && matches!(t(reference), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType) {
187        reference = arena.next_sibling.get(reference);
188    }
189    if reference == 0 || t(reference) != EnumToken::CustomFunctionTokenType {
190        return;
191    }
192    // the comments and the whitespace are ignored: `@apply --mixin(/* comment */)` has no argument
193    let mut token = arena.first_token.get(reference);
194    while token != 0 {
195        if !matches!(t(token), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType) {
196            return;
197        }
198        token = arena.next_sibling.get(token);
199    }
200    let name = arena.resolve_string(arena.string_value.get(reference));
201    let token = arena.create_token(EnumToken::DashedIdenTokenType, TokenValue::Str(&name), None);
202    arena.set_token_list(node, &[token]);
203    arena.string_value.set(node, arena.intern_string(&name));
204}
205
206/// minify the prelude of a media rule: the sections after `all` are dropped
207fn minify_at_rule_media(arena: &AstArena, tokens: &mut Vec<u32>) {
208    let mut parts: Vec<Vec<u32>> = vec![Vec::new()];
209    for &token in tokens.iter() {
210        if arena.data_types.get(token) == EnumToken::CommaTokenType {
211            parts.push(Vec::new());
212        } else {
213            parts.last_mut().unwrap().push(token);
214        }
215    }
216    let mut keys: Vec<String> = Vec::new();
217    for mut values in parts {
218        if keys.iter().any(|k| k == "all") {
219            break;
220        }
221        // `transformAtRuleMediaPrelude()`: the values are trimmed, there is no update
222        trim_array(arena, &mut values);
223        if values.is_empty() {
224            continue;
225        }
226        let key: String = values.iter().map(|&t| render_value_default(arena, t)).collect();
227        if !keys.contains(&key) {
228            keys.push(key);
229        }
230    }
231    if keys.iter().any(|k| k == "all") {
232        tokens.clear();
233    }
234}
235
236/// render the tokens of a prelude without the comments
237fn render_prelude(arena: &AstArena, arr: &[u32]) -> String {
238    let t = |i: usize| arr.get(i).map_or(0, |&x| arena.data_types.get(x));
239    let mut acc = String::new();
240    for (index, &curr) in arr.iter().enumerate() {
241        let skip = t(index) == EnumToken::CommentTokenType
242            || (t(index) == EnumToken::WhitespaceTokenType
243                && t(index + 1) == EnumToken::CommentTokenType
244                && (index + 3 < arr.len() || t(index + 2) == EnumToken::WhitespaceTokenType));
245        if !skip {
246            acc.push_str(&render_value_default(arena, curr));
247        }
248    }
249    acc
250}
251
252/// reduce selectors: the leading `& ` is removed (the selector is modified in place)
253fn reduce(acc: &mut Vec<String>, curr: &mut Vec<String>) {
254    if curr.first().map(String::as_str) == Some("&") && curr.get(1).map(String::as_str) == Some(" ") {
255        let third = curr.get(2).map(String::as_str).unwrap_or("");
256        if !is_ident(third) && !is_function(third) {
257            curr.drain(0..2);
258        }
259    }
260    acc.push(curr.concat());
261}
262
263/// `selectors.reduce(reducer, []).join(",")`
264fn reduce_join(selectors: &mut [Vec<String>]) -> String {
265    let mut acc = Vec::new();
266    for curr in selectors.iter_mut() {
267        reduce(&mut acc, curr);
268    }
269    acc.join(",")
270}
271
272/// true if the selector part is a simple selector that can be moved into `:is()`
273fn is_compound_part(part: &str) -> bool {
274    let lower = part.to_lowercase();
275    !part.trim().is_empty()
276        && part != "&"
277        && !is_combinator(part)
278        && !part.starts_with("::")
279        && !matches!(lower.as_str(), ":before" | ":after" | ":first-line" | ":first-letter")
280}
281
282/// factor the common prefix of the selectors of a rule into `:is()`. `None` when the selectors cannot be factored
283fn factor_selector(optimized: &OptimizedSelector) -> Option<String> {
284    let prefix = &optimized.optimized;
285    if prefix.is_empty() || !prefix.iter().all(|part| part == " " || is_compound_part(part) || is_combinator(part)) {
286        return None;
287    }
288    let mut combinator: Option<String> = None;
289    let mut members: Vec<String> = Vec::new();
290    for selector in &optimized.selector {
291        let parts: &[String] = if selector.first().map(String::as_str) == Some("&") { &selector[1..] } else { selector };
292        // the parts that follow the prefix. the whitespace around the combinators is removed
293        let suffix: Vec<String> = parts
294            .iter()
295            .enumerate()
296            .filter(|(index, part)| {
297                !part.trim().is_empty()
298                    || (!(*index > 0 && is_combinator(&parts[index - 1])) && !parts.get(index + 1).is_some_and(|p| is_combinator(p)))
299            })
300            .map(|(_, p)| p.clone())
301            .collect();
302        // the prefix itself
303        if suffix.is_empty() {
304            if combinator.as_deref().is_some_and(|c| !c.is_empty()) {
305                return None;
306            }
307            combinator = Some(String::new());
308            members.push("*".into());
309            continue;
310        }
311        // the combinator that joins the suffix to the prefix. "" for a compound selector
312        let current: String = if suffix[0].trim().is_empty() {
313            " ".into()
314        } else if is_combinator(&suffix[0]) {
315            suffix[0].clone()
316        } else {
317            String::new()
318        };
319        let compound: &[String] = if current.is_empty() { &suffix } else { &suffix[1..] };
320        if combinator.as_ref().is_some_and(|c| *c != current) || current == "|" || compound.is_empty() || !compound.iter().all(|p| is_compound_part(p)) {
321            return None;
322        }
323        combinator = Some(current);
324        members.push(compound.concat());
325    }
326    Some(format!("{}{}:is({})", prefix.concat(), combinator.unwrap_or_default(), members.join(",")))
327}
328
329fn optimized_of(arena: &AstArena, node: u32) -> Option<Rc<RefCell<OptimizedSelector>>> {
330    arena.optimized.borrow().get(&node).cloned()
331}
332
333fn set_selector(arena: &AstArena, node: u32, sel: &str) {
334    arena.name.set(node, arena.intern_string(sel));
335}
336
337/// the selector of `optimized.selector` joined with the optimized prefix: `sel1` is the `:is()` form
338fn reducible_selector(arena: &AstArena, node: u32, optimized: &Rc<RefCell<OptimizedSelector>>, nesting_content: bool) {
339    let mut o = optimized.borrow_mut();
340    if o.optimized.len() == 1 {
341        let prefix = o.optimized[0].clone();
342        let sel1 = format!("{}:is({})", prefix, reduce_join(&mut o.selector));
343        let sel2 = o.selector.iter().map(|curr| format!("{}{}", prefix, curr.concat())).collect::<Vec<_>>().join(",");
344        set_selector(arena, node, if js_len(&sel1) < js_len(&sel2) { &sel1 } else { &sel2 });
345        arena.set_token_list(node, &[]);
346    } else if o.optimized.is_empty() {
347        // `/^[a-zA-Z]/.test(curr[0])`: `undefined` is tested as "undefined"
348        let test_ident = |s: Option<&String>| s.map_or(true, |s| s.chars().next().is_some_and(|c| c.is_ascii_alphabetic()));
349        let sel = o
350            .selector
351            .iter()
352            .map(|curr| format!("{}{}", if nesting_content && test_ident(curr.first()) { "& " } else { "" }, curr.concat()))
353            .collect::<Vec<_>>()
354            .join(",");
355        set_selector(arena, node, &sel);
356        arena.set_token_list(node, &[]);
357    }
358}
359
360/// apply the minification rules to the ast tree
361#[allow(clippy::too_many_arguments)]
362fn do_minify(
363    arena: &AstArena,
364    ast: u32,
365    options: &ParserOptions,
366    recursive: bool,
367    mut errors: Option<&mut Vec<ErrorDescription>>,
368    nesting_content: bool,
369    context: &mut MinifyContext,
370) -> u32 {
371    if context.nodes.contains(&ast) {
372        return ast;
373    }
374    context.nodes.insert(ast);
375    if arena.flags.get(ast) & EnumAstNodeStatus::HasChildren == 0 || arena.first_child.get(ast) == 0 {
376        return ast;
377    }
378    let t = |x: u32| arena.data_types.get(x);
379    let nesting_content = nesting_content || (options.nesting_rules == Some(true) && t(ast) == EnumToken::RuleNodeType);
380    let opt = |x: u32| if x == 0 { None } else { Some(x) };
381    // the children list is modified while it is visited: every branch sets the next child to visit
382    let mut cursor = arena.first_child.get(ast);
383    let mut previous: Option<u32> = None;
384    let mut node: Option<u32> = None;
385    // the node located `count` positions before a child of ast (the end of the list when 0)
386    let before = |child: u32, count: i32| -> Option<u32> {
387        let mut result = if child == 0 { arena.last_child.get(ast) } else { arena.previous_sibling.get(child) };
388        let mut count = count;
389        loop {
390            count -= 1;
391            if !(count > 0 && result != 0) {
392                break;
393            }
394            result = arena.previous_sibling.get(result);
395        }
396        opt(result)
397    };
398    macro_rules! recurse {
399        ($n:expr) => {
400            do_minify(arena, $n, options, recursive, errors.as_deref_mut(), nesting_content, context)
401        };
402    }
403    while cursor != 0 {
404        if t(cursor) == EnumToken::CommentNodeType {
405            cursor = arena.next_sibling.get(cursor);
406            continue;
407        }
408        while let Some(p) = previous {
409            if t(p) != EnumToken::CommentNodeType {
410                break;
411            }
412            previous = opt(arena.previous_sibling.get(p));
413        }
414        let mut n = cursor;
415        node = Some(n);
416        let mut node_type = t(n);
417        let mut previous_type = previous.map(t);
418        if node_type == EnumToken::AtRuleNodeType {
419            let nam = arena.resolve_string(arena.name.get(n));
420            if &*nam == "font-face" {
421                cursor = arena.next_sibling.get(n);
422                continue;
423            }
424            // there is no early return: the result that precedes the conditional rules is moved after them
425            if equals_ignore_case(&nam, "function") {
426                move_result(arena, n);
427            }
428        }
429        if node_type == EnumToken::KeyframesAtRuleNodeType {
430            if let Some(p) = previous {
431                if previous_type == Some(EnumToken::KeyframesAtRuleNodeType)
432                    && arena.name.get(n) == arena.name.get(p)
433                    && arena.string_value.get(n) == arena.string_value.get(p)
434                {
435                    // the previous keyframes are dropped, the node is visited again
436                    let previous_node = arena.previous_sibling.get(p);
437                    cursor = arena.next_sibling.get(p);
438                    arena.detach(p);
439                    previous = opt(previous_node);
440                    continue;
441                }
442            }
443        } else if node_type == EnumToken::KeyframesRuleNodeType {
444            if let Some(p) = previous {
445                if previous_type == Some(EnumToken::KeyframesRuleNodeType) && arena.name.get(n) == arena.name.get(p) {
446                    // https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules/@keyframes#resolving_duplicates
447                    arena.move_children(n, p, 0);
448                    if let Some(cache) = context.cache.as_mut() {
449                        cache.remove(&p);
450                    }
451                    arena.detach(n);
452                    cursor = arena.next_sibling.get(p);
453                    continue;
454                }
455            }
456            let mut k = arena.first_child.get(n);
457            while k != 0 {
458                let next = arena.next_sibling.get(k);
459                if t(k) == EnumToken::DeclarationNodeType {
460                    let mut l = arena.last_token.get(k);
461                    while l != 0 {
462                        if t(l) == EnumToken::ImportantTokenType {
463                            arena.detach(k);
464                            break;
465                        }
466                        if matches!(t(l), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType) {
467                            l = arena.previous_sibling.get(l);
468                            continue;
469                        }
470                        break;
471                    }
472                }
473                k = next;
474            }
475        } else if node_type == EnumToken::AtRuleNodeType {
476            let nam = arena.resolve_string(arena.name.get(n));
477            let tokens: Option<Vec<u32>> = if arena.first_token.get(n) == 0 { None } else { Some(arena.tokens(n)) };
478            if nam == "apply" {
479                minify_apply_prelude(arena, n);
480            } else if nam == "media" {
481                if let Some(tokens) = &tokens {
482                    let mut slice = tokens.clone();
483                    minify_at_rule_media(arena, &mut slice);
484                    if slice.len() != tokens.len() {
485                        arena.set_token_list(n, &slice);
486                        arena.string_value.set(n, arena.intern_string(&render_prelude(arena, &slice)));
487                    }
488                }
489                let value = arena.resolve_string(arena.string_value.get(n));
490                if &*value == "all" || value.is_empty() {
491                    // the node is replaced by its children
492                    cursor = match arena.first_child.get(n) {
493                        0 => arena.next_sibling.get(n),
494                        c => c,
495                    };
496                    arena.move_children(n, ast, n);
497                    arena.detach(n);
498                    continue;
499                }
500            } else if nam == "import" && tokens.is_some() {
501                let mut tokens = tokens.unwrap();
502                let l = tokens
503                    .iter()
504                    .position(|&token| {
505                        matches!(t(token), EnumToken::ParensTokenType | EnumToken::MediaQueryConditionTokenType)
506                            || (t(token) == EnumToken::IdenTokenType && !arena.string_equals(arena.string_value.get(token), "layer"))
507                    })
508                    .unwrap_or(tokens.len());
509                if l < tokens.len() {
510                    let mut slice: Vec<u32> = tokens[l..].to_vec();
511                    minify_at_rule_media(arena, &mut slice);
512                    tokens.splice(l.., slice);
513                    arena.set_token_list(n, &tokens);
514                    trim_array(arena, &mut tokens);
515                    arena.string_value.set(n, arena.intern_string(&render_prelude(arena, &tokens)));
516                }
517            } else if t(ast) == node_type && arena.name.get(ast) == arena.name.get(n) && arena.string_value.get(ast) == arena.string_value.get(n) {
518                // the node is replaced by its children
519                cursor = match arena.first_child.get(n) {
520                    0 => arena.next_sibling.get(n),
521                    c => c,
522                };
523                arena.move_children(n, ast, n);
524                arena.detach(n);
525                continue;
526            }
527            if let Some(p) = previous {
528                if previous_type == Some(EnumToken::AtRuleNodeType)
529                    && nam != "font-face"
530                    && arena.name.get(p) == arena.name.get(n)
531                    && arena.string_value.get(p) == arena.string_value.get(n)
532                {
533                    if arena.flags.get(n) & EnumAstNodeStatus::HasChildren != 0 {
534                        arena.move_children(n, p, 0);
535                        if let Some(cache) = context.cache.as_mut() {
536                            cache.remove(&p);
537                        }
538                        if !has_declaration(arena, p) {
539                            context.nodes.remove(&p);
540                            recurse!(p);
541                        }
542                    }
543                    cursor = arena.next_sibling.get(n);
544                    arena.detach(n);
545                    continue;
546                }
547            }
548            if arena.flags.get(n) & EnumAstNodeStatus::HasChildren != 0 {
549                recurse!(n);
550            }
551            previous = Some(n);
552            cursor = arena.next_sibling.get(n);
553            continue;
554        } else if node_type == EnumToken::RuleNodeType {
555            // a single selector that does not end with a combinator is not reduced (see is_simple_selector())
556            if !is_simple_selector(arena, arena.name.get(n)) {
557                reduce_rule_selector(arena, n);
558            }
559            let mut wrapper: Option<u32> = None;
560            if options.nesting_rules == Some(true) {
561                // the rules that apply a mixin are not merged
562                if let Some(p) = previous {
563                    if previous_type == Some(EnumToken::RuleNodeType) && !has_at_rule_statement(arena, p) && !has_at_rule_statement(arena, n) {
564                        if !is_simple_selector(arena, arena.name.get(p)) {
565                            reduce_rule_selector(arena, p);
566                        }
567                        // the selectors are split when their first parts are equal: they do not match otherwise
568                        if may_match_selectors(arena, p, n) {
569                            if let Some(m) = match_selectors_of(arena, p, n) {
570                                wrapper = Some(wrap_nodes(arena, p, n, m));
571                            }
572                        }
573                    }
574                }
575                let optimized = optimized_of(arena, n);
576                if let Some(mut w) = wrapper {
577                    // wrap the following rules that match the wrapper selector
578                    let mut next_node = arena.next_sibling.get(w);
579                    while next_node != 0 && t(next_node) == EnumToken::RuleNodeType && !has_at_rule_statement(arena, next_node) {
580                        if !is_simple_selector(arena, arena.name.get(next_node)) {
581                            reduce_rule_selector(arena, next_node);
582                        }
583                        // the selector is split when its first part matches the wrapper selector
584                        let m = if may_match_selectors(arena, w, next_node) { match_selectors_of(arena, w, next_node) } else { None };
585                        let Some(m) = m else {
586                            break;
587                        };
588                        w = wrap_nodes(arena, w, next_node, m);
589                        next_node = arena.next_sibling.get(w);
590                    }
591                    previous = Some(w);
592                    cursor = arena.next_sibling.get(w);
593                    recurse!(w);
594                    continue;
595                } else if let Some(optimized) = optimized.as_ref().filter(|o| o.borrow().match_ && o.borrow().selector.len() > 1) {
596                    let w = arena.clone_node(n);
597                    arena.optimized.borrow_mut().insert(w, optimized.clone());
598                    let first = optimized.borrow().optimized[0].clone();
599                    set_selector(arena, w, &first);
600                    arena.raw.borrow_mut().insert(w, Rc::<RawSelector>::new(RawSelector::from(vec![vec![first]])));
601                    arena.set_token_list(w, &[]);
602                    let (sel, raw) = {
603                        let mut o = optimized.borrow_mut();
604                        let sel = reduce_join(&mut o.selector);
605                        (sel, o.selector.clone())
606                    };
607                    set_selector(arena, n, &sel);
608                    arena.raw.borrow_mut().insert(n, Rc::<RawSelector>::new(RawSelector::from(raw)));
609                    arena.set_token_list(n, &[]);
610                    // the wrapper takes the place of the node
611                    arena.insert_before(n, &[w]);
612                    arena.append_child(w, n);
613                    n = w;
614                    node = Some(n);
615                    node_type = EnumToken::RuleNodeType;
616                } else if let Some(optimized) = optimized.as_ref().filter(|o| o.borrow().reducible) {
617                    reducible_selector(arena, n, optimized, nesting_content);
618                }
619            } else {
620                let optimized = optimized_of(arena, n);
621                match optimized {
622                    Some(o) if o.borrow().match_ => {
623                        let sel = factor_selector(&o.borrow());
624                        if let Some(sel) = sel {
625                            if js_len(&sel) < arena.string_length(arena.name.get(n)) {
626                                set_selector(arena, n, &sel);
627                                arena.set_token_list(n, &[]);
628                            }
629                        }
630                    }
631                    Some(o) if o.borrow().reducible => reducible_selector(arena, n, &o, nesting_content),
632                    Some(o) if !o.borrow().optimized.is_empty() => {
633                        let sel = o.borrow().optimized.concat();
634                        if js_len(&sel) < arena.string_length(arena.name.get(n)) {
635                            set_selector(arena, n, &sel);
636                            arena.raw.borrow_mut().insert(n, Rc::<RawSelector>::new(RawSelector::from(vec![o.borrow().optimized.clone()])));
637                            arena.set_token_list(n, &[]);
638                        }
639                    }
640                    _ => {}
641                }
642            }
643            recurse!(n);
644        }
645        if let Some(p) = previous {
646            previous_type = Some(t(p));
647            if arena.flags.get(p) & EnumAstNodeStatus::HasChildren != 0 && arena.flags.get(n) & EnumAstNodeStatus::HasChildren != 0 {
648                if previous_type == Some(node_type) {
649                    let mut should_merge = true;
650                    let mut k = arena.last_child.get(p);
651                    while k != 0 {
652                        if t(k) == EnumToken::CommentNodeType {
653                            k = arena.previous_sibling.get(k);
654                            continue;
655                        }
656                        should_merge = t(k) == EnumToken::DeclarationNodeType;
657                        break;
658                    }
659                    // the rules that apply a mixin are not merged
660                    if should_merge && (node_type != EnumToken::RuleNodeType || (!has_at_rule_statement(arena, p) && !has_at_rule_statement(arena, n))) {
661                        if ((node_type == EnumToken::RuleNodeType || node_type == EnumToken::KeyframesRuleNodeType) && arena.name.get(n) == arena.name.get(p))
662                            || (node_type == EnumToken::AtRuleNodeType
663                                && !arena.string_equals(arena.name.get(n), "font-face")
664                                && arena.name.get(n) == arena.name.get(p))
665                        {
666                            arena.move_children(p, n, arena.first_child.get(n));
667                            if let Some(cache) = context.cache.as_mut() {
668                                cache.remove(&n);
669                            }
670                            recurse!(n);
671                            arena.detach(p);
672                            previous = Some(n);
673                            cursor = arena.next_sibling.get(n);
674                            continue;
675                        } else if matches!(node_type, EnumToken::KeyframesRuleNodeType | EnumToken::RuleNodeType) {
676                            if let Some((result, node1, node2)) = diff(arena, p, n, options, context) {
677                                // [result, node2] take the place of node1 (previous), node1 takes the place of node2 (node)
678                                let after = arena.next_sibling.get(node2);
679                                let keep2 = arena.first_child.get(node2) != 0;
680                                if let Some(result) = result {
681                                    arena.insert_before(node1, &[result]);
682                                }
683                                if keep2 {
684                                    arena.insert_before(node1, &[node2]);
685                                } else {
686                                    arena.detach(node2);
687                                }
688                                if arena.first_child.get(node1) == 0 {
689                                    arena.detach(node1);
690                                } else if after == 0 {
691                                    arena.append_child(ast, node1);
692                                } else {
693                                    arena.insert_before(after, &[node1]);
694                                }
695                                // next node to visit
696                                node = if keep2 {
697                                    opt(arena.next_sibling.get(result.unwrap_or(node2)))
698                                } else {
699                                    before(if arena.parents.get(node1) == ast { node1 } else { after }, if result.is_none() { 1 } else { 2 })
700                                };
701                                previous = result;
702                            }
703                        }
704                    }
705                }
706                if recursive {
707                    if let Some(p) = previous {
708                        if Some(p) != node && !has_declaration(arena, p) {
709                            recurse!(p);
710                        }
711                    }
712                }
713            }
714        }
715        if !nesting_content {
716            if let Some(p) = previous {
717                if t(p) == EnumToken::RuleNodeType && arena.string_index_of(arena.name.get(p), 0x26) != -1 {
718                    fix_selector(arena, p);
719                }
720            }
721        }
722        previous = node;
723        cursor = match node {
724            None => arena.first_child.get(ast),
725            Some(n) => arena.next_sibling.get(n),
726        };
727    }
728    if let Some(n) = node {
729        if recursive
730            && arena.flags.get(n) & EnumAstNodeStatus::HasChildren != 0
731            && (t(n) == EnumToken::KeyframesAtRuleNodeType || !has_declaration_child(arena, n))
732            && !(t(n) == EnumToken::AtRuleNodeType && !arena.string_equals(arena.name.get(n), "font-face"))
733        {
734            recurse!(n);
735        }
736        if !nesting_content && t(n) == EnumToken::RuleNodeType && arena.string_index_of(arena.name.get(n), 0x26) != -1 {
737            fix_selector(arena, n);
738        }
739    }
740    ast
741}
742
743/// true if the first non comment child is a declaration
744fn has_declaration(arena: &AstArena, node: u32) -> bool {
745    let mut child = arena.first_child.get(node);
746    while child != 0 {
747        if arena.data_types.get(child) != EnumToken::CommentNodeType {
748            return arena.data_types.get(child) == EnumToken::DeclarationNodeType;
749        }
750        child = arena.next_sibling.get(child);
751    }
752    true
753}
754
755/// true if the node has a declaration child
756fn has_declaration_child(arena: &AstArena, node: u32) -> bool {
757    let mut child = arena.first_child.get(node);
758    while child != 0 {
759        if arena.data_types.get(child) == EnumToken::DeclarationNodeType {
760            return true;
761        }
762        child = arena.next_sibling.get(child);
763    }
764    false
765}
766
767/// optimize a selector
768pub fn optimize_selector(selector: &[Vec<String>]) -> Option<OptimizedSelector> {
769    if selector.is_empty() {
770        return None;
771    }
772    if selector.len() == 1 {
773        let current = &selector[0];
774        if current.last().is_none_or(|last| !last.starts_with(":is(")) {
775            let mut end = current.len();
776            while end > 0 && (current[end - 1] == " " || is_combinator(&current[end - 1])) {
777                end -= 1;
778            }
779            let mut optimized: Vec<String> = current[..end].to_vec();
780            if optimized.first().map(String::as_str) == Some("&") && optimized.get(1).map(String::as_str) == Some(" ") {
781                optimized.drain(0..2);
782            }
783            let remainder: Vec<String> = current[end..].to_vec();
784            let remainder = if remainder.first().map(String::as_str) == Some("&") && remainder.get(1).map(String::as_str) == Some(" ") {
785                remainder[2..].to_vec()
786            } else {
787                remainder
788            };
789            return Some(OptimizedSelector { match_: false, optimized, selector: vec![remainder], reducible: false });
790        }
791    }
792    let mut expanded: Vec<Vec<String>> = Vec::new();
793    for curr in selector {
794        if curr.last().is_some_and(|l| l.starts_with(":is(")) {
795            let last = curr.last().unwrap();
796            let inner: Vec<u16> = last.encode_utf16().collect();
797            let inner = String::from_utf16_lossy(&inner[4..inner.len().saturating_sub(1).max(4)]);
798            let rules = split_rule(&inner).into_iter().map(|x| {
799                if x.first().map(String::as_str) == Some("&") && x.len() > 1 {
800                    x[if x[1] == " " { 2 } else { 1 }..].to_vec()
801                } else {
802                    x
803                }
804            });
805            let part = &curr[..curr.len() - 1];
806            for rule in rules {
807                let mut v = part.to_vec();
808                v.extend(rule);
809                expanded.push(v);
810            }
811            continue;
812        }
813        expanded.push(curr.clone());
814    }
815    let mut seen: HashSet<String> = HashSet::default();
816    let mut selector: Vec<Vec<String>> = expanded.into_iter().filter(|x| seen.insert(x.concat())).collect();
817    let k = selector.iter().fold(0usize, |acc, curr| if acc == 0 { curr.len() } else if curr.is_empty() { acc } else { acc.min(curr.len()) });
818    let mut optimized: Vec<String> = Vec::new();
819    for i in 0..k {
820        let item = selector[0].get(i);
821        if !(1..selector.len()).all(|j| selector[j].get(i) == item) {
822            break;
823        }
824        optimized.push(item.cloned().unwrap_or_default());
825    }
826    while let Some(last) = optimized.last() {
827        if last == " " || is_combinator(last) {
828            optimized.pop();
829            continue;
830        }
831        break;
832    }
833    for s in selector.iter_mut() {
834        let n = optimized.len().min(s.len());
835        s.drain(0..n);
836    }
837    if optimized.first().map(String::as_str) == Some("&") && optimized.get(1).map(String::as_str) == Some(" ") {
838        optimized.drain(0..2);
839    }
840    if optimized.is_empty() || optimized[0].starts_with('&') || selector.len() == 1 {
841        let reducible = selector.len() > 1 && selector.iter().all(|s| s.first().is_none_or(|f| !is_combinator(f)));
842        let selector = selector
843            .into_iter()
844            .map(|mut s| {
845                // the leading `& ` is removed in place
846                if s.first().map(String::as_str) == Some("&") && s.get(1).map(String::as_str) == Some(" ") {
847                    s.drain(0..2);
848                }
849                s
850            })
851            .collect();
852        return Some(OptimizedSelector { match_: false, optimized, selector, reducible });
853    }
854    let mut result: Vec<Vec<String>> = Vec::with_capacity(selector.len());
855    let mut reducible = true;
856    // the selectors are moved into the result
857    for mut curr in selector {
858        let mut has_compound = true;
859        if !curr.is_empty() {
860            let c0 = char_at0(&curr[0]);
861            has_compound = c0 != "&" && !is_combinator(&c0);
862        }
863        if has_compound && curr.first().map(String::as_str) == Some(" ") {
864            has_compound = false;
865            curr.insert(0, "&".into());
866        }
867        if curr.is_empty() {
868            curr.push("&".into());
869            has_compound = false;
870        }
871        reducible &= curr.first().is_none_or(|f| !matches!(f.as_str(), ">" | "+" | "~" | "&"));
872        if has_compound {
873            curr.insert(0, "&".to_string());
874        }
875        result.push(curr);
876    }
877    Some(OptimizedSelector { match_: true, optimized, selector: result, reducible })
878}
879
880/// split a selector string into selectors of parts
881pub fn split_rule(buffer: &str) -> Vec<Vec<String>> {
882    // the delimiters are ascii: an ascii selector is split on its bytes (the byte offsets are the utf-16 offsets), the
883    // other selectors on their utf-16 code units
884    if buffer.is_ascii() {
885        let bytes = buffer.as_bytes();
886        return split_units(bytes, |a, b| buffer[a..b.min(bytes.len())].to_owned());
887    }
888    let units: Vec<u16> = buffer.encode_utf16().collect();
889    let length = units.len();
890    split_units(&units, |a, b| String::from_utf16_lossy(&units[a..b.min(length)]))
891}
892
893/// split a selector given as code units (bytes of an ascii selector or utf-16 code units)
894fn split_units<U: Copy + Into<u32>>(units: &[U], slice: impl Fn(usize, usize) -> String) -> Vec<Vec<String>> {
895    let length = units.len();
896    let code_at = |i: usize| units.get(i).map_or(u32::MAX, |&c| c.into());
897    let mut result: Vec<Vec<String>> = vec![Vec::new()];
898    let mut start: Option<usize> = None;
899    let mut i = 0usize;
900    while i < length {
901        let code: u32 = units[i].into();
902        let group = result.last_mut().unwrap();
903        if is_white_space(code) {
904            if let Some(s) = start.take() {
905                group.push(slice(s, i));
906            }
907            if !group.is_empty() {
908                group.push(" ".into());
909            }
910            i += 1;
911            continue;
912        }
913        if code == 0x2c {
914            if let Some(s) = start.take() {
915                group.push(slice(s, i));
916            }
917            result.push(Vec::new());
918            i += 1;
919            continue;
920        }
921        if code == 0x2e {
922            if let Some(s) = start {
923                group.push(slice(s, i));
924            }
925            start = Some(i);
926            i += 1;
927            continue;
928        }
929        // the combinators: + > ~ | ||
930        if matches!(code, 0x2b | 0x3e | 0x7e | 0x7c) {
931            if let Some(s) = start.take() {
932                group.push(slice(s, i));
933            }
934            if code == 0x7c && code_at(i + 1) == 0x7c {
935                group.push("||".into());
936                i += 1;
937            } else {
938                group.push(match code {
939                    0x2b => "+",
940                    0x3e => ">",
941                    0x7e => "~",
942                    _ => "|",
943                }
944                .into());
945            }
946            i += 1;
947            continue;
948        }
949        // : ::
950        if code == 0x3a {
951            if let Some(s) = start {
952                group.push(slice(s, i));
953            }
954            start = Some(i);
955            if code_at(i + 1) == 0x3a {
956                i += 1;
957            }
958            i += 1;
959            continue;
960        }
961        if start.is_none() {
962            start = Some(i);
963        }
964        // \: the escaped character
965        if code == 0x5c {
966            i += 2;
967            continue;
968        }
969        // ( [: the part ends with the matching ) ]
970        if code == 0x28 || code == 0x5b {
971            i = matching_close(units, i, length);
972        }
973        i += 1;
974    }
975    if let Some(s) = start {
976        result.last_mut().unwrap().push(slice(s, length));
977    }
978    result
979}
980
981/// index of the `)` / `]` that closes the `(` / `[` at `i` (`length` when it is not closed)
982fn matching_close<U: Copy + Into<u32>>(codes: &[U], i: usize, length: usize) -> usize {
983    let code: u32 = codes[i].into();
984    let close = if code == 0x28 { 0x29 } else { 0x5d };
985    let mut depth = 1;
986    let mut k = i;
987    loop {
988        k += 1;
989        if k >= length {
990            break;
991        }
992        let c: u32 = codes[k].into();
993        if c == 0x5c {
994            k += 1;
995            continue;
996        }
997        if c == code {
998            depth += 1;
999        } else if c == close {
1000            depth -= 1;
1001        }
1002        if depth == 0 {
1003            break;
1004        }
1005    }
1006    k
1007}
1008
1009/// reduce a selector relative to the matched prefix (`reduceSelector.bind({ match })`)
1010fn reduce_selector(match_: &[Vec<String>], curr: &[String]) -> Vec<String> {
1011    let mut has_compound_selector = true;
1012    let mut curr: Vec<String> = curr.get(match_[0].len().min(curr.len())..).unwrap_or(&[]).to_vec();
1013    while curr.first().map(String::as_str) == Some(" ") {
1014        has_compound_selector = false;
1015        curr.insert(0, "&".into());
1016        // `continue`: the first part is now "&"
1017        break;
1018    }
1019    if has_compound_selector && !curr.is_empty() {
1020        let c0 = char_at0(&curr[0]);
1021        has_compound_selector = c0 != "&" && !is_combinator(&c0);
1022    }
1023    if curr.first().map(String::as_str) == Some(":is(") {
1024        let mut can_reduce = true;
1025        let mut is_compound: Vec<Vec<String>> = vec![Vec::new()];
1026        for (index, token) in curr.iter().enumerate() {
1027            if index == 0 {
1028                can_reduce = curr.get(1).map(String::as_str) == Some("&");
1029            } else if token == ")" {
1030            } else if token == "," {
1031                if !can_reduce {
1032                    can_reduce = curr.get(index + 1).map(String::as_str) == Some("&");
1033                }
1034                is_compound.push(Vec::new());
1035            } else {
1036                is_compound.last_mut().unwrap().push(token.clone());
1037            }
1038        }
1039        if can_reduce {
1040            let mut acc: Vec<String> = Vec::new();
1041            for c in is_compound {
1042                if !acc.is_empty() {
1043                    acc.push(",".into());
1044                }
1045                acc.extend(c);
1046            }
1047            curr = acc;
1048        }
1049    }
1050    if match_.is_empty() {
1051        return vec!["&".into()];
1052    }
1053    if has_compound_selector && curr.first().map(String::as_str) != Some("&") && curr.first().is_none_or(|c| !is_combinator(&char_at0(c))) {
1054        let mut v = vec!["&".to_string()];
1055        v.extend(curr);
1056        return v;
1057    }
1058    curr
1059}
1060
1061/// matched selectors (`MatchedSelector`)
1062pub struct MatchedSelector {
1063    pub eq: bool,
1064    pub match_: Vec<Vec<String>>,
1065    pub selector1: Vec<Vec<String>>,
1066    pub selector2: Vec<Vec<String>>,
1067}
1068
1069/// `/^:is\(([:.][^\s,]+)\)$/`
1070fn is_single_is(token: &str) -> Option<String> {
1071    let inner = token.strip_prefix(":is(")?.strip_suffix(')')?;
1072    let mut chars = inner.chars();
1073    let first = chars.next()?;
1074    if first != ':' && first != '.' {
1075        return None;
1076    }
1077    let rest: Vec<char> = chars.collect();
1078    if rest.is_empty() || rest.iter().any(|c| c.is_whitespace() || *c == ',' || *c == '\u{feff}') {
1079        return None;
1080    }
1081    Some(inner.to_string())
1082}
1083
1084/// the `:is(.a)` parts of the selectors that start with `&` are replaced by `.a` (in place)
1085/// true if a selector may contain a single `:is()` to unwrap (see unwrap_single_is()): the selector is not copied
1086/// otherwise
1087fn needs_unwrap(selector: &[Vec<String>]) -> bool {
1088    selector.iter().any(|s| s.first().map(String::as_str) == Some("&") && s.iter().skip(1).any(|t| t.starts_with(":is(")))
1089}
1090
1091/// returns true when the selector is modified
1092fn unwrap_single_is(selector: &mut [Vec<String>]) -> bool {
1093    let mut modified = false;
1094    for s in selector.iter_mut() {
1095        if s.first().map(String::as_str) != Some("&") {
1096            continue;
1097        }
1098        for token in s.iter_mut().skip(1) {
1099            if token.starts_with(":is(") {
1100                if let Some(m) = is_single_is(token) {
1101                    *token = m;
1102                    modified = true;
1103                }
1104            }
1105        }
1106    }
1107    modified
1108}
1109
1110/// match the selectors of two rules: their raw selectors are modified in place (`:is(.a)` -> `.a`)
1111fn match_selectors_of(arena: &AstArena, node1: u32, node2: u32) -> Option<MatchedSelector> {
1112    let mut s1 = raw_selector(arena, node1);
1113    let mut s2 = raw_selector(arena, node2);
1114    // raw_selector() cached the selectors (shared): a selector is copied and stored again only when it is modified
1115    if needs_unwrap(&s1) && unwrap_single_is(Rc::make_mut(&mut s1).as_mut_slice()) {
1116        arena.raw.borrow_mut().insert(node1, s1.clone());
1117    }
1118    if needs_unwrap(&s2) && unwrap_single_is(Rc::make_mut(&mut s2).as_mut_slice()) && node1 != node2 {
1119        arena.raw.borrow_mut().insert(node2, s2.clone());
1120    }
1121    match_selectors(&s1, &s2)
1122}
1123
1124/// match selectors
1125fn match_selectors(selector1: &[Vec<String>], selector2: &[Vec<String>]) -> Option<MatchedSelector> {
1126    let min_len = |s: &[Vec<String>]| s.iter().fold(s.first().map_or(0, |f| f.len()), |acc, curr| acc.min(curr.len()));
1127    let j = min_len(&selector1).min(min_len(&selector2));
1128    let mut match_: Vec<Vec<String>> = vec![Vec::new()];
1129    let mut match_function = 0;
1130    for i in 0..j {
1131        let token = &selector1[0][i];
1132        if !selector1.iter().all(|s| s.get(i) == Some(token)) || !selector2.iter().all(|s| s.get(i) == Some(token)) {
1133            break;
1134        }
1135        if token.ends_with('(') {
1136            match_function += 1;
1137        }
1138        match_.last_mut().unwrap().push(token.clone());
1139    }
1140    // invalid function
1141    if match_function != 0 {
1142        return None;
1143    }
1144    for part in match_.iter_mut() {
1145        while let Some(token) = part.last() {
1146            if token == " " || is_combinator(token) || token.chars().last().is_some_and(not_ending_with) {
1147                part.pop();
1148                continue;
1149            }
1150            break;
1151        }
1152    }
1153    if match_.iter().all(|t| t.is_empty()) {
1154        return None;
1155    }
1156    if match_ == vec![vec!["&".to_string()]] {
1157        return None;
1158    }
1159    let selector1: Vec<Vec<String>> = selector1.iter().map(|curr| reduce_selector(&match_, curr)).collect();
1160    let selector2: Vec<Vec<String>> = selector2.iter().map(|curr| reduce_selector(&match_, curr)).collect();
1161    Some(MatchedSelector { eq: selector1 == selector2, match_, selector1, selector2 })
1162}
1163
1164/// the nesting selectors of the `:is()` functions of a rule selector are removed
1165fn fix_selector(arena: &AstArena, node: u32) {
1166    let sel = arena.resolve_string(arena.name.get(node));
1167    if !sel.contains('&') {
1168        return;
1169    }
1170    let attributes = parse_string(arena, &sel);
1171    let mut walker = ValueWalker::of_tokens(&attributes, WalkerValueOptions::default(), false);
1172    while let Some(attr) = walker.next(arena) {
1173        if arena.data_types.get(attr) == EnumToken::PseudoClassFuncTokenType && arena.string_equals(arena.string_value.get(attr), ":is") {
1174            let mut child = arena.last_token.get(attr);
1175            while child != 0 {
1176                let previous = arena.previous_sibling.get(child);
1177                if arena.data_types.get(child) == EnumToken::NestingSelectorTokenType {
1178                    arena.detach(child);
1179                }
1180                child = previous;
1181            }
1182        }
1183    }
1184    let rendered: String = attributes.iter().map(|&a| render_value_default(arena, a)).collect();
1185    set_selector(arena, node, &rendered);
1186    arena.set_token_list(node, &[]);
1187}
1188
1189/// wrap two sibling rules into a new rule. the wrapper takes the place of node, previous is removed
1190fn wrap_nodes(arena: &AstArena, previous: u32, node: u32, mut m: MatchedSelector) -> u32 {
1191    let p_sel = reduce_join(&mut m.selector1);
1192    let n_sel = reduce_join(&mut m.selector2);
1193    let wrapper = arena.clone_node(previous);
1194    let mut match_copy = m.match_.clone();
1195    set_selector(arena, wrapper, &reduce_join(&mut match_copy));
1196    // the matched selector is moved: reduce_join() modified its copy
1197    arena.raw.borrow_mut().insert(wrapper, Rc::<RawSelector>::new(RawSelector::from(m.match_)));
1198    // not copied by cloneNode()
1199    arena.optimized.borrow_mut().remove(&wrapper);
1200    arena.set_token_list(wrapper, &[]);
1201    let parent = arena.parents.get(node);
1202    // the wrapper takes the place of node
1203    arena.insert_before(node, &[wrapper]);
1204    if p_sel == "&" || p_sel.is_empty() {
1205        arena.move_children(previous, wrapper, 0);
1206        if n_sel == "&" || n_sel.is_empty() {
1207            arena.move_children(node, wrapper, 0);
1208        } else {
1209            arena.append_child(wrapper, node);
1210        }
1211    } else {
1212        arena.append_child(wrapper, previous);
1213        arena.append_child(wrapper, node);
1214    }
1215    // the nodes whose children were moved into the wrapper are dropped
1216    if arena.parents.get(previous) == parent {
1217        arena.detach(previous);
1218    }
1219    if arena.parents.get(node) == parent {
1220        arena.detach(node);
1221    }
1222    // update the selectors of the wrapped nodes
1223    if arena.parents.get(previous) == wrapper {
1224        set_selector(arena, previous, &p_sel);
1225        arena.raw.borrow_mut().insert(previous, Rc::<RawSelector>::new(RawSelector::from(m.selector1)));
1226        arena.set_token_list(previous, &[]);
1227    }
1228    if arena.parents.get(node) == wrapper {
1229        set_selector(arena, node, &n_sel);
1230        arena.raw.borrow_mut().insert(node, Rc::<RawSelector>::new(RawSelector::from(m.selector2)));
1231        arena.set_token_list(node, &[]);
1232    }
1233    reduce_rule_selector(arena, wrapper);
1234    arena.set_token_list(wrapper, &[]);
1235    wrapper
1236}
1237
1238/// true if a child of the node is an at-rule without a block or an `@apply` rule
1239fn has_at_rule_statement(arena: &AstArena, node: u32) -> bool {
1240    let mut child = arena.first_child.get(node);
1241    while child != 0 {
1242        if arena.data_types.get(child) == EnumToken::AtRuleNodeType
1243            && (arena.flags.get(child) & EnumAstNodeStatus::HasChildren == 0 || arena.string_equals(arena.name.get(child), "apply"))
1244        {
1245            return true;
1246        }
1247        child = arena.next_sibling.get(child);
1248    }
1249    false
1250}
1251
1252/// the first vendor prefix of a part of a selector: `::?-([a-z]+)-`
1253fn part_prefix(codes: &[u16], start: usize, end: usize) -> Option<String> {
1254    for p in start..end {
1255        if codes[p] != 0x3a {
1256            continue;
1257        }
1258        let mut q = p + 1;
1259        if q < end && codes[q] == 0x3a {
1260            q += 1;
1261        }
1262        if q >= end || codes[q] != 0x2d {
1263            continue;
1264        }
1265        let mut k = q + 1;
1266        while k < end && (0x61..=0x7a).contains(&codes[k]) {
1267            k += 1;
1268        }
1269        if k > q + 1 && k < end && codes[k] == 0x2d {
1270            return Some(String::from_utf16_lossy(&codes[q + 1..k]));
1271        }
1272    }
1273    None
1274}
1275
1276/// `t.match(/::?-([a-z]+)-/)?.[1]`
1277fn string_prefix(t: &str) -> Option<String> {
1278    let codes: Vec<u16> = t.encode_utf16().collect();
1279    part_prefix(&codes, 0, codes.len())
1280}
1281
1282/// the vendor prefixes of the pseudo classes of a split selector
1283fn raw_selector_prefixes(raw: &RawSelectorTokens) -> Vec<String> {
1284    let mut prefixes: Vec<String> = Vec::new();
1285    'outer: for token in raw {
1286        for t in token {
1287            if t.contains(':') {
1288                let Some(prefix) = string_prefix(t) else {
1289                    continue;
1290                };
1291                if !prefixes.contains(&prefix) {
1292                    prefixes.push(prefix);
1293                }
1294                if prefixes.len() > 1 {
1295                    break 'outer;
1296                }
1297            }
1298        }
1299    }
1300    prefixes
1301}
1302
1303/// code units of an interned string
1304fn read_selector(arena: &AstArena, id: u32) -> Vec<u16> {
1305    let mut codes = Vec::with_capacity(arena.string_length(id));
1306    arena.copy_string(id, &mut codes);
1307    codes
1308}
1309
1310/// the vendor prefixes of the pseudo classes of a selector read from the string table
1311/// the vendor prefixes of a selector string, cached by string id (the string epoch invalidates the cache)
1312fn selector_prefixes_of(arena: &AstArena, id: u32) -> Rc<[String]> {
1313    let epoch = arena.string_epoch();
1314    {
1315        let cache = arena.selector_prefixes.borrow();
1316        if cache.0 == epoch {
1317            if let Some(prefixes) = cache.1.get(&id) {
1318                return prefixes.clone();
1319            }
1320        }
1321    }
1322    let prefixes: Rc<[String]> = selector_prefixes(arena, id).into();
1323    let mut cache = arena.selector_prefixes.borrow_mut();
1324    if cache.0 != epoch {
1325        cache.1.clear();
1326        cache.0 = epoch;
1327    }
1328    cache.1.insert(id, prefixes.clone());
1329    prefixes
1330}
1331
1332fn selector_prefixes(arena: &AstArena, id: u32) -> Vec<String> {
1333    // the selectors without `:-` are skipped: computed once per string id
1334    let has_prefix = arena.string_flag_id(id, StringFlag::VendorPrefix, |id| read_selector(arena, id).windows(2).any(|w| w[0] == 0x3a && w[1] == 0x2d));
1335    let mut prefixes: Vec<String> = Vec::new();
1336    if !has_prefix {
1337        return prefixes;
1338    }
1339    let codes = read_selector(arena, id);
1340    let length = codes.len();
1341    let mut start: Option<usize> = None;
1342    let add_part = |start: usize, end: usize, prefixes: &mut Vec<String>| -> bool {
1343        if codes[start..end].contains(&0x3a) {
1344            if let Some(prefix) = part_prefix(&codes, start, end) {
1345                if !prefixes.contains(&prefix) {
1346                    prefixes.push(prefix);
1347                }
1348            }
1349        }
1350        prefixes.len() > 1
1351    };
1352    let mut i = 0usize;
1353    while i < length {
1354        let code = codes[i] as u32;
1355        if is_white_space(code) || code == 0x2c {
1356            if let Some(s) = start {
1357                if add_part(s, i, &mut prefixes) {
1358                    return prefixes;
1359                }
1360            }
1361            start = None;
1362        } else if code == 0x2e || code == 0x3a {
1363            if let Some(s) = start {
1364                if add_part(s, i, &mut prefixes) {
1365                    return prefixes;
1366                }
1367            }
1368            start = Some(i);
1369            if code == 0x3a && codes.get(i + 1) == Some(&0x3a) {
1370                i += 1;
1371            }
1372        } else if matches!(code, 0x2b | 0x3e | 0x7e | 0x7c) {
1373            if let Some(s) = start {
1374                if add_part(s, i, &mut prefixes) {
1375                    return prefixes;
1376                }
1377            }
1378            start = None;
1379            if code == 0x7c && codes.get(i + 1) == Some(&0x7c) {
1380                i += 1;
1381            }
1382        } else {
1383            if start.is_none() {
1384                start = Some(i);
1385            }
1386            if code == 0x5c {
1387                i += 1;
1388            } else if code == 0x28 || code == 0x5b {
1389                i = matching_close(&codes, i, length);
1390            }
1391        }
1392        i += 1;
1393    }
1394    if let Some(s) = start {
1395        add_part(s, length, &mut prefixes);
1396    }
1397    prefixes
1398}
1399
1400fn same_prefixes(a: &[String], b: &[String]) -> bool {
1401    a.len() == b.len() && a.iter().all(|p| b.contains(p))
1402}
1403
1404/// move the declarations shared by both rules into a new rule. `(result, node1, node2)`
1405fn diff(arena: &AstArena, n1: u32, n2: u32, options: &ParserOptions, context: &mut MinifyContext) -> Option<(Option<u32>, u32, u32)> {
1406    // the declarations of a rule that applies a mixin are not moved
1407    if has_at_rule_statement(arena, n1) || has_at_rule_statement(arena, n2) {
1408        return None;
1409    }
1410    context.cache.get_or_insert_with(HashMap::default);
1411    let t = |x: u32| arena.data_types.get(x);
1412    let (mut node1, mut node2) = (n1, n2);
1413    let mut exchanged = false;
1414    if arena.child_count(node1) > arena.child_count(node2) {
1415        std::mem::swap(&mut node1, &mut node2);
1416        exchanged = true;
1417    }
1418    // the prefixes of the cached raw selectors are read in place
1419    // the prefixes are computed once per split selector (see RawSelector) or per selector string
1420    let cached1 = arena.raw.borrow().get(&node1).map(|r| r.prefixes(raw_selector_prefixes));
1421    let prefixes1 = cached1.unwrap_or_else(|| selector_prefixes_of(arena, arena.name.get(node1)));
1422    let cached2 = arena.raw.borrow().get(&node2).map(|r| r.prefixes(raw_selector_prefixes));
1423    let prefixes2 = cached2.unwrap_or_else(|| selector_prefixes_of(arena, arena.name.get(node2)));
1424    if !same_prefixes(&prefixes1, &prefixes2) {
1425        return None;
1426    }
1427    // match the declarations of both rules, from the last to the first
1428    let mut matches = 0;
1429    let mut child1 = arena.last_child.get(node1);
1430    while child1 != 0 {
1431        if t(child1) != EnumToken::CommentNodeType {
1432            let mut child2 = arena.last_child.get(node2);
1433            while child2 != 0 {
1434                if t(child2) != EnumToken::CommentNodeType
1435                    && arena.flags.get(child2) & EnumAstNodeStatus::Matched == 0
1436                    && arena.name.get(child1) == arena.name.get(child2)
1437                    && eq_node(arena, child1, child2)
1438                {
1439                    arena.flags.set(child1, arena.flags.get(child1) | EnumAstNodeStatus::Matched);
1440                    arena.flags.set(child2, arena.flags.get(child2) | EnumAstNodeStatus::Matched);
1441                    matches += 1;
1442                    break;
1443                }
1444                child2 = arena.previous_sibling.get(child2);
1445            }
1446        }
1447        child1 = arena.previous_sibling.get(child1);
1448    }
1449    if matches == 0 && (arena.first_child.get(node1) != 0 || arena.first_child.get(node2) != 0) {
1450        return None;
1451    }
1452    // the rules are rendered with the same options during the minification
1453    if context.renderer.is_none() {
1454        context.renderer = Some(NodeRenderer::new(options));
1455    }
1456    let rendered_size = |context: &mut MinifyContext, node: u32, cache: bool| -> usize {
1457        let mut size = if cache { context.cache.as_ref().unwrap().get(&node).copied() } else { None };
1458        if size.is_none() {
1459            let s = context.renderer.as_mut().unwrap().size(arena, node);
1460            if cache {
1461                context.cache.as_mut().unwrap().insert(node, s);
1462            }
1463            size = Some(s);
1464        }
1465        if arena.first_child.get(node) == 0 {
1466            0
1467        } else {
1468            size.unwrap()
1469        }
1470    };
1471    // size of the original nodes
1472    let size = rendered_size(context, n1, true) + rendered_size(context, n2, true);
1473    // the shared declarations are moved into the result node
1474    let result = arena.clone_node(node1);
1475    let merged = merge_selectors(arena, arena.name.get(node1), arena.name.get(node2)).unwrap_or_else(|| {
1476        let mut seen: Vec<String> = Vec::new();
1477        for s in split_rule(&arena.resolve_string(arena.name.get(node1)))
1478            .into_iter()
1479            .chain(split_rule(&arena.resolve_string(arena.name.get(node2))))
1480        {
1481            let joined = s.concat();
1482            if !seen.contains(&joined) {
1483                seen.push(joined);
1484            }
1485        }
1486        arena.intern_string(&seen.join(","))
1487    });
1488    arena.name.set(result, merged);
1489    // the matched declarations of node1 are moved into the result, the duplicates in node2 are dropped
1490    let mut moves: Vec<(u32, u32, u32)> = Vec::new();
1491    let mut move_matched = |parent: u32, target: Option<u32>| {
1492        let mut child = arena.first_child.get(parent);
1493        while child != 0 {
1494            let next = arena.next_sibling.get(child);
1495            if arena.flags.get(child) & EnumAstNodeStatus::Matched != 0 {
1496                arena.flags.set(child, arena.flags.get(child) & !EnumAstNodeStatus::Matched);
1497                moves.push((child, parent, next));
1498                match target {
1499                    None => arena.detach(child),
1500                    Some(target) => arena.append_child(target, child),
1501                }
1502            }
1503            child = next;
1504        }
1505    };
1506    move_matched(node1, Some(result));
1507    move_matched(node2, None);
1508    arena.insert_before(n1, &[result]);
1509    if let Some(cache) = context.cache.as_mut() {
1510        cache.remove(&node1);
1511        cache.remove(&node2);
1512    }
1513    let merged_size = rendered_size(context, node1, false) + rendered_size(context, node2, false) + rendered_size(context, result, false);
1514    if size < merged_size || (size == merged_size && arena.first_child.get(node1) != 0 && arena.first_child.get(node2) != 0) {
1515        // restore the nodes: undo the moves in reverse order
1516        for &(child, parent, next) in moves.iter().rev() {
1517            if next == 0 {
1518                arena.append_child(parent, child);
1519            } else {
1520                arena.insert_before(next, &[child]);
1521            }
1522        }
1523        arena.detach(result);
1524        return None;
1525    }
1526    arena.set_token_list(result, &[]);
1527    // the raw and optimized selectors are not copied by cloneNode()
1528    arena.raw.borrow_mut().remove(&result);
1529    arena.optimized.borrow_mut().remove(&result);
1530    if let Some(optimized) = optimize_selector(&split_rule(&arena.resolve_string(arena.name.get(result)))) {
1531        if optimized.match_ {
1532            if let Some(sel) = factor_selector(&optimized) {
1533                if js_len(&sel) < arena.string_length(arena.name.get(result)) {
1534                    set_selector(arena, result, &sel);
1535                    arena.set_token_list(result, &[]);
1536                }
1537            }
1538        }
1539    }
1540    arena.detach(result);
1541    Some((Some(result), if exchanged { node2 } else { node1 }, if exchanged { node1 } else { node2 }))
1542}
1543
1544/// compare two nodes
1545fn eq_node(arena: &AstArena, a: u32, b: u32) -> bool {
1546    if a == b {
1547        return true;
1548    }
1549    if arena.data_types.get(a) != arena.data_types.get(b) || arena.name.get(a) != arena.name.get(b) || arena.string_value.get(a) != arena.string_value.get(b) {
1550        return false;
1551    }
1552    if arena.flags.get(a) & EnumAstNodeStatus::HasValues != 0 {
1553        let mut token1 = arena.first_token.get(a);
1554        let mut token2 = arena.first_token.get(b);
1555        while token1 != 0 && token2 != 0 {
1556            if !eq_token(arena, token1, token2) {
1557                return false;
1558            }
1559            token1 = arena.next_sibling.get(token1);
1560            token2 = arena.next_sibling.get(token2);
1561        }
1562        if token1 != token2 {
1563            return false;
1564        }
1565    }
1566    if arena.flags.get(a) & EnumAstNodeStatus::HasChildren != 0 {
1567        let mut child1 = arena.first_child.get(a);
1568        let mut child2 = arena.first_child.get(b);
1569        while child1 != 0 && child2 != 0 {
1570            if !eq_node(arena, child1, child2) {
1571                return false;
1572            }
1573            child1 = arena.next_sibling.get(child1);
1574            child2 = arena.next_sibling.get(child2);
1575        }
1576        return child1 == child2;
1577    }
1578    true
1579}
1580
1581/// the bounds of the comma separated selectors of a selector string appended to `codes`. `None` when the selector
1582/// string is not normalized (whitespace other than a single space between two parts, a space after a comma)
1583fn selector_ranges(arena: &AstArena, id: u32, codes: &mut Vec<u16>, bounds: &mut Vec<(usize, usize)>) -> Option<()> {
1584    let length = arena.string_length(id);
1585    let offset = codes.len();
1586    arena.copy_string(id, codes);
1587    let mut start = offset;
1588    let mut i = offset;
1589    while i < offset + length {
1590        let code = codes[i] as u32;
1591        if is_white_space(code) {
1592            // a single space between two parts
1593            if code != 0x20 || i == start || is_white_space(codes[i - 1] as u32) {
1594                return None;
1595            }
1596        } else if code == 0x2c {
1597            bounds.push((start, i));
1598            start = i + 1;
1599        } else if code == 0x5c {
1600            i += 1;
1601        } else if code == 0x28 || code == 0x5b {
1602            i = matching_close(codes, i, offset + length);
1603        }
1604        i += 1;
1605    }
1606    bounds.push((start, offset + length));
1607    Some(())
1608}
1609
1610/// the distinct selectors of two selector strings, comma separated. `None` when a selector string is not normalized
1611fn merge_selectors(arena: &AstArena, id1: u32, id2: u32) -> Option<u32> {
1612    let mut codes: Vec<u16> = Vec::new();
1613    let mut bounds: Vec<(usize, usize)> = Vec::new();
1614    selector_ranges(arena, id1, &mut codes, &mut bounds)?;
1615    selector_ranges(arena, id2, &mut codes, &mut bounds)?;
1616    let mut result: Vec<u16> = Vec::new();
1617    let mut written = 0;
1618    for i in 0..bounds.len() {
1619        let (start1, end1) = bounds[i];
1620        let duplicate = (0..i).any(|k| codes[bounds[k].0..bounds[k].1] == codes[start1..end1]);
1621        if duplicate {
1622            continue;
1623        }
1624        if written > 0 {
1625            result.push(0x2c);
1626        }
1627        written += 1;
1628        result.extend_from_slice(&codes[start1..end1]);
1629    }
1630    Some(arena.intern_units(&result))
1631}
1632
1633/// the split selector of a rule (see split_rule()): computed when it is not cached
1634fn raw_selector(arena: &AstArena, node: u32) -> Rc<RawSelector> {
1635    if let Some(raw) = arena.raw.borrow().get(&node) {
1636        return raw.clone();
1637    }
1638    let raw = Rc::new(RawSelector::from(split_rule(&arena.resolve_string(arena.name.get(node)))));
1639    arena.raw.borrow_mut().insert(node, raw.clone());
1640    raw
1641}
1642
1643/// the first part of the first selector of a selector string, cached by string id (the string epoch invalidates the
1644/// cache when the ids are renumbered): the code units, `None` when the first selector is empty
1645fn first_part_of(arena: &AstArena, id: u32) -> Option<Rc<[u16]>> {
1646    let epoch = arena.string_epoch();
1647    {
1648        let cache = arena.first_parts.borrow();
1649        if cache.0 == epoch {
1650            if let Some(part) = cache.1.get(&id) {
1651                return part.clone();
1652            }
1653        }
1654    }
1655    let part: Option<Rc<[u16]>> = first_part_units(arena, id).map(Rc::from);
1656    let mut cache = arena.first_parts.borrow_mut();
1657    if cache.0 != epoch {
1658        cache.1.clear();
1659        cache.0 = epoch;
1660    }
1661    cache.1.insert(id, part.clone());
1662    part
1663}
1664
1665/// the first part of the first selector of a selector string: the code units, `None` when the first selector is empty
1666fn first_part_units(arena: &AstArena, id: u32) -> Option<Vec<u16>> {
1667    let codes = read_selector(arena, id);
1668    let length = codes.len();
1669    let code_at = |i: usize| codes.get(i).copied().map_or(u32::MAX, u32::from);
1670    let mut start: Option<usize> = None;
1671    let mut i = 0;
1672    while i < length && is_white_space(codes[i] as u32) {
1673        i += 1;
1674    }
1675    let part_start = i;
1676    let range = |end: usize| Some(codes[part_start..end].to_vec());
1677    while i < length {
1678        let code = codes[i] as u32;
1679        if is_white_space(code) {
1680            return range(i);
1681        }
1682        if code == 0x2c {
1683            return if start.is_none() { None } else { range(i) };
1684        }
1685        if code == 0x2e || code == 0x3a {
1686            if start.is_some() {
1687                return range(i);
1688            }
1689            start = Some(i);
1690            if code == 0x3a && code_at(i + 1) == 0x3a {
1691                i += 1;
1692            }
1693            i += 1;
1694            continue;
1695        }
1696        if matches!(code, 0x2b | 0x3e | 0x7e | 0x7c) {
1697            let end = if start.is_some() {
1698                i
1699            } else if code == 0x7c && code_at(i + 1) == 0x7c {
1700                i + 2
1701            } else {
1702                i + 1
1703            };
1704            return range(end.min(length));
1705        }
1706        if start.is_none() {
1707            start = Some(i);
1708        }
1709        if code == 0x5c {
1710            i += 2;
1711            continue;
1712        }
1713        if code == 0x28 || code == 0x5b {
1714            i = matching_close(&codes, i, length);
1715        }
1716        i += 1;
1717    }
1718    if start.is_none() {
1719        None
1720    } else {
1721        range(i.min(length))
1722    }
1723}
1724
1725/// false when the selectors of two rules cannot match: the first parts of their first selectors are different
1726fn may_match_selectors(arena: &AstArena, node1: u32, node2: u32) -> bool {
1727    // the first part of a split selector is its first token (a string), the first part of a selector string is read
1728    // from its code units: the parts are compared without a copy
1729    let raw = arena.raw.borrow();
1730    let part = |node: u32| -> Result<Option<&str>, u32> {
1731        match raw.get(&node) {
1732            Some(r) => Ok(r.first().and_then(|r| r.first()).map(String::as_str)),
1733            None => Err(arena.name.get(node)),
1734        }
1735    };
1736    match (part(node1), part(node2)) {
1737        (Ok(a), Ok(b)) => a.is_some() && a == b,
1738        (Ok(a), Err(id)) | (Err(id), Ok(a)) => match (a, first_part_of(arena, id)) {
1739            (Some(a), Some(b)) => a.encode_utf16().eq(b.iter().copied()),
1740            _ => false,
1741        },
1742        (Err(id1), Err(id2)) => match (first_part_of(arena, id1), first_part_of(arena, id2)) {
1743            (Some(a), Some(b)) => a == b,
1744            _ => false,
1745        },
1746    }
1747}
1748
1749/// true if a rule selector is not modified by reduce_rule_selector(): a single selector (no comma), that does not
1750/// start with `&`, does not end with `)`, a combinator or a whitespace, and has no whitespace other than single spaces
1751fn is_simple_selector(arena: &AstArena, id: u32) -> bool {
1752    arena.string_flag_id(id, StringFlag::SimpleSelector, |id| {
1753        let codes = read_selector(arena, id);
1754        if codes.is_empty() || codes[0] == 0x26 {
1755            return false;
1756        }
1757        let mut previous = 0u32;
1758        for (i, &code) in codes.iter().enumerate() {
1759            let code = code as u32;
1760            if code == 0x2c {
1761                return false;
1762            }
1763            if is_white_space(code) && (code != 0x20 || i == 0 || is_white_space(previous)) {
1764                return false;
1765            }
1766            previous = code;
1767        }
1768        !(matches!(previous, 0x29 | 0x2b | 0x3e | 0x7e | 0x7c) || is_white_space(previous))
1769    })
1770}
1771
1772/// reduce a rule selector
1773fn reduce_rule_selector(arena: &AstArena, node: u32) {
1774    let raw = raw_selector(arena, node);
1775    let Some(mut optimized) = optimize_selector(&raw) else {
1776        return;
1777    };
1778    if optimized.match_ && optimized.reducible && optimized.selector.len() > 1 {
1779        for selector in optimized.selector.iter_mut() {
1780            if selector.len() > 1
1781                && selector[0] == "&"
1782                && (is_combinator(&selector[1]) || !selector[1].chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == ':'))
1783            {
1784                selector.remove(0);
1785            }
1786        }
1787        let mut unique: HashSet<String> = HashSet::default();
1788        let mut reduced: Vec<String> = Vec::new();
1789        for curr in &optimized.selector {
1790            if unique.insert(curr.concat()) {
1791                if !reduced.is_empty() {
1792                    reduced.push(",".into());
1793                }
1794                reduced.extend(curr.iter().cloned());
1795            }
1796        }
1797        let mut first = vec![optimized.optimized[0].clone(), if reduced.len() == 1 { reduced.concat() } else { ":is(".into() }];
1798        first.extend(reduced);
1799        first.push(")".into());
1800        let sel = first.concat();
1801        let shared = Rc::new(RefCell::new(optimized));
1802        arena.optimized.borrow_mut().insert(node, shared);
1803        if js_len(&sel) < arena.string_length(arena.name.get(node)) {
1804            set_selector(arena, node, &sel);
1805            arena.raw.borrow_mut().insert(node, Rc::<RawSelector>::new(RawSelector::from(vec![first])));
1806            arena.set_token_list(node, &[]);
1807        }
1808        return;
1809    }
1810    arena.optimized.borrow_mut().insert(node, Rc::new(RefCell::new(optimized)));
1811}