Skip to main content

rust_css_parser/parser/utils/
selector.rs

1//! Port of `src/parser/utils/selector.ts`.
2
3use crate::ast::arena::{AstArena, StrOrId, TokenValue};
4use crate::ast::strings::{StringBuilder, StringDerived};
5use crate::utils::pool::PooledVec;
6use crate::ast::types::{EnumAstNodeStatus, EnumToken};
7use crate::options::ParserOptions;
8use crate::parser::utils::text::equals_ignore_case;
9use crate::printer::render::render_value;
10use crate::syntax::constants::{is_function_def_type, tokens_func_def_map, COMBINATORS, PSEUDO_ELEMENTS};
11use crate::syntax::syntax::{is_hash, is_ident};
12use crate::types::ErrorDescription;
13use crate::validation::config::{get_parsed_syntax, get_syntax_rule};
14use crate::validation::match_::{create_validation_context, match_all_syntaxes, match_selector_syntax, match_simple_selector, selector_function_syntax, trim_array};
15use crate::validation::parser::typedef::{ValidationSyntaxGroupEnum, ValidationTokenEnum};
16use crate::validation::utils::list::split_token_list_comma;
17use std::cell::RefCell;
18
19/// `trimWhiteSpace` of `parse.ts`
20pub fn is_trim_white_space(t: u8) -> bool {
21    matches!(
22        t,
23        EnumToken::CommentTokenType
24            | EnumToken::GtTokenType
25            | EnumToken::GteTokenType
26            | EnumToken::LtTokenType
27            | EnumToken::LteTokenType
28            | EnumToken::ColumnCombinatorTokenType
29    )
30}
31
32/// `/^(([+-]?[0-9]*)?n)?([+-]?[0-9]+)?$/`: groups 2 and 3
33fn nth_groups(value: &str) -> Option<(Option<String>, Option<String>)> {
34    let parse_int = |s: &str| -> bool {
35        let r = s.strip_prefix(['+', '-']).unwrap_or(s);
36        !r.is_empty() && r.bytes().all(|c| c.is_ascii_digit())
37    };
38    if let Some(n) = value.find('n') {
39        let prefix = &value[..n];
40        let digits = prefix.strip_prefix(['+', '-']).unwrap_or(prefix);
41        if digits.bytes().all(|c| c.is_ascii_digit()) {
42            let rest = &value[n + 1..];
43            if rest.is_empty() {
44                return Some((Some(prefix.to_string()), None));
45            }
46            if parse_int(rest) {
47                return Some((Some(prefix.to_string()), Some(rest.to_string())));
48            }
49        }
50    }
51    if value.is_empty() {
52        return Some((None, None));
53    }
54    if parse_int(value) {
55        return Some((None, Some(value.to_string())));
56    }
57    None
58}
59
60fn js_sign(n: f64) -> f64 {
61    if n > 0.0 {
62        1.0
63    } else if n < 0.0 {
64        -1.0
65    } else {
66        n
67    }
68}
69
70/// minify the an+b expression of a pseudo class function
71fn minify_nth_expression(arena: &AstArena, func: u32) {
72    let t = |x: u32| arena.data_types.get(x);
73    // pooled buffers: no allocation per selector function
74    let mut chi = PooledVec::new();
75    chi.extend(arena.token_iter(func));
76    let mut list = PooledVec::new();
77    let mut index: isize = 0;
78    while (index as usize) < chi.len() {
79        let c = chi[index as usize];
80        if matches!(t(c), EnumToken::CommentTokenType | EnumToken::WhitespaceTokenType) {
81            index += 1;
82            continue;
83        }
84        if t(c) == EnumToken::IdenTokenType && arena.string_equals_ignore_case(arena.string_value.get(c), "of") {
85            index -= 1;
86            break;
87        }
88        list.push(c);
89        index += 1;
90    }
91    let splice_start = |chi: &mut Vec<u32>, index: isize, items: &[u32]| {
92        let n = index.clamp(0, chi.len() as isize) as usize;
93        chi.splice(0..n, items.iter().copied());
94    };
95    if list.len() == 2 {
96        if t(list[1]) == EnumToken::NumberTokenType {
97            if arena.numeric_value.get(list[1]) == 0.0 {
98                list.truncate(1);
99                if t(list[0]) == EnumToken::DimensionTokenType && arena.numeric_value.get(list[0]) == -2.0 {
100                    arena.numeric_value.set(list[0], 2.0);
101                }
102            } else {
103                let sign = js_sign(arena.numeric_value.get(list[1]));
104                arena.numeric_value.set(list[1], arena.numeric_value.get(list[1]) * sign);
105                let literal = arena.create_token(EnumToken::LiteralTokenType, TokenValue::Str(if sign > 0.0 { "+" } else { "-" }), None);
106                list.insert(1, literal);
107            }
108        }
109        if list.len() == 3
110            && t(list[2]) == EnumToken::NumberTokenType
111            && t(list[0]) == EnumToken::DimensionTokenType
112            && (arena.numeric_value.get(list[0]) == 2.0 || arena.numeric_value.get(list[0]) == -2.0)
113        {
114            let name = if arena.numeric_value.get(list[2]) == 1.0 {
115                Some("odd")
116            } else if arena.numeric_value.get(list[2]) == 0.0 {
117                Some("even")
118            } else {
119                None
120            };
121            if let Some(name) = name {
122                let ident = arena.create_token(EnumToken::IdenTokenType, TokenValue::Str(name), None);
123                arena.copy_location(ident, list[0]);
124                list.splice(0..3, [ident]);
125            }
126        }
127        splice_start(&mut chi, index, &list);
128    }
129    if list.len() == 1 && t(list[0]) == EnumToken::IdenTokenType && arena.string_equals_ignore_case(arena.string_value.get(list[0]), "-n") {
130        arena.string_value.set(list[0], arena.intern_string("n"));
131    }
132    if list.len() == 3
133        && t(list[0]) == EnumToken::IdenTokenType
134        && arena.with_string(arena.string_value.get(list[0]), |v| matches!(v, "n" | "-n" | "+n"))
135        && t(list[1]) == EnumToken::NextSiblingCombinatorTokenType
136        && t(list[2]) == EnumToken::NumberTokenType
137        && arena.numeric_value.get(list[2]) == 0.0
138    {
139        arena.string_value.set(list[0], arena.intern_string("n"));
140        splice_start(&mut chi, index, &[list[0]]);
141        arena.set_token_list(func, &chi);
142        return;
143    }
144    let token = chi.iter().copied().find(|&x| !matches!(t(x), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType));
145    if let Some(token) = token {
146        if matches!(t(token), EnumToken::IdenTokenType | EnumToken::LiteralTokenType) {
147            let val = arena.resolve_string(arena.string_value.get(token));
148            if t(token) == EnumToken::IdenTokenType && (&*val == "odd" || &*val == "even") {
149                if &*val == "even" {
150                    arena.reset_token(token, EnumToken::DimensionTokenType, TokenValue::Num(2.0), Some("n"));
151                }
152            } else if let Some((g2, g3)) = nth_groups(&val) {
153                // `matches[2] === "" ? 1 : matches[2] === "-" ? -1 : +matches[2]` (undefined -> NaN)
154                let a1 = match g2.as_deref() {
155                    Some("") => 1.0,
156                    Some("-") => -1.0,
157                    Some(s) => crate::utils::number::js_parse_number(s),
158                    None => f64::NAN,
159                };
160                let b1 = g3.map_or(f64::NAN, |s| crate::utils::number::js_parse_number(&s));
161                if b1 == 0.0 {
162                    if a1.abs() == 1.0 {
163                        arena.reset_token(token, EnumToken::IdenTokenType, TokenValue::Str("n"), None);
164                    } else {
165                        arena.reset_token(token, EnumToken::DimensionTokenType, TokenValue::Num(a1 * js_sign(a1)), Some("n"));
166                    }
167                }
168            }
169        } else if t(token) == EnumToken::DimensionTokenType {
170            let index = chi.iter().position(|&x| x == token).unwrap();
171            let mut num: Option<u32> = None;
172            let mut i = index + 1;
173            while i < chi.len() {
174                if matches!(t(chi[i]), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType) {
175                    i += 1;
176                    continue;
177                }
178                if t(chi[i]) == EnumToken::NumberTokenType {
179                    num = Some(chi[i]);
180                    break;
181                }
182                i += 1;
183            }
184            if let Some(num) = num {
185                if arena.numeric_value.get(num) == 0.0 {
186                    let end = (i + 1).min(chi.len());
187                    chi.drain(index + 1..end);
188                    if arena.numeric_value.get(token) < 0.0 {
189                        arena.numeric_value.set(token, arena.numeric_value.get(token) * -1.0);
190                    }
191                } else if arena.numeric_value.get(token) == 2.0 && arena.numeric_value.get(num).abs() == 1.0 {
192                    arena.reset_token(token, EnumToken::IdenTokenType, TokenValue::Str("odd"), None);
193                    let end = (i + 1).min(chi.len());
194                    chi.drain(index + 1..end);
195                }
196            }
197        }
198    }
199    arena.set_token_list(func, &chi);
200}
201
202/// split the unicode ranges of a selector: `u+a` is the element `u` followed by the element `a`
203fn split_unicode_ranges(arena: &AstArena, tokens: &mut Vec<u32>) {
204    let mut i = 0;
205    while i < tokens.len() {
206        let token = tokens[i];
207        if arena.data_types.get(token) == EnumToken::UniCodeRange {
208            let text = arena.resolve_string(arena.string_value.get(token));
209            let first: String = text.chars().take(1).collect();
210            let rest: String = text.chars().skip(2).collect();
211            let split = [
212                arena.create_token(EnumToken::IdenTokenType, TokenValue::Str(&first), None),
213                arena.create_token(EnumToken::Plus, TokenValue::Str("+"), None),
214                arena.create_token(if is_ident(&rest) { EnumToken::IdenTokenType } else { EnumToken::LiteralTokenType }, TokenValue::Str(&rest), None),
215            ];
216            for &t in &split {
217                arena.copy_location(t, token);
218            }
219            tokens.splice(i..i + 1, split);
220            i += split.len() - 1;
221        } else if arena.first_token.get(token) != 0 {
222            let mut children = arena.tokens(token);
223            if children.iter().any(|&c| arena.data_types.get(c) == EnumToken::UniCodeRange || arena.first_token.get(c) != 0) {
224                let length = children.len();
225                split_unicode_ranges(arena, &mut children);
226                if children.len() != length {
227                    arena.set_token_list(token, &children);
228                }
229            }
230        }
231        i += 1;
232    }
233}
234
235fn source_of(arena: &AstArena, token: u32) -> u32 {
236    arena.sources.borrow().get(arena.get_source_id(token) as usize).copied().unwrap_or(0)
237}
238
239fn locate(arena: &AstArena, node: u32, tokens: &[u32]) {
240    let (Some(&first), Some(&last)) = (tokens.first(), tokens.last()) else {
241        // typescript: `arena.getSourceId(undefined)` reads index 0
242        arena.set_location(node, Some(source_of(arena, 0)), Some(arena.get_span_start(0)), Some(arena.get_span_end(0)));
243        return;
244    };
245    arena.set_location(node, Some(source_of(arena, first)), Some(arena.get_span_start(first)), Some(arena.get_span_end(last)));
246}
247
248/// true if the token is a keyframe selector: `from`, `to` or a percentage between 0 and 100
249fn is_keyframe_selector_token(arena: &AstArena, token: u32) -> bool {
250    match arena.data_types.get(token) {
251        EnumToken::PercentageTokenType => (0.0..=100.0).contains(&arena.numeric_value.get(token)),
252        EnumToken::IdenTokenType => {
253            let id = arena.string_value.get(token);
254            let code = |k: usize| arena.string_code_at(id, k) | 0x20;
255            // `from` and `to`, case-insensitive
256            match arena.string_length(id) {
257                4 => code(0) == 0x66 && code(1) == 0x72 && code(2) == 0x6f && code(3) == 0x6d,
258                2 => code(0) == 0x74 && code(1) == 0x6f,
259                _ => false,
260            }
261        }
262        _ => false,
263    }
264}
265
266/// true if the selector of a keyframe is a list of `from`, `to` and percentages between 0 and 100, separated by commas
267/// and whitespace: it matches the `keyframe-selectors` syntax
268fn is_simple_keyframe_selector(arena: &AstArena, tokens: &[u32]) -> bool {
269    // a keyframe selector is expected
270    let mut selector = true;
271    for &token in tokens {
272        let typ = arena.data_types.get(token);
273        if typ == EnumToken::WhitespaceTokenType {
274            continue;
275        }
276        if selector {
277            if !is_keyframe_selector_token(arena, token) {
278                return false;
279            }
280        } else if typ != EnumToken::CommaTokenType {
281            return false;
282        }
283        selector = !selector;
284    }
285    !selector
286}
287
288/// parse a selector: a rule or a keyframes rule
289pub fn parse_selector(arena: &AstArena, tokens: &mut Vec<u32>, context: Option<u32>, options: &ParserOptions, errors: &mut Vec<ErrorDescription>) -> u32 {
290    let t = |x: u32| arena.data_types.get(x);
291    let context_type = context.map(t);
292    split_unicode_ranges(arena, tokens);
293    if context_type == Some(EnumToken::KeyframesAtRuleNodeType) {
294        // `from`, `to` and the percentages are valid: the syntax is not matched
295        let (success, result_errors) = if is_simple_keyframe_selector(arena, tokens) {
296            (true, Vec::new())
297        } else {
298            let syntax = get_parsed_syntax(ValidationSyntaxGroupEnum::Syntaxes, "keyframe-selectors");
299            let result = match_all_syntaxes(arena, syntax.as_deref().map(|v| v.as_slice()), &create_validation_context(arena, tokens), options);
300            (result.success, result.errors)
301        };
302        let mut parts = split_token_list_comma(arena, tokens);
303        for part in parts.iter_mut() {
304            trim_array(arena, part);
305            if options.minify == Some(true) {
306                let filtered: Vec<u32> = part.iter().copied().filter(|&x| !matches!(t(x), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType)).collect();
307                if filtered.len() == 1 {
308                    let f = filtered[0];
309                    if t(f) == EnumToken::IdenTokenType && arena.with_string(arena.string_value.get(f), |v| v.eq_ignore_ascii_case("from")) {
310                        arena.reset_token(f, EnumToken::PercentageTokenType, TokenValue::Num(0.0), None);
311                    } else if t(f) == EnumToken::PercentageTokenType && arena.numeric_value.get(f) == 100.0 {
312                        arena.reset_token(f, EnumToken::IdenTokenType, TokenValue::Str("to"), None);
313                    }
314                    *part = filtered;
315                }
316            }
317        }
318        let mut joined: Vec<u32> = Vec::new();
319        for part in &parts {
320            if !joined.is_empty() {
321                joined.push(arena.create_token(EnumToken::CommaTokenType, TokenValue::None, None));
322            }
323            joined.extend_from_slice(part);
324        }
325        *tokens = joined;
326        trim_array(arena, tokens);
327        let render_options = ParserOptions { minify: Some(false), ..Default::default() };
328        let mut seen: Vec<String> = Vec::new();
329        for part in split_token_list_comma(arena, tokens) {
330            let s: String = part.iter().map(|&x| render_value(arena, x, &render_options)).collect();
331            if !seen.contains(&s) {
332                seen.push(s);
333            }
334        }
335        let sel = seen.join(",");
336        let node = arena.create_rule(
337            EnumToken::KeyframesRuleNodeType,
338            StrOrId::Str(&sel),
339            if tokens.is_empty() { None } else { Some(tokens) },
340            if success { EnumAstNodeStatus::Validated } else { EnumAstNodeStatus::Invalid },
341            Some(result_errors),
342        );
343        locate(arena, node, tokens);
344        return node;
345    }
346    let mut stack = PooledVec::new();
347    let mut allowed = true;
348    let mut nested = false;
349    if context_type != Some(EnumToken::StyleSheetNodeType) && context_type != Some(EnumToken::RuleNodeType) {
350        allowed = false;
351        if context_type == Some(EnumToken::AtRuleNodeType) {
352            // computed once per at-rule name: the name is not formatted for each selector
353            allowed = arena.string_derived(arena.name.get(context.unwrap()), StringDerived::AtRuleAcceptsRules, |id| {
354                let rule = get_syntax_rule(ValidationSyntaxGroupEnum::AtRules, &format!("@{}", arena.resolve_string(id)));
355                rule.as_ref().is_some_and(|r| r.accept_any_rule)
356                    || rule.and_then(|r| r.get_block_rules()).is_some_and(|rules| {
357                        rules.iter().any(|r| r.typ == ValidationTokenEnum::PropertyType && matches!(r.val_str(), "block-contents" | "rule-list"))
358                    })
359            });
360        }
361    }
362    let mut parent = context.unwrap_or(0);
363    while parent > 0 {
364        if t(parent) == EnumToken::AtRuleNodeType && arena.string_equals(arena.name.get(parent), "media") {
365            parent = arena.parents.get(parent);
366            continue;
367        }
368        nested = t(parent) == EnumToken::RuleNodeType || (t(parent) == EnumToken::AtRuleNodeType && arena.string_equals(arena.name.get(parent), "mixin"));
369        if nested {
370            break;
371        }
372        parent = arena.parents.get(parent);
373    }
374    // a pooled buffer: it is swapped with the tokens, the buffer of the tokens returns to the pool
375    let mut all = PooledVec::new();
376    all.reserve(tokens.len());
377    let mut read = 0;
378    while read < tokens.len() {
379        let token = tokens[read];
380        let next = tokens.get(read + 1).copied();
381        let nt = next.map(t);
382        if t(token) == EnumToken::ColonTokenType {
383            if nt == Some(EnumToken::IdenTokenType) {
384                let next = next.unwrap();
385                arena.data_types.set(token, EnumToken::PseudoElementTokenType);
386                let id = with_builder(|b| {
387                    b.reset().append_code(0x3a);
388                    arena.append_string(b, arena.string_value.get(next));
389                    arena.intern_builder(b)
390                });
391                arena.string_value.set(token, id);
392                arena.span_location(token, token, next);
393                all.push(token);
394                read += 2;
395                continue;
396            }
397            if nt == Some(EnumToken::FunctionTokenDefType) {
398                let next = next.unwrap();
399                let id = with_builder(|b| {
400                    b.reset().append_code(0x3a);
401                    arena.append_string(b, arena.string_value.get(next));
402                    arena.intern_builder(b)
403                });
404                arena.string_value.set(token, id);
405                // `:name()` is a selector function: looked up once per name
406                arena.data_types.set(
407                    token,
408                    if selector_function_syntax(arena, token).is_some() { EnumToken::PseudoClassFunctionTokenDefType } else { t(next) },
409                );
410                arena.span_location(token, token, next);
411                all.push(token);
412                read += 2;
413                continue;
414            }
415        }
416        if t(token) == EnumToken::DoubleColonTokenType {
417            if nt == Some(EnumToken::IdenTokenType) {
418                let next = next.unwrap();
419                arena.data_types.set(token, EnumToken::PseudoClassTokenType);
420                let single = is_single_colon_pseudo_element(arena, arena.string_value.get(next));
421                let id = with_builder(|b| {
422                    b.reset().append_code(0x3a);
423                    if !single {
424                        b.append_code(0x3a);
425                    }
426                    arena.append_string(b, arena.string_value.get(next));
427                    arena.intern_builder(b)
428                });
429                arena.string_value.set(token, id);
430                arena.span_location(token, token, next);
431                all.push(token);
432                read += 2;
433                continue;
434            }
435            if nt == Some(EnumToken::FunctionTokenDefType) {
436                let next = next.unwrap();
437                let id = with_builder(|b| {
438                    b.reset().append_code(0x3a).append_code(0x3a);
439                    arena.append_string(b, arena.string_value.get(next));
440                    arena.intern_builder(b)
441                });
442                arena.string_value.set(token, id);
443                arena.data_types.set(
444                    token,
445                    if selector_function_syntax(arena, token).is_some() { EnumToken::PseudoClassFunctionTokenDefType } else { EnumToken::FunctionTokenDefType },
446                );
447                arena.span_location(token, token, next);
448                all.push(token);
449                read += 2;
450                continue;
451            }
452        }
453        if t(token) == EnumToken::ColorTokenType {
454            if arena.with_string(arena.string_value.get(token), is_hash) {
455                arena.data_types.set(token, EnumToken::HashTokenType);
456                all.push(token);
457                read += 1;
458                continue;
459            }
460            let sel = render_selector(arena, tokens);
461            let node = arena.create_rule(
462                EnumToken::RuleNodeType,
463                StrOrId::Id(sel),
464                Some(tokens),
465                EnumAstNodeStatus::Invalid,
466                Some(vec![ErrorDescription::drop("invalid hash id").with_node(token)]),
467            );
468            locate(arena, node, tokens);
469            return node;
470        }
471        all.push(token);
472        read += 1;
473    }
474    std::mem::swap(tokens, &mut *all);
475    drop(all);
476    // a selector made of simple selectors is valid, it has no attribute selector and no function
477    let simple = match_simple_selector(arena, tokens);
478    let (success, result_errors) = if simple { (true, Vec::new()) } else { match_selector_syntax(arena, tokens, errors, options, nested) };
479    trim_array(arena, tokens);
480    if success && !simple {
481        let mut i: isize = 0;
482        while (i as usize) < tokens.len() {
483            let token = tokens[i as usize];
484            match t(token) {
485                EnumToken::AttrStartTokenType | EnumToken::PseudoClassFunctionTokenDefType => stack.push(token),
486                EnumToken::AttrEndTokenType => {
487                    if stack.last().is_some_and(|&s| t(s) == EnumToken::AttrStartTokenType) {
488                        let attr = *stack.last().unwrap();
489                        let index = tokens.iter().position(|&x| x == attr).unwrap() as isize;
490                        arena.span_location(attr, attr, token);
491                        tokens.remove(i as usize);
492                        arena.data_types.set(attr, EnumToken::AttrTokenType);
493                        arena.string_value.set(attr, 0);
494                        // the tokens are read in place, then removed
495                        arena.set_token_list(attr, &tokens[(index + 1) as usize..i as usize]);
496                        tokens.drain((index + 1) as usize..i as usize);
497                        i = index;
498                        stack.pop();
499                    }
500                }
501                EnumToken::EndParensTokenType => {
502                    if stack.last().is_some_and(|&s| t(s) == EnumToken::PseudoClassFunctionTokenDefType) {
503                        let func = *stack.last().unwrap();
504                        let index = tokens.iter().position(|&x| x == func).unwrap() as isize;
505                        arena.span_location(func, func, token);
506                        tokens.remove(i as usize);
507                        if is_function_def_type(t(func)) {
508                            arena.data_types.set(func, tokens_func_def_map(t(func)).unwrap_or(0));
509                            // the trimmed range is read in place, then the tokens are removed
510                            let range = &tokens[(index + 1) as usize..i as usize];
511                            let ws = |x: &u32| t(*x) == EnumToken::WhitespaceTokenType;
512                            let start = range.iter().position(|x| !ws(x)).unwrap_or(range.len());
513                            let end = range.iter().rposition(|x| !ws(x)).map_or(start, |e| e + 1);
514                            arena.set_token_list(func, &range[start..end]);
515                            tokens.drain((index + 1) as usize..i as usize);
516                        }
517                        if options.minify == Some(true) {
518                            let is_nth = arena.with_string(arena.string_value.get(func), |n| {
519                                matches!(n, ":nth-child" | ":nth-last-child" | ":nth-of-type" | ":nth-last-of-type")
520                            });
521                            if is_nth {
522                                minify_nth_expression(arena, func);
523                            }
524                        }
525                        i = index;
526                        stack.pop();
527                    }
528                }
529                _ => {}
530            }
531            i += 1;
532        }
533    }
534    let sel = if simple { render_simple_selector(arena, tokens) } else { render_selector(arena, tokens) };
535    let state = if success && allowed {
536        EnumAstNodeStatus::Validated
537    } else if allowed {
538        EnumAstNodeStatus::Invalid
539    } else {
540        EnumAstNodeStatus::Disallowed
541    };
542    let node = arena.create_rule(EnumToken::RuleNodeType, StrOrId::Id(sel), Some(tokens), state, Some(if success { Vec::new() } else { result_errors }));
543    locate(arena, node, tokens);
544    node
545}
546
547/// buffers of the selector rendering, reused
548struct Buffers {
549    pseudo: StringBuilder,
550    part: StringBuilder,
551    selector: StringBuilder,
552    part_offsets: Vec<usize>,
553    selector_offsets: Vec<usize>,
554}
555
556thread_local! {
557    static BUFFERS: RefCell<Buffers> = RefCell::new(Buffers {
558        pseudo: StringBuilder::new(),
559        part: StringBuilder::new(),
560        selector: StringBuilder::new(),
561        part_offsets: Vec::with_capacity(64),
562        selector_offsets: Vec::with_capacity(16),
563    });
564}
565
566fn with_builder<R>(f: impl FnOnce(&mut StringBuilder) -> R) -> R {
567    let mut builder = BUFFERS.with(|b| std::mem::take(&mut b.borrow_mut().pseudo));
568    let result = f(&mut builder);
569    BUFFERS.with(|b| b.borrow_mut().pseudo = builder);
570    result
571}
572
573/// true if ":" + the string is a pseudo element with a single colon syntax (`:before`)
574fn is_single_colon_pseudo_element(arena: &AstArena, id: u32) -> bool {
575    let length = arena.string_length(id);
576    PSEUDO_ELEMENTS.iter().any(|pseudo| {
577        let bytes = pseudo.as_bytes();
578        bytes.len() == length + 1 && bytes[0] == b':' && (0..length).all(|k| arena.string_code_at(id, k) == bytes[k + 1] as u32)
579    })
580}
581
582/// true if the string of a token is a combinator
583fn is_combinator_string(arena: &AstArena, token: Option<u32>) -> bool {
584    let Some(token) = token else {
585        return false;
586    };
587    let id = arena.string_value.get(token);
588    let length = arena.string_length(id);
589    if length == 0 || length > 2 {
590        return false;
591    }
592    COMBINATORS.iter().any(|c| arena.string_equals(id, c))
593}
594
595/// append the rendering of a selector token to the builder
596fn append_selector_token(arena: &AstArena, token: u32, builder: &mut StringBuilder) {
597    if arena.first_token.get(token) == 0 && arena.first_child.get(token) == 0 {
598        let code = match arena.data_types.get(token) {
599            EnumToken::HashTokenType
600            | EnumToken::IdenTokenType
601            | EnumToken::LiteralTokenType
602            | EnumToken::DashedIdenTokenType
603            | EnumToken::ClassSelectorTokenType
604            | EnumToken::PseudoClassTokenType => {
605                arena.append_string(builder, arena.string_value.get(token));
606                return;
607            }
608            EnumToken::WhitespaceTokenType | EnumToken::DescendantCombinatorTokenType => Some(0x20),
609            EnumToken::CommaTokenType => Some(0x2c),
610            EnumToken::Star | EnumToken::UniversalSelectorTokenType => Some(0x2a),
611            EnumToken::NestingSelectorTokenType => Some(0x26),
612            EnumToken::GtTokenType | EnumToken::ChildCombinatorTokenType => Some(0x3e),
613            EnumToken::Plus | EnumToken::NextSiblingCombinatorTokenType => Some(0x2b),
614            EnumToken::Tilda | EnumToken::SubsequentSiblingCombinatorTokenType => Some(0x7e),
615            _ => None,
616        };
617        if let Some(code) = code {
618            builder.append_code(code);
619            return;
620        }
621    }
622    let options = ParserOptions { minify: Some(false), ..Default::default() };
623    builder.append_string(&render_value(arena, token, &options));
624}
625
626fn is_part_code(b: &Buffers, index: isize, count: usize, code: u16) -> bool {
627    if index < 0 || index as usize >= count {
628        return false;
629    }
630    let i = index as usize;
631    let start = b.part_offsets[i * 2];
632    b.part_offsets[i * 2 + 1] - start == 1 && b.part.codes[start] == code
633}
634
635fn is_subclass_part(b: &Buffers, index: usize, count: usize) -> bool {
636    if index >= count || b.part_offsets[index * 2 + 1] == b.part_offsets[index * 2] {
637        return false;
638    }
639    let code = b.part.codes[b.part_offsets[index * 2]];
640    matches!(code, 0x2e | 0x23 | 0x3a | 0x5b)
641}
642
643fn is_type_part(b: &Buffers, index: usize, count: usize) -> bool {
644    if index >= count {
645        return false;
646    }
647    let (start, end) = (b.part_offsets[index * 2], b.part_offsets[index * 2 + 1]);
648    let code = b.part.codes.get(start).copied().unwrap_or(0);
649    if is_part_code(b, index as isize + 1, count, 0x7c) {
650        return false;
651    }
652    if !((0x61..=0x7a).contains(&code) || (0x41..=0x5a).contains(&code) || code == 0x5f || code >= 0x80) {
653        return false;
654    }
655    let c = &b.part.codes;
656    !(end - start == 4 && (c[start] | 0x20) == 0x68 && (c[start + 1] | 0x20) == 0x74 && (c[start + 2] | 0x20) == 0x6d && (c[start + 3] | 0x20) == 0x6c)
657}
658
659/// add the current selector to the selectors of the rule when it is not already present
660fn add_selector_codes(b: &mut Buffers, mut count: usize, selectors: usize) -> usize {
661    let mut i = 0;
662    while i + 1 < count {
663        if is_part_code(b, i as isize, count, 0x2a) && !is_part_code(b, i as isize - 1, count, 0x7c) && is_subclass_part(b, i + 1, count) {
664            b.part_offsets.copy_within((i + 1) * 2..count * 2, i * 2);
665            count -= 1;
666        }
667        i += 1;
668    }
669    if count > 2 && is_part_code(b, 0, count, 0x2a) && is_part_code(b, 1, count, 0x20) && is_type_part(b, 2, count) {
670        b.part_offsets.copy_within(4..count * 2, 0);
671        count -= 2;
672    }
673    let start = b.selector.len() + if selectors > 0 { 1 } else { 0 };
674    if selectors > 0 {
675        b.selector.append_code(0x2c);
676    }
677    for i in 0..count {
678        let (ts, te) = (b.part_offsets[i * 2], b.part_offsets[i * 2 + 1]);
679        for k in ts..te {
680            let c = b.part.codes[k];
681            b.selector.append_code(c);
682        }
683    }
684    let end = b.selector.len();
685    for k in 0..selectors {
686        let (s, e) = (b.selector_offsets[k * 2], b.selector_offsets[k * 2 + 1]);
687        if e - s == end - start && b.selector.codes[s..e] == b.selector.codes[start..end] {
688            b.selector.codes.truncate(if selectors > 0 { start - 1 } else { start });
689            return selectors;
690        }
691    }
692    if b.selector_offsets.len() < (selectors + 1) * 2 {
693        b.selector_offsets.resize((selectors + 1) * 2, 0);
694    }
695    b.selector_offsets[selectors * 2] = start;
696    b.selector_offsets[selectors * 2 + 1] = end;
697    selectors + 1
698}
699
700/// selector of a rule made of simple selectors (see [`match_simple_selector`]), without the leading and the trailing
701/// whitespace: the string of a single token is used as is, a compound or a complex selector is built without
702/// [`render_selector`]. a selector list is rendered with [`render_selector`]: the duplicate selectors are removed
703fn render_simple_selector(arena: &AstArena, tokens: &[u32]) -> u32 {
704    // rendered as their string by append_selector_token()
705    if tokens.len() == 1 && arena.data_types.get(tokens[0]) != EnumToken::PseudoElementTokenType {
706        return arena.string_value.get(tokens[0]);
707    }
708    if tokens.iter().any(|&x| arena.data_types.get(x) == EnumToken::CommaTokenType) {
709        return render_selector(arena, tokens);
710    }
711    let mut selector = BUFFERS.with(|b| std::mem::take(&mut b.borrow_mut().selector));
712    selector.reset();
713    for &token in tokens {
714        append_selector_token(arena, token, &mut selector);
715    }
716    let id = arena.intern_builder(&selector);
717    BUFFERS.with(|b| b.borrow_mut().selector = selector);
718    id
719}
720
721/// selector of a rule: the distinct comma separated selectors, interned. no string is created
722pub fn render_selector(arena: &AstArena, tokens: &[u32]) -> u32 {
723    let mut b = BUFFERS.with(|b| {
724        let mut buffers = b.borrow_mut();
725        Buffers {
726            pseudo: std::mem::take(&mut buffers.pseudo),
727            part: std::mem::take(&mut buffers.part),
728            selector: std::mem::take(&mut buffers.selector),
729            part_offsets: std::mem::take(&mut buffers.part_offsets),
730            selector_offsets: std::mem::take(&mut buffers.selector_offsets),
731        }
732    });
733    let mut count = 0usize;
734    let mut selectors = 0usize;
735    b.part.reset();
736    b.selector.reset();
737    b.part_offsets.clear();
738    let typ = |i: isize| if i < 0 { None } else { tokens.get(i as usize).map(|&x| arena.data_types.get(x)) };
739    for (index, &curr) in tokens.iter().enumerate() {
740        let i = index as isize;
741        let t = arena.data_types.get(curr);
742        if t == EnumToken::WhitespaceTokenType
743            && (typ(i - 1).is_some_and(is_trim_white_space)
744                || typ(i + 1).is_some_and(is_trim_white_space)
745                || is_combinator_string(arena, if index > 0 { Some(tokens[index - 1]) } else { None })
746                || is_combinator_string(arena, tokens.get(index + 1).copied()))
747        {
748            continue;
749        }
750        if t == EnumToken::CommaTokenType {
751            selectors = add_selector_codes(&mut b, count, selectors);
752            count = 0;
753            b.part.reset();
754            b.part_offsets.clear();
755            continue;
756        }
757        let start = b.part.len();
758        let mut part = std::mem::take(&mut b.part);
759        append_selector_token(arena, curr, &mut part);
760        b.part = part;
761        if b.part.len() - start == 1 && b.part.codes[start] == 0x2c {
762            b.part.codes.truncate(start);
763            selectors = add_selector_codes(&mut b, count, selectors);
764            count = 0;
765            b.part.reset();
766            b.part_offsets.clear();
767            continue;
768        }
769        if b.part_offsets.len() < (count + 1) * 2 {
770            b.part_offsets.resize((count + 1) * 2, 0);
771        }
772        b.part_offsets[count * 2] = start;
773        b.part_offsets[count * 2 + 1] = b.part.len();
774        count += 1;
775    }
776    add_selector_codes(&mut b, count, selectors);
777    let id = arena.intern_builder(&b.selector);
778    BUFFERS.with(|buffers| {
779        let mut buffers = buffers.borrow_mut();
780        buffers.pseudo = b.pseudo;
781        buffers.part = b.part;
782        buffers.selector = b.selector;
783        buffers.part_offsets = b.part_offsets;
784        buffers.selector_offsets = b.selector_offsets;
785    });
786    id
787}
788
789#[allow(dead_code)]
790fn _unused(a: &str, b: &str) -> bool {
791    equals_ignore_case(a, b)
792}