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