Skip to main content

rust_css_parser/validation/
match_.rs

1//! Port of `src/validation/match.ts` (`match` is a rust keyword: the module is `match_`).
2//!
3//! Matches value tokens of the arena against the parsed value definition syntaxes.
4//!
5//! - a [`Context`] is a shared mutable cursor (`Rc<RefCell<..>>`, like the typescript context objects that are passed
6//!   around and advanced in place). `slice()` shares the token buffer (offset), it does not copy the tokens
7//! - syntax identity (typescript object identity) is the `Rc` address; the stacks keep the syntaxes alive
8
9use super::config::{get_parsed_syntax, get_syntax_config};
10use super::first::{is_nullable, matching_alternatives, may_start_with};
11use super::parser::typedef::{MediaFeatureType, ValidationSyntaxGroupEnum, ValidationTokenEnum as V};
12use super::parser::types::{MatchMax, ValidationToken};
13use crate::ast::arena::AstArena;
14use crate::ast::strings::StringDerived;
15use crate::ast::types::EnumToken;
16use crate::options::ParserOptions;
17use crate::parser::utils::text::equals_ignore_case;
18use crate::syntax::constants::{is_function_def_type, TOKENS_FUNC_DEF_MAP};
19use crate::types::{ErrorAction, ErrorDescription, ErrorSyntax};
20use std::cell::RefCell;
21use crate::utils::fx::HashMap;
22use std::rc::Rc;
23use std::sync::OnceLock;
24
25pub type Syntax = Rc<ValidationToken>;
26
27/// css wide keywords (`all` syntax)
28fn all_values() -> &'static [String] {
29    static VALUES: OnceLock<Vec<String>> = OnceLock::new();
30    VALUES.get_or_init(|| {
31        get_syntax_config()["declarations"]["all"]["syntax"]
32            .as_str()
33            .unwrap_or("")
34            .split(|c: char| c.is_whitespace() || c == '|')
35            .filter(|s| !s.is_empty())
36            .map(String::from)
37            .collect()
38    })
39}
40
41/// true if the value is a css wide keyword, ignoring the case
42pub fn is_css_wide_keyword(value: &str) -> bool {
43    all_values().iter().any(|v| equals_ignore_case(v, value))
44}
45
46pub const SELECTOR_NODE_TYPES: [u8; 5] = [
47    EnumToken::CommaTokenType,
48    EnumToken::ColumnCombinatorTokenType,
49    EnumToken::ChildCombinatorTokenType,
50    EnumToken::NextSiblingCombinatorTokenType,
51    EnumToken::SubsequentSiblingCombinatorTokenType,
52];
53
54fn trim_whitespace_before(t: u8) -> bool {
55    SELECTOR_NODE_TYPES.contains(&t)
56        || matches!(
57            t,
58            EnumToken::DelimTokenType
59                | EnumToken::DashMatchTokenType
60                | EnumToken::IncludeMatchTokenType
61                | EnumToken::ContainMatchTokenType
62                | EnumToken::StartMatchTokenType
63                | EnumToken::EndMatchTokenType
64                | EnumToken::AttrEndTokenType
65        )
66}
67
68fn trim_whitespace_after(t: u8) -> bool {
69    SELECTOR_NODE_TYPES.contains(&t)
70        || matches!(
71            t,
72            EnumToken::DelimTokenType
73                | EnumToken::DashMatchTokenType
74                | EnumToken::IncludeMatchTokenType
75                | EnumToken::ContainMatchTokenType
76                | EnumToken::StartMatchTokenType
77                | EnumToken::EndMatchTokenType
78                | EnumToken::AttrStartTokenType
79        )
80}
81
82/// `funcTypes`: the function token types
83pub fn is_func_type(t: u8) -> bool {
84    TOKENS_FUNC_DEF_MAP.iter().any(|(_, v)| *v == t) || t == EnumToken::FunctionTokenType || t == EnumToken::PseudoClassFuncTokenType
85}
86
87/// trim leading and trailing whitespace
88pub fn trim_array(arena: &AstArena, tokens: &mut Vec<u32>) {
89    let start = tokens.iter().position(|&t| arena.data_types.get(t) != EnumToken::WhitespaceTokenType).unwrap_or(tokens.len());
90    tokens.drain(..start);
91    while tokens.last().is_some_and(|&t| arena.data_types.get(t) == EnumToken::WhitespaceTokenType) {
92        tokens.pop();
93    }
94}
95
96/// true if the token is a simple selector without arguments: a type (`a`), an id (`#a`), a class (`.a`), a
97/// pseudo-class (`:hover`) or a pseudo-element (`::before`)
98fn is_simple_selector_token(t: u8) -> bool {
99    matches!(
100        t,
101        EnumToken::ClassSelectorTokenType
102            | EnumToken::IdenTokenType
103            | EnumToken::PseudoElementTokenType
104            | EnumToken::PseudoClassTokenType
105            | EnumToken::HashTokenType
106    )
107}
108
109/// match a selector made of simple selectors (see [`is_simple_selector_token`]), separated by whitespace (the
110/// descendant combinator) and by commas: `.a:hover`, `.a .b`, `.a, #b`. such a selector is valid: the whitespace
111/// around the commas is removed, the tokens are the tokens produced by [`match_selector_syntax`]. the tokens of
112/// another selector are not changed. returns true if the selector is made of simple selectors
113pub fn match_simple_selector(arena: &AstArena, tokens: &mut Vec<u32>) -> bool {
114    let t = |x: u32| arena.data_types.get(x);
115    // a simple selector is expected: at the start of the selector and after a comma
116    let mut expected = true;
117    let mut comma_whitespace = false;
118    for i in 0..tokens.len() {
119        let typ = t(tokens[i]);
120        if is_simple_selector_token(typ) {
121            expected = false;
122            continue;
123        }
124        if typ == EnumToken::WhitespaceTokenType {
125            // leading whitespace
126            if i == 0 {
127                return false;
128            }
129            // whitespace after a comma or before a comma
130            if expected || tokens.get(i + 1).is_some_and(|&x| t(x) == EnumToken::CommaTokenType) {
131                comma_whitespace = true;
132            }
133            continue;
134        }
135        if typ != EnumToken::CommaTokenType || expected {
136            return false;
137        }
138        expected = true;
139    }
140    if expected {
141        return false;
142    }
143    if comma_whitespace {
144        let original: Vec<u32> = tokens.clone();
145        tokens.clear();
146        for (i, &token) in original.iter().enumerate() {
147            if t(token) == EnumToken::WhitespaceTokenType
148                && ((i > 0 && t(original[i - 1]) == EnumToken::CommaTokenType)
149                    || original.get(i + 1).is_some_and(|&x| t(x) == EnumToken::CommaTokenType))
150            {
151                continue;
152            }
153            tokens.push(token);
154        }
155    }
156    true
157}
158
159/// `ValidationMediaFeature`
160pub fn get_mf_info(feature_name: &str) -> Option<&'static serde_json::Value> {
161    get_syntax_config()["mediaFeatures"].get(feature_name.to_lowercase())
162}
163
164/// result of [`is_mf_value`]
165#[derive(Clone, Copy, Debug, PartialEq, Eq)]
166pub struct MFValue {
167    pub valid: bool,
168    pub success: bool,
169    pub is_value_allowed: Option<bool>,
170}
171
172/// validate a media feature value
173pub fn is_mf_value(arena: &AstArena, feature_name: &str, tokens: &[u32], is_mf_range: bool) -> MFValue {
174    let tokens: Vec<u32> = tokens
175        .iter()
176        .copied()
177        .filter(|&t| !matches!(arena.data_types.get(t), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType))
178        .collect();
179    if feature_name.starts_with("--") || (is_mf_range && (feature_name.starts_with("min-") || feature_name.starts_with("max-"))) {
180        return MFValue { valid: true, success: false, is_value_allowed: Some(false) };
181    }
182    let Some(feature) = get_mf_info(feature_name) else {
183        return MFValue { valid: false, success: false, is_value_allowed: None };
184    };
185    let t = |i: usize| tokens.get(i).map_or(0, |&x| arena.data_types.get(x));
186    let one = tokens.len() == 1;
187    let success = match feature["type"].as_str().unwrap_or("") {
188        MediaFeatureType::BooleanType => {
189            one && t(0) == EnumToken::NumberTokenType && matches!(arena.numeric_value.get(tokens[0]), v if v == 0.0 || v == 1.0)
190        }
191        MediaFeatureType::KeywordType => {
192            one && t(0) == EnumToken::IdenTokenType && {
193                let v = arena.resolve_string(arena.string_value.get(tokens[0])).to_lowercase();
194                feature["values"].as_array().is_some_and(|a| a.iter().any(|x| x.as_str() == Some(v.as_str())))
195            }
196        }
197        MediaFeatureType::LengthType => {
198            one && (t(0) == EnumToken::LengthTokenType
199                || (t(0) == EnumToken::NumberTokenType && arena.numeric_value.get(tokens[0]) == 0.0 && !arena.has_fraction(tokens[0])))
200        }
201        MediaFeatureType::IntergerType => {
202            one && t(0) == EnumToken::NumberTokenType && !crate::utils::number::js_number_to_string(arena.numeric_value.get(tokens[0])).contains('.')
203        }
204        MediaFeatureType::NumberType => one && t(0) == EnumToken::NumberTokenType && !arena.has_fraction(tokens[0]),
205        MediaFeatureType::StringType => one && t(0) == EnumToken::StringTokenType,
206        MediaFeatureType::ResolutionType => one && t(0) == EnumToken::ResolutionTokenType,
207        MediaFeatureType::RatioType => {
208            (one && t(0) == EnumToken::NumberTokenType)
209                || (tokens.len() == 3
210                    && t(0) == EnumToken::NumberTokenType
211                    && !arena.has_fraction(tokens[0])
212                    && t(1) == EnumToken::LiteralTokenType
213                    && arena.string_equals(arena.string_value.get(tokens[1]), "/")
214                    && t(2) == EnumToken::NumberTokenType
215                    && !arena.has_fraction(tokens[2]))
216        }
217        _ => true,
218    };
219    MFValue { valid: true, success, is_value_allowed: None }
220}
221
222// ---------------------------------------------------------------------------------------------------------------------
223// validation context
224// ---------------------------------------------------------------------------------------------------------------------
225
226/// cursor over the tokens being validated
227#[derive(Clone, Debug)]
228pub struct ContextData {
229    buffer: Rc<[u32]>,
230    start: usize,
231    pub index: isize,
232}
233
234/// shared validation context (`ValidationContext`)
235pub type Context = Rc<RefCell<ContextData>>;
236
237fn is_skipped(arena: &AstArena, token: u32) -> bool {
238    matches!(arena.data_types.get(token), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType | EnumToken::CDOCOMMTokenType)
239}
240
241impl ContextData {
242    fn new(tokens: Vec<u32>, index: isize) -> Self {
243        Self { buffer: Rc::from(tokens), start: 0, index }
244    }
245
246    /// a context over tokens, at an index (the compiled matchers, see `validation::compiled::runtime`)
247    pub(crate) fn from_tokens(tokens: Vec<u32>, index: isize) -> Self {
248        Self::new(tokens, index)
249    }
250
251    /// the tokens of the context
252    #[inline]
253    pub fn tokens(&self) -> &[u32] {
254        &self.buffer[self.start..]
255    }
256
257    #[inline]
258    fn get(&self, index: isize) -> Option<u32> {
259        if index < 0 {
260            None
261        } else {
262            self.tokens().get(index as usize).copied()
263        }
264    }
265
266    /// `current()`
267    pub fn current(&self) -> Option<u32> {
268        if self.index < 0 {
269            None
270        } else {
271            self.get(self.index)
272        }
273    }
274
275    /// `peek(offset)`: the next significant token
276    pub fn peek(&self, arena: &AstArena, mut offset: isize) -> Option<u32> {
277        let len = self.tokens().len() as isize;
278        let mut index = self.index + 1;
279        let mut token = self.get(index);
280        while offset >= 0 && index < len {
281            while token.is_some_and(|t| is_skipped(arena, t)) {
282                index += 1;
283                token = self.get(index);
284            }
285            if token.is_none() || offset == 0 {
286                return token;
287            }
288            offset -= 1;
289            index += 1;
290            token = self.get(index);
291        }
292        token
293    }
294
295    /// `peekRange(close, counter)`: the tokens until the closing token (balanced parentheses and braces)
296    pub fn peek_range(&self, arena: &AstArena, close: u8, mut counter: i32) -> Vec<u32> {
297        let tokens = self.tokens();
298        let len = tokens.len() as isize;
299        let mut index = self.index;
300        let mut match_count = 0i32;
301        let mut block_count = 0i32;
302        let mut result = Vec::new();
303        while index + 1 < len && arena.data_types.get(tokens[(index + 1) as usize]) == EnumToken::WhitespaceTokenType {
304            index += 1;
305        }
306        while index + 1 < len {
307            index += 1;
308            let token = tokens[index as usize];
309            let t = arena.data_types.get(token);
310            if t == EnumToken::StartParensTokenType || is_function_def_type(t) {
311                match_count += 1;
312            } else if t == EnumToken::EndParensTokenType {
313                match_count -= 1;
314            } else if t == EnumToken::BlockStartTokenType {
315                block_count += 1;
316            } else if t == EnumToken::BlockEndTokenType && block_count > 0 {
317                block_count -= 1;
318            }
319            if match_count >= 0 {
320                result.push(token);
321            }
322            if match_count == 0 && block_count == 0 && close != EnumToken::EndParensTokenType && t == close {
323                counter -= 1;
324            }
325            if match_count <= 0 && counter <= 0 {
326                break;
327            }
328        }
329        result
330    }
331
332    /// `split(split)`: the remaining tokens split by a token type (balanced parentheses)
333    pub fn split(&self, arena: &AstArena, split: u8) -> Vec<Vec<u32>> {
334        let tokens = self.tokens();
335        let mut index = self.index;
336        let mut match_count = 0i32;
337        let mut result: Vec<Vec<u32>> = vec![Vec::new()];
338        while index + 1 < tokens.len() as isize {
339            index += 1;
340            let token = tokens[index as usize];
341            let t = arena.data_types.get(token);
342            if t == EnumToken::StartParensTokenType || is_function_def_type(t) {
343                match_count += 1;
344            } else if t == EnumToken::EndParensTokenType {
345                match_count -= 1;
346            }
347            result.last_mut().unwrap().push(token);
348            if match_count == 0 && t == split {
349                result.push(Vec::new());
350            }
351        }
352        result
353    }
354
355    pub fn get_remaining_tokens(&self) -> Vec<u32> {
356        let start = (self.index + 1).max(0) as usize;
357        self.tokens().get(start..).map_or_else(Vec::new, |s| s.to_vec())
358    }
359
360    pub fn end(&mut self) {
361        self.index = self.tokens().len() as isize + 1;
362    }
363
364    /// `next()`: the next significant token
365    pub fn next(&mut self, arena: &AstArena) -> Option<u32> {
366        self.index += 1;
367        let mut token = self.get(self.index);
368        while token.is_some_and(|t| {
369            matches!(
370                arena.data_types.get(t),
371                EnumToken::WhitespaceTokenType
372                    | EnumToken::CommentTokenType
373                    | EnumToken::CDOCOMMTokenType
374                    | EnumToken::BadCdoTokenType
375                    | EnumToken::BadCommentTokenType
376                    | EnumToken::BadStringTokenType
377            )
378        }) {
379            self.index += 1;
380            token = self.get(self.index);
381        }
382        token
383    }
384
385    /// `slice()`: a new context over the tokens from the current one (shared buffer)
386    pub fn slice(&self) -> ContextData {
387        if self.index == -1 {
388            ContextData { buffer: self.buffer.clone(), start: self.start, index: -1 }
389        } else {
390            let start = (self.start as isize + self.index).clamp(0, self.buffer.len() as isize) as usize;
391            ContextData { buffer: self.buffer.clone(), start, index: 0 }
392        }
393    }
394
395    /// `update(token)`: move to a token
396    pub fn update(&mut self, token: Option<u32>) {
397        if let Some(token) = token {
398            if let Some(index) = self.tokens().iter().position(|&t| t == token) {
399                self.index = index as isize;
400            }
401        }
402    }
403
404    /// `done()`: no significant token left
405    pub fn done(&self, arena: &AstArena) -> bool {
406        let tokens = self.tokens();
407        let mut index = self.index + 1;
408        while index < tokens.len() as isize {
409            if matches!(arena.data_types.get(tokens[index as usize]), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType) {
410                index += 1;
411            } else {
412                return false;
413            }
414        }
415        true
416    }
417}
418
419/// context helpers on the shared handle
420pub trait ContextExt {
421    fn current(&self) -> Option<u32>;
422    fn peek(&self, arena: &AstArena) -> Option<u32>;
423    fn next_token(&self, arena: &AstArena) -> Option<u32>;
424    fn done(&self, arena: &AstArena) -> bool;
425    fn end(&self);
426    fn update(&self, token: Option<u32>);
427    fn slice(&self) -> Context;
428    fn tokens(&self) -> Vec<u32>;
429    fn index(&self) -> isize;
430}
431
432impl ContextExt for Context {
433    fn current(&self) -> Option<u32> {
434        self.borrow().current()
435    }
436
437    fn peek(&self, arena: &AstArena) -> Option<u32> {
438        self.borrow().peek(arena, 0)
439    }
440
441    fn next_token(&self, arena: &AstArena) -> Option<u32> {
442        self.borrow_mut().next(arena)
443    }
444
445    fn done(&self, arena: &AstArena) -> bool {
446        self.borrow().done(arena)
447    }
448
449    fn end(&self) {
450        self.borrow_mut().end();
451    }
452
453    fn update(&self, token: Option<u32>) {
454        self.borrow_mut().update(token);
455    }
456
457    fn slice(&self) -> Context {
458        Rc::new(RefCell::new(self.borrow().slice()))
459    }
460
461    fn tokens(&self) -> Vec<u32> {
462        self.borrow().tokens().to_vec()
463    }
464
465    fn index(&self) -> isize {
466        self.borrow().index
467    }
468}
469
470/// create a validation context: the comments are removed, the whitespace and `!important` are trimmed
471pub fn create_validation_context(arena: &AstArena, tokens: &[u32]) -> Context {
472    let t = |x: u32| arena.data_types.get(x);
473    if !tokens.iter().any(|&x| t(x) == EnumToken::CommentTokenType) {
474        // no comment: the trimmed range is copied once into the shared buffer of the context
475        let mut start = 0;
476        let mut end = tokens.len();
477        while start < end && t(tokens[start]) == EnumToken::WhitespaceTokenType {
478            start += 1;
479        }
480        while end > start && t(tokens[end - 1]) == EnumToken::WhitespaceTokenType {
481            end -= 1;
482        }
483        if end > start && t(tokens[end - 1]) == EnumToken::ImportantTokenType {
484            end -= 1;
485            while end > start && t(tokens[end - 1]) == EnumToken::WhitespaceTokenType {
486                end -= 1;
487            }
488        }
489        return Rc::new(RefCell::new(ContextData { buffer: Rc::from(&tokens[start..end]), start: 0, index: -1 }));
490    }
491    let mut filtered: Vec<u32> = tokens.iter().copied().filter(|&t| arena.data_types.get(t) != EnumToken::CommentTokenType).collect();
492    trim_array(arena, &mut filtered);
493    if filtered.last().is_some_and(|&t| arena.data_types.get(t) == EnumToken::ImportantTokenType) {
494        filtered.pop();
495        trim_array(arena, &mut filtered);
496    }
497    Rc::new(RefCell::new(ContextData::new(filtered, -1)))
498}
499
500// ---------------------------------------------------------------------------------------------------------------------
501// results
502// ---------------------------------------------------------------------------------------------------------------------
503
504/// result of a match (`ValidationMatch`)
505#[derive(Clone, Debug)]
506pub struct ValidationMatch {
507    pub success: bool,
508    pub valid: bool,
509    pub token: Option<u32>,
510    pub context: Option<Context>,
511    pub syntax_token: Option<Syntax>,
512    pub errors: Vec<ErrorDescription>,
513}
514
515impl ValidationMatch {
516    pub fn new(success: bool, valid: bool, token: Option<u32>, context: Option<Context>, syntax_token: Option<Syntax>, errors: Vec<ErrorDescription>) -> Self {
517        Self { success, valid, token, context, syntax_token, errors }
518    }
519
520    /// the context of the result (contexts are always set, except for the cached results)
521    pub fn ctx(&self) -> &Context {
522        self.context.as_ref().expect("validation context")
523    }
524}
525
526/// `[file, line, column]` of a token
527pub fn token_location(arena: &AstArena, token: u32, options: &ParserOptions) -> Option<(Option<Rc<str>>, u32, u32)> {
528    let source = options.source.as_ref()?;
529    let (line, column) = source.line_starts.borrow().get_offsets(arena.get_span_start(token));
530    Some((source.file.clone(), line, column))
531}
532
533/// a "drop" error of a token, with its location
534pub fn drop_error(arena: &AstArena, message: String, token: u32, options: &ParserOptions) -> ErrorDescription {
535    let mut error = ErrorDescription::drop(message).with_node(token);
536    error.location = token_location(arena, token, options);
537    error
538}
539
540/// `EnumToken[type]`
541pub fn token_type_name(t: u8) -> &'static str {
542    EnumToken::name(t).unwrap_or("undefined")
543}
544
545// ---------------------------------------------------------------------------------------------------------------------
546// selectors
547// ---------------------------------------------------------------------------------------------------------------------
548
549/// match a selector: the tokens are checked and normalized in place (combinators, whitespace)
550pub fn match_selector_syntax(
551    arena: &AstArena,
552    stream: &mut Vec<u32>,
553    errors: &mut Vec<ErrorDescription>,
554    options: &ParserOptions,
555    nested: bool,
556) -> (bool, Vec<ErrorDescription>) {
557    let fail = |message: String, token: u32| (false, vec![drop_error(arena, message, token, options)]);
558    // pooled buffers: the tokens are swapped with the stream, the buffer of the stream returns to the pool
559    let mut stack = crate::utils::pool::PooledVec::new();
560    let mut tokens = crate::utils::pool::PooledVec::new();
561    tokens.reserve(stream.len());
562    let mut i = 0usize;
563    let mut success = true;
564    let t = |x: u32| arena.data_types.get(x);
565    let top = |stack: &Vec<u32>| stack.last().map(|&x| t(x));
566    while i < stream.len() && matches!(t(stream[i]), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType) {
567        i += 1;
568    }
569    if i < stream.len() {
570        match t(stream[i]) {
571            EnumToken::Plus
572            | EnumToken::Tilda
573            | EnumToken::GtTokenType
574            | EnumToken::ColumnCombinatorTokenType
575            | EnumToken::ChildCombinatorTokenType
576            | EnumToken::NextSiblingCombinatorTokenType
577            | EnumToken::SubsequentSiblingCombinatorTokenType => {
578                if !nested {
579                    return fail(format!("Unexpected token {}", token_type_name(t(stream[i]))), stream[i]);
580                }
581            }
582            _ => {}
583        }
584    }
585    while i < stream.len() {
586        let token = stream[i];
587        if t(token) == EnumToken::Star {
588            arena.data_types.set(token, EnumToken::UniversalSelectorTokenType);
589        }
590        tokens.push(token);
591        if is_function_def_type(t(token)) {
592            if top(&stack).is_some_and(|x| SELECTOR_NODE_TYPES.contains(&x)) {
593                stack.pop();
594            }
595            stack.push(token);
596            i += 1;
597            continue;
598        }
599        if top(&stack).is_some_and(|x| SELECTOR_NODE_TYPES.contains(&x))
600            && !SELECTOR_NODE_TYPES.contains(&t(token))
601            && !matches!(t(token), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType | EnumToken::CDOCOMMTokenType)
602        {
603            stack.pop();
604        }
605        match t(token) {
606            EnumToken::PseudoClassFuncTokenType => {
607                let syntax = selector_function_syntax(arena, token);
608                // the children of the syntax are borrowed: the parsed syntax is shared (Rc)
609                let chi: &[Syntax] = syntax.as_ref().and_then(|s| s.first()).map_or(&[], |f| f.children());
610                let result = match_all_syntaxes(arena, Some(chi), &create_validation_context(arena, &arena.tokens(token)), options);
611                if !result.success {
612                    success = false;
613                    errors.extend(result.errors);
614                }
615            }
616            EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType | EnumToken::CDOCOMMTokenType => {}
617            EnumToken::NestingSelectorTokenType => {
618                if !nested && options.nested_rule != Some(true) {
619                    return fail("Nesting selector is not allowed".into(), token);
620                }
621            }
622            EnumToken::Plus => {
623                arena.data_types.set(token, EnumToken::NextSiblingCombinatorTokenType);
624                stack.push(token);
625            }
626            EnumToken::Tilda => arena.data_types.set(token, EnumToken::SubsequentSiblingCombinatorTokenType),
627            EnumToken::GtTokenType => arena.data_types.set(token, EnumToken::ChildCombinatorTokenType),
628            EnumToken::UniversalSelectorTokenType => {}
629            EnumToken::ColumnCombinatorTokenType
630            | EnumToken::ChildCombinatorTokenType
631            | EnumToken::DescendantCombinatorTokenType
632            | EnumToken::NextSiblingCombinatorTokenType
633            | EnumToken::SubsequentSiblingCombinatorTokenType => {
634                if stream.get(i + 1).is_some_and(|&n| t(n) == EnumToken::WhitespaceTokenType) {
635                    i += 1;
636                }
637                if top(&stack) == Some(EnumToken::UniversalSelectorTokenType) {
638                    stack.pop();
639                }
640                if top(&stack).is_some_and(|x| SELECTOR_NODE_TYPES.contains(&x)) {
641                    return fail(format!("Unexpected combinator {}", token_type_name(t(token))), token);
642                }
643                stack.push(token);
644            }
645            EnumToken::CommaTokenType => {
646                if top(&stack) == Some(EnumToken::UniversalSelectorTokenType) {
647                    stack.pop();
648                }
649                stack.push(token);
650            }
651            EnumToken::PipeTokenType
652            | EnumToken::DelimTokenType
653            | EnumToken::StringTokenType
654            | EnumToken::IncludeMatchTokenType
655            | EnumToken::ContainMatchTokenType
656            | EnumToken::StartMatchTokenType
657            | EnumToken::EndMatchTokenType
658            | EnumToken::DashMatchTokenType
659            | EnumToken::IdenTokenType
660            | EnumToken::HashTokenType
661            | EnumToken::PseudoElementTokenType
662            | EnumToken::PseudoClassTokenType
663            | EnumToken::ClassSelectorTokenType => {}
664            EnumToken::AttrStartTokenType => stack.push(token),
665            EnumToken::AttrEndTokenType => {
666                if top(&stack) == Some(EnumToken::UniversalSelectorTokenType) {
667                    stack.pop();
668                }
669                if top(&stack) != Some(EnumToken::AttrStartTokenType) {
670                    return fail(format!("Unexpected token {}", token_type_name(t(token))), token);
671                }
672                let k = tokens.len() - 1;
673                let index = tokens.iter().position(|&x| Some(x) == stack.last().copied()).map_or(-1, |p| p as isize);
674                let mut slice: Vec<u32> = Vec::new();
675                for n in (index + 1) as usize..k {
676                    if matches!(t(tokens[n]), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType | EnumToken::CDOCOMMTokenType) {
677                        continue;
678                    }
679                    slice.push(tokens[n]);
680                }
681                let ty = |s: &Vec<u32>, i: usize| s.get(i).map(|&x| t(x));
682                if ty(&slice, 1) == Some(EnumToken::PipeTokenType) {
683                    slice.remove(0);
684                }
685                if ty(&slice, 0) == Some(EnumToken::PipeTokenType) {
686                    slice.remove(0);
687                }
688                if slice.len() == 1 {
689                    stack.pop();
690                } else {
691                    for _ in 0..2 {
692                        if !slice.is_empty() {
693                            slice.remove(0);
694                        }
695                    }
696                    if ty(&slice, 0) == Some(EnumToken::StringTokenType) {
697                        let value = arena.resolve_string(arena.string_value.get(slice[0]));
698                        let inner: String = {
699                            let chars: Vec<char> = value.chars().collect();
700                            if chars.len() >= 2 { chars[1..chars.len() - 1].iter().collect() } else { String::new() }
701                        };
702                        if !inner.is_empty() && inner.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') {
703                            arena.string_value.set(slice[0], arena.intern_string(&inner));
704                            arena.data_types.set(slice[0], EnumToken::IdenTokenType);
705                        }
706                    }
707                    if !slice.is_empty() {
708                        slice.remove(0);
709                    }
710                    if slice.is_empty() {
711                        stack.pop();
712                    } else {
713                        let s0 = slice[0];
714                        if t(s0) != EnumToken::IdenTokenType
715                            || (!arena.string_equals(arena.string_value.get(s0), "i") && !arena.string_equals(arena.string_value.get(s0), "s"))
716                        {
717                            return fail(format!("Unexpected token {}", token_type_name(t(s0))), s0);
718                        }
719                        stack.pop();
720                    }
721                }
722            }
723            EnumToken::StartParensTokenType => {
724                return fail(format!("Unexpected token {}", token_type_name(t(token))), token);
725            }
726            EnumToken::EndParensTokenType => {
727                if top(&stack) == Some(EnumToken::UniversalSelectorTokenType) {
728                    stack.pop();
729                }
730                if matches!(top(&stack), Some(EnumToken::PseudoClassFunctionTokenDefType) | Some(EnumToken::PseudoElementTokenType)) {
731                    let func = *stack.last().unwrap();
732                    let index = tokens.iter().position(|&x| x == func).map_or(-1, |p| p as isize);
733                    // looked up once per function name (`:name()`), the children of the syntax are borrowed
734                    let syntax = selector_function_syntax(arena, func);
735                    let chi: &[Syntax] = syntax.as_ref().and_then(|s| s.first()).map_or(&[], |f| f.children());
736                    let end = tokens.len().saturating_sub(1);
737                    let start = ((index + 1) as usize).min(end);
738                    let result = match_all_syntaxes(arena, Some(chi), &create_validation_context(arena, &tokens[start..end]), options);
739                    if !result.success {
740                        success = false;
741                        errors.extend(result.errors);
742                    }
743                    stack.pop();
744                } else {
745                    return fail(format!("Unexpected token {}", token_type_name(t(token))), token);
746                }
747            }
748            EnumToken::NumberTokenType | EnumToken::LiteralTokenType | EnumToken::DimensionTokenType
749                if top(&stack) == Some(EnumToken::PseudoClassFunctionTokenDefType) => {}
750            _ => {
751                return fail(format!("Unsupported selector token {}", token_type_name(t(token))), token);
752            }
753        }
754        let len = tokens.len();
755        if t(token) == EnumToken::WhitespaceTokenType
756            && len >= 2
757            && trim_whitespace_after(t(tokens[len - 2]))
758            && t(tokens[len - 1]) == EnumToken::WhitespaceTokenType
759        {
760            tokens.pop();
761        } else if trim_whitespace_before(t(token)) && len >= 2 && t(tokens[len - 2]) == EnumToken::WhitespaceTokenType {
762            tokens.remove(len - 2);
763        }
764        i += 1;
765    }
766    if top(&stack) == Some(EnumToken::UniversalSelectorTokenType) {
767        stack.pop();
768    }
769    if let Some(&last) = stack.last() {
770        return fail(format!("Unmatched token {}", token_type_name(t(last))), last);
771    }
772    // the buffer of the stream is replaced: no copy
773    std::mem::swap(stream, &mut *tokens);
774    // typescript returns the array of the caller (`{ success, errors }`): the node errors of an invalid rule are the
775    // errors of the parse so far. the callers only read them when the selector is not valid: the list is not copied for
776    // a valid selector (a copy per selector is quadratic with the number of errors of the stylesheet)
777    (success, if success { Vec::new() } else { errors.clone() })
778}
779
780// ---------------------------------------------------------------------------------------------------------------------
781// declaration validation cache
782// ---------------------------------------------------------------------------------------------------------------------
783
784/// error of a failed validation bound to the position of its tokens in the value
785#[derive(Clone, Debug)]
786struct CachedError {
787    error: ErrorDescription,
788    node: isize,
789    location: isize,
790}
791
792#[derive(Clone, Debug)]
793struct CachedValidation {
794    offset: usize,
795    length: usize,
796    valid: bool,
797    errors: Option<Vec<CachedError>>,
798}
799
800#[derive(Default)]
801struct ValidationCache {
802    by_syntax: HashMap<(usize, usize), (Vec<Syntax>, HashMap<i32, Vec<CachedValidation>>)>,
803    pool: Vec<f64>,
804}
805
806struct EncodingState {
807    caches: HashMap<u64, ValidationCache>,
808    epochs: Vec<u64>,
809    encoding: Vec<f64>,
810    hash: i32,
811    /// the encoded value contains a token the compiled matchers do not handle (var(), a custom function call, ...): the
812    /// interpreter validates it, see [`compiled_verdict`]
813    bail: bool,
814}
815
816thread_local! {
817    static ENCODING: RefCell<EncodingState> = RefCell::new(EncodingState { caches: HashMap::default(), epochs: Vec::new(), encoding: Vec::with_capacity(512), hash: 0, bail: false });
818}
819
820/// `value | 0`
821fn to_int32(value: f64) -> i32 {
822    if !value.is_finite() {
823        return 0;
824    }
825    let v = value.trunc() % 4294967296.0;
826    (if v < 0.0 { v + 4294967296.0 } else { v }) as u32 as i32
827}
828
829fn encode(state: &mut EncodingState, value: f64) {
830    state.encoding.push(value);
831    let v = if value.fract() == 0.0 && value.is_finite() { to_int32(value) } else { to_int32(value * 4096.0) };
832    state.hash = (state.hash ^ v).wrapping_mul(0x01000193);
833}
834
835fn encode_token(arena: &AstArena, state: &mut EncodingState, token: u32) {
836    let typ = arena.data_types.get(token);
837    if matches!(
838        typ,
839        EnumToken::WildCardFunctionTokenType
840            | EnumToken::WildCardFunctionTokenDefType
841            | EnumToken::CustomFunctionTokenType
842            | EnumToken::CustomFunctionTokenDefType
843            | EnumToken::BadCdoTokenType
844            | EnumToken::BadCommentTokenType
845            | EnumToken::BadStringTokenType
846    ) {
847        state.bail = true;
848    }
849    encode(state, typ as f64);
850    encode(state, arena.name.get(token) as f64);
851    encode(state, if typ == EnumToken::StringTokenType { 0.0 } else { arena.string_value.get(token) as f64 });
852    encode(state, arena.numeric_value.get(token));
853    encode(state, arena.unit.get(token) as f64);
854    encode(state, arena.color_type.get(token) as f64);
855    if arena.first_token.get(token) != 0 {
856        encode(state, -1.0);
857        for child in arena.token_iter(token) {
858            encode_token(arena, state, child);
859        }
860        encode(state, -2.0);
861    }
862    if arena.first_child.get(token) != 0 {
863        encode(state, -3.0);
864        for child in arena.child_iter(token) {
865            encode_token(arena, state, child);
866        }
867        encode(state, -4.0);
868    }
869}
870
871/// encode the value tokens: returns the encoding hash
872fn encode_value(arena: &AstArena, tokens: &[u32]) {
873    ENCODING.with(|e| {
874        let mut state = e.borrow_mut();
875        state.encoding.clear();
876        state.hash = 0x811c9dc5u32 as i32;
877        state.bail = false;
878        for &t in tokens {
879            encode_token(arena, &mut state, t);
880        }
881    });
882}
883
884fn syntaxes_key(syntaxes: &[Syntax]) -> (usize, usize) {
885    (syntaxes.as_ptr() as usize, syntaxes.len())
886}
887
888/// the cache of the arena strings (by string epoch). the old epochs are dropped
889fn cache_of(state: &mut EncodingState, epoch: u64) -> &mut ValidationCache {
890    if !state.caches.contains_key(&epoch) {
891        state.epochs.push(epoch);
892        if state.epochs.len() > 16 {
893            let old = state.epochs.remove(0);
894            state.caches.remove(&old);
895        }
896    }
897    state.caches.entry(epoch).or_default()
898}
899
900/// the cached validation of the current encoding for the syntax: (index in the bucket, validation)
901fn find_validation(arena: &AstArena, syntaxes: &[Syntax]) -> Option<CachedValidation> {
902    ENCODING.with(|e| {
903        let state = e.borrow();
904        let cache = state.caches.get(&arena.string_epoch())?;
905        let (keep, by_hash) = cache.by_syntax.get(&syntaxes_key(syntaxes))?;
906        if keep.len() != syntaxes.len() || !keep.iter().zip(syntaxes).all(|(a, b)| Rc::ptr_eq(a, b)) {
907            return None;
908        }
909        let bucket = by_hash.get(&state.hash)?;
910        bucket
911            .iter()
912            .find(|v| v.length == state.encoding.len() && cache.pool[v.offset..v.offset + v.length] == state.encoding[..])
913            .cloned()
914    })
915}
916
917/// copy the current encoding to the pool of the cache: (offset, length, hash)
918fn store_encoding(arena: &AstArena) -> (usize, usize, i32) {
919    ENCODING.with(|e| {
920        let mut state = e.borrow_mut();
921        let encoding = std::mem::take(&mut state.encoding);
922        let hash = state.hash;
923        let cache = cache_of(&mut state, arena.string_epoch());
924        let offset = cache.pool.len();
925        cache.pool.extend_from_slice(&encoding);
926        state.encoding = encoding;
927        (offset, state.encoding.len(), hash)
928    })
929}
930
931fn cache_validation(arena: &AstArena, syntaxes: &[Syntax], offset: usize, length: usize, hash: i32, valid: bool, errors: Option<Vec<CachedError>>) {
932    ENCODING.with(|e| {
933        let mut state = e.borrow_mut();
934        let cache = cache_of(&mut state, arena.string_epoch());
935        let entry = cache.by_syntax.entry(syntaxes_key(syntaxes)).or_insert_with(|| (syntaxes.to_vec(), HashMap::default()));
936        if !(entry.0.len() == syntaxes.len() && entry.0.iter().zip(syntaxes).all(|(a, b)| Rc::ptr_eq(a, b))) {
937            *entry = (syntaxes.to_vec(), HashMap::default());
938        }
939        entry.1.entry(hash).or_default().push(CachedValidation { offset, length, valid, errors });
940    });
941}
942
943/// record the errors of a failure cached without its errors
944fn set_cached_errors(arena: &AstArena, syntaxes: &[Syntax], offset: usize, errors: Option<Vec<CachedError>>) {
945    ENCODING.with(|e| {
946        let mut state = e.borrow_mut();
947        let cache = cache_of(&mut state, arena.string_epoch());
948        if let Some((_, by_hash)) = cache.by_syntax.get_mut(&syntaxes_key(syntaxes)) {
949            for bucket in by_hash.values_mut() {
950                for v in bucket.iter_mut() {
951                    if v.offset == offset {
952                        v.errors = errors;
953                        return;
954                    }
955                }
956            }
957        }
958    });
959}
960
961fn collect_tokens(arena: &AstArena, token: u32, result: &mut Vec<u32>) {
962    result.push(token);
963    for child in arena.token_iter(token) {
964        collect_tokens(arena, child, result);
965    }
966    for child in arena.child_iter(token) {
967        collect_tokens(arena, child, result);
968    }
969}
970
971fn value_tokens(arena: &AstArena, tokens: &[u32]) -> Vec<u32> {
972    let mut result = Vec::new();
973    for &t in tokens {
974        collect_tokens(arena, t, &mut result);
975    }
976    result
977}
978
979fn bind_errors(arena: &AstArena, tokens: &[u32], errors: &[ErrorDescription], options: &ParserOptions) -> Option<Vec<CachedError>> {
980    let mut result = Vec::new();
981    for error in errors {
982        let mut node: isize = -1;
983        let mut location: isize = -1;
984        if let Some(n) = error.node {
985            node = tokens.iter().position(|&t| t == n)? as isize;
986        }
987        if let Some(loc) = &error.location {
988            if node != -1 && token_location(arena, tokens[node as usize], options).as_ref() == Some(loc) {
989                location = node;
990            } else {
991                location = tokens.iter().position(|&t| token_location(arena, t, options).as_ref() == Some(loc))? as isize;
992            }
993        }
994        result.push(CachedError { error: error.clone(), node, location });
995    }
996    Some(result)
997}
998
999fn rebuild_errors(arena: &AstArena, tokens: &[u32], errors: &[CachedError], options: &ParserOptions) -> Vec<ErrorDescription> {
1000    errors
1001        .iter()
1002        .map(|e| {
1003            let mut error = e.error.clone();
1004            if e.node != -1 {
1005                error.node = Some(tokens[e.node as usize]);
1006            }
1007            if e.location != -1 {
1008                error.location = token_location(arena, tokens[e.location as usize], options);
1009            }
1010            error
1011        })
1012        .collect()
1013}
1014
1015thread_local! {
1016    /// number of declaration values validated (cache misses), see [`declaration_validations`]
1017    static DECLARATION_VALIDATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1018}
1019
1020/// number of declaration values validated on this thread: an identical value is validated once
1021pub fn declaration_validations() -> usize {
1022    DECLARATION_VALIDATIONS.with(|c| c.get())
1023}
1024
1025fn count_validation() {
1026    DECLARATION_VALIDATIONS.with(|c| c.set(c.get() + 1));
1027}
1028
1029// ---------------------------------------------------------------------------------------------------------------------
1030// compiled matchers
1031// ---------------------------------------------------------------------------------------------------------------------
1032
1033/// the number of values validated by the compiled matchers, see [`compiled_stats`]
1034#[derive(Clone, Debug, Default)]
1035pub struct CompiledStats {
1036    /// valid: the answer of the compiled matcher is final
1037    pub valid: usize,
1038    /// deferred to the interpreter
1039    pub deferred: usize,
1040    /// deferred: the value contains var(), a custom function, ...
1041    pub bail: usize,
1042    /// deferred: the syntax is not compiled
1043    pub uncompiled: usize,
1044    /// deferred: the compiled matcher rejected the value, the interpreter accepted it (verified mode)
1045    pub rejected_valid: usize,
1046    /// (syntax, value) of the values rejected by a compiled matcher and accepted by the interpreter (verified mode)
1047    pub rejected_valid_samples: Vec<(String, String)>,
1048    /// (syntax, value) of the values accepted by a compiled matcher and rejected by the interpreter (verified mode)
1049    pub mismatches: Vec<(String, String)>,
1050}
1051
1052thread_local! {
1053    /// 0: the compiled matchers are not used, 1: used (a valid answer is final), 2: verified by the interpreter
1054    static COMPILED_MODE: std::cell::Cell<u8> = const { std::cell::Cell::new(1) };
1055    static COMPILED_STATS: RefCell<CompiledStats> = RefCell::new(CompiledStats::default());
1056    /// the compiled definition of the syntaxes (by address), None when they are not compiled
1057    static COMPILED_DEFINITIONS: RefCell<HashMap<(usize, usize), Option<u32>>> = RefCell::new(HashMap::default());
1058}
1059
1060/// use the compiled matchers (see [`crate::validation::compiled`]): 0 not used, 1 used, 2 verified by the interpreter
1061/// (see [`compiled_stats`])
1062pub fn set_compiled_validation(mode: u8) {
1063    COMPILED_MODE.with(|m| m.set(mode));
1064}
1065
1066/// the number of values validated by the compiled matchers on this thread, and the disagreements with the interpreter
1067/// (verified mode, see [`set_compiled_validation`])
1068pub fn compiled_stats() -> CompiledStats {
1069    COMPILED_STATS.with(|s| s.borrow().clone())
1070}
1071
1072/// the text of a value, for the reports
1073fn value_text(arena: &AstArena, tokens: &[u32]) -> String {
1074    tokens.iter().map(|&t| crate::printer::render::render_value_default(arena, t)).collect()
1075}
1076
1077/// true if the value is valid according to the compiled matcher of the syntax. false: the interpreter must validate it
1078/// (the value may be valid). the value must be encoded (see [`encode_value`])
1079fn compiled_verdict(arena: &AstArena, syntaxes: &[Syntax], tokens: &[u32], options: &ParserOptions) -> bool {
1080    let mode = COMPILED_MODE.with(|m| m.get());
1081    if mode == 0 {
1082        return false;
1083    }
1084    if ENCODING.with(|e| e.borrow().bail) {
1085        COMPILED_STATS.with(|s| {
1086            let mut s = s.borrow_mut();
1087            s.deferred += 1;
1088            s.bail += 1;
1089        });
1090        return false;
1091    }
1092    let definition = COMPILED_DEFINITIONS.with(|c| {
1093        *c.borrow_mut()
1094            .entry(syntaxes_key(syntaxes))
1095            .or_insert_with(|| super::config::syntax_key(syntaxes).and_then(|key| super::compiled::runtime::compiled_definition(&key)))
1096    });
1097    let Some(definition) = definition else {
1098        COMPILED_STATS.with(|s| {
1099            let mut s = s.borrow_mut();
1100            s.deferred += 1;
1101            s.uncompiled += 1;
1102        });
1103        return false;
1104    };
1105    let valid = super::compiled::runtime::match_compiled(arena, definition, tokens, options);
1106    if mode == 2 {
1107        // the validation may encode other values
1108        let saved = ENCODING.with(|e| {
1109            let e = e.borrow();
1110            (e.encoding.clone(), e.hash, e.bail)
1111        });
1112        let interpreted = match_all_syntaxes(arena, Some(syntaxes), &create_validation_context(arena, tokens), options).success;
1113        ENCODING.with(|e| {
1114            let mut e = e.borrow_mut();
1115            e.encoding = saved.0;
1116            e.hash = saved.1;
1117            e.bail = saved.2;
1118        });
1119        if valid != interpreted {
1120            let sample = (super::config::syntax_key(syntaxes).unwrap_or_default(), value_text(arena, tokens));
1121            COMPILED_STATS.with(|s| {
1122                let mut s = s.borrow_mut();
1123                if valid {
1124                    s.mismatches.push(sample);
1125                } else {
1126                    s.rejected_valid += 1;
1127                    s.rejected_valid_samples.push(sample);
1128                }
1129            });
1130        }
1131    }
1132    COMPILED_STATS.with(|s| {
1133        let mut s = s.borrow_mut();
1134        if valid {
1135            s.valid += 1;
1136        } else {
1137            s.deferred += 1;
1138        }
1139    });
1140    valid
1141}
1142
1143/// validate the value of a declaration. the successful and the failed validations are cached by value encoding
1144pub fn match_declaration_syntax(arena: &AstArena, syntaxes: &[Syntax], tokens: &[u32], options: &ParserOptions) -> ValidationMatch {
1145    encode_value(arena, tokens);
1146    let cached = find_validation(arena, syntaxes);
1147    if let Some(cached) = &cached {
1148        if cached.valid {
1149            return ValidationMatch::new(true, true, None, None, None, Vec::new());
1150        }
1151        if let Some(errors) = &cached.errors {
1152            return ValidationMatch::new(false, true, None, None, None, rebuild_errors(arena, &value_tokens(arena, tokens), errors, options));
1153        }
1154    }
1155    if cached.is_none() && compiled_verdict(arena, syntaxes, tokens, options) {
1156        let (offset, length, hash) = store_encoding(arena);
1157        count_validation();
1158        cache_validation(arena, syntaxes, offset, length, hash, true, None);
1159        return ValidationMatch::new(true, true, None, None, None, Vec::new());
1160    }
1161    // the encoding is stored before the validation, which may encode other values
1162    let (offset, length, hash) = store_encoding(arena);
1163    count_validation();
1164    let result = match_all_syntaxes(arena, Some(syntaxes), &create_validation_context(arena, tokens), options);
1165    if result.success {
1166        cache_validation(arena, syntaxes, offset, length, hash, true, None);
1167    } else {
1168        let errors = bind_errors(arena, &value_tokens(arena, tokens), &result.errors, options);
1169        if let Some(cached) = &cached {
1170            // failure cached without its errors
1171            set_cached_errors(arena, syntaxes, cached.offset, errors);
1172        } else {
1173            cache_validation(arena, syntaxes, offset, length, hash, false, errors);
1174        }
1175    }
1176    result
1177}
1178
1179/// validate the value tokens of a declaration node. the validations are cached
1180pub fn is_valid_declaration_value(arena: &AstArena, syntaxes: &[Syntax], declaration: u32, options: &ParserOptions) -> bool {
1181    let tokens = arena.tokens(declaration);
1182    encode_value(arena, &tokens);
1183    if let Some(cached) = find_validation(arena, syntaxes) {
1184        return cached.valid;
1185    }
1186    if compiled_verdict(arena, syntaxes, &tokens, options) {
1187        let (offset, length, hash) = store_encoding(arena);
1188        count_validation();
1189        cache_validation(arena, syntaxes, offset, length, hash, true, None);
1190        return true;
1191    }
1192    let (offset, length, hash) = store_encoding(arena);
1193    count_validation();
1194    let valid = match_all_syntaxes(arena, Some(syntaxes), &create_validation_context(arena, &tokens), options).success;
1195    cache_validation(arena, syntaxes, offset, length, hash, valid, None);
1196    valid
1197}
1198
1199// ---------------------------------------------------------------------------------------------------------------------
1200// matching
1201// ---------------------------------------------------------------------------------------------------------------------
1202
1203struct Visited {
1204    entries: Vec<(u32, Syntax)>,
1205    base: usize,
1206}
1207
1208thread_local! {
1209    /// the syntaxes being matched and the token they are matched at: a syntax matched again at the same token while
1210    /// it is being matched is a cyclic definition
1211    static VISITED: RefCell<Visited> = const { RefCell::new(Visited { entries: Vec::new(), base: 0 }) };
1212    /// the wildcard functions being matched with a syntax
1213    static WILDCARD_PROBES: RefCell<HashMap<u32, Syntax>> = RefCell::new(HashMap::default());
1214}
1215
1216/// true if a syntax is being matched at a token
1217pub(crate) fn is_visited(token: u32, syntax: &Syntax) -> bool {
1218    VISITED.with(|v| {
1219        let v = v.borrow();
1220        v.entries[v.base..].iter().any(|(t, s)| *t == token && Rc::ptr_eq(s, syntax))
1221    })
1222}
1223
1224/// record that a syntax is being matched at a token
1225pub(crate) fn enter_syntax(token: u32, syntax: &Syntax) -> usize {
1226    VISITED.with(|v| {
1227        let mut v = v.borrow_mut();
1228        v.entries.push((token, syntax.clone()));
1229        v.entries.len() - 1
1230    })
1231}
1232
1233/// leave the syntaxes entered after a mark
1234pub(crate) fn leave_syntax(length: usize) {
1235    VISITED.with(|v| v.borrow_mut().entries.truncate(length));
1236}
1237
1238/// mark a visited entry as matched (`visitedSyntaxes[i] = null`)
1239pub(crate) fn clear_visited(index: usize) {
1240    VISITED.with(|v| {
1241        if let Some(e) = v.borrow_mut().entries.get_mut(index) {
1242            e.0 = u32::MAX;
1243        }
1244    });
1245}
1246
1247/// match all the syntaxes: the tokens must be consumed
1248pub fn match_all_syntaxes(arena: &AstArena, syntaxes: Option<&[Syntax]>, context: &Context, options: &ParserOptions) -> ValidationMatch {
1249    let (base, length) = VISITED.with(|v| {
1250        let mut v = v.borrow_mut();
1251        let state = (v.base, v.entries.len());
1252        v.base = v.entries.len();
1253        state
1254    });
1255    let result = match_syntax(arena, syntaxes, context, options);
1256    VISITED.with(|v| {
1257        let mut v = v.borrow_mut();
1258        v.base = base;
1259        v.entries.truncate(length);
1260    });
1261    if let Some(syntaxes) = syntaxes {
1262        if result.success {
1263            if let Some(syntax_token) = &result.syntax_token {
1264                if let Some(index) = syntaxes.iter().position(|s| Rc::ptr_eq(s, syntax_token)) {
1265                    let mandatory = find_mandatory_syntax(syntaxes, index);
1266                    if mandatory != -1 {
1267                        return ValidationMatch::new(
1268                            false,
1269                            result.valid,
1270                            result.token,
1271                            result.context.clone(),
1272                            Some(syntaxes[mandatory as usize].clone()),
1273                            result.errors,
1274                        );
1275                    }
1276                }
1277            }
1278        }
1279        if result.success && !result.ctx().done(arena) {
1280            let token = result.ctx().peek(arena);
1281            let mut errors = Vec::new();
1282            if let Some(token) = token {
1283                errors.push(drop_error(arena, "unexpected token".into(), token, options));
1284            }
1285            return ValidationMatch::new(false, result.valid, token, result.context.clone(), None, errors);
1286        }
1287    }
1288    let errors = if !result.success && result.errors.is_empty() {
1289        let location_token = result.token.or_else(|| context.borrow().tokens().last().copied());
1290        let mut error = ErrorDescription::drop("could not match syntax");
1291        error.node = result.token;
1292        error.syntax = result.syntax_token.clone().map(ErrorSyntax::Token);
1293        error.location = location_token.and_then(|t| token_location(arena, t, options));
1294        vec![error]
1295    } else {
1296        result.errors
1297    };
1298    ValidationMatch::new(
1299        result.success,
1300        result.valid,
1301        result.token,
1302        result.context,
1303        if !result.success { result.syntax_token } else { None },
1304        errors,
1305    )
1306}
1307
1308/// number of the mandatory commas of a list item
1309fn count_item_commas(syntax: &ValidationToken) -> i32 {
1310    if syntax.typ == V::Bracket {
1311        syntax.children().iter().filter(|t| t.typ == V::Comma).count() as i32
1312    } else {
1313        0
1314    }
1315}
1316
1317fn match_max_finite(syntax: &ValidationToken) -> Option<f64> {
1318    match syntax.match_.as_ref().map(|m| &m.max) {
1319        Some(MatchMax::Token(t)) if t.val_num().is_finite() => Some(t.val_num()),
1320        _ => None,
1321    }
1322}
1323
1324/// matches a list (`#`) of a syntax
1325pub(crate) fn match_list_syntax(arena: &AstArena, syntax: &Syntax, context: &Context, options: &ParserOptions) -> ValidationMatch {
1326    let mut rest = (**syntax).clone();
1327    rest.is_list = None;
1328    rest.match_ = None;
1329    rest.is_optional = None;
1330    let rest = Rc::new(rest);
1331    let mut success = false;
1332    let mut result: Option<ValidationMatch> = None;
1333    let mut count = 0.0;
1334    let commas = count_item_commas(&rest);
1335    let rest_list = [rest.clone()];
1336    loop {
1337        let range = context.borrow().peek_range(arena, EnumToken::CommaTokenType, 1 + commas);
1338        let last_is_comma = range.last().is_some_and(|&t| arena.data_types.get(t) == EnumToken::CommaTokenType);
1339        let item: &[u32] = if last_is_comma { &range[..range.len() - 1] } else { &range };
1340        let tmp = match_syntax(arena, Some(&rest_list), &create_validation_context(arena, item), options);
1341        if tmp.success && !tmp.ctx().done(arena) {
1342            if let Some(current) = tmp.ctx().current() {
1343                count += 1.0;
1344                success = true;
1345                result = Some(tmp.clone());
1346                context.update(Some(current));
1347            }
1348            break;
1349        }
1350        let mut done = false;
1351        if tmp.success {
1352            count += 1.0;
1353            success = true;
1354            result = Some(tmp.clone());
1355            if let Some(max) = match_max_finite(syntax) {
1356                if count == max {
1357                    let target = if last_is_comma { range.len().checked_sub(2).map(|i| range[i]) } else { range.last().copied() };
1358                    context.update(target);
1359                    break;
1360                }
1361            }
1362            context.update(range.last().copied());
1363            done = context.done(arena);
1364        }
1365        if !(tmp.success && !done) {
1366            break;
1367        }
1368    }
1369    if result.is_some() {
1370        if let Some(m) = &syntax.match_ {
1371            let min = m.min.val_num();
1372            if !min.is_nan() && count < min {
1373                result = None;
1374            }
1375        }
1376    }
1377    match result {
1378        None => ValidationMatch::new(false, true, context.peek(arena), Some(context.clone()), Some(syntax.clone()), Vec::new()),
1379        Some(mut r) => {
1380            r.success = success;
1381            r.context = Some(context.clone());
1382            r.token = context.peek(arena);
1383            r
1384        }
1385    }
1386}
1387
1388/// matches the occurrences (`{min,max}`) of a syntax
1389pub(crate) fn match_occurence_syntax(arena: &AstArena, syntax: &Syntax, context: &Context, options: &ParserOptions) -> ValidationMatch {
1390    let mut rest = (**syntax).clone();
1391    rest.match_ = None;
1392    let rest_list = [Rc::new(rest)];
1393    let mut result: Option<ValidationMatch> = None;
1394    let mut count = 0.0;
1395    loop {
1396        let tmp = match_syntax(arena, Some(&rest_list), &context.slice(), options);
1397        if tmp.success {
1398            count += 1.0;
1399            result = Some(tmp.clone());
1400            if tmp.ctx().done(arena) {
1401                context.end();
1402                break;
1403            }
1404            if tmp.ctx().current() == context.current() {
1405                break;
1406            }
1407            context.update(tmp.ctx().current());
1408            if let Some(max) = match_max_finite(syntax) {
1409                if count == max {
1410                    break;
1411                }
1412            }
1413        }
1414        if !(tmp.success && !context.done(arena)) {
1415            break;
1416        }
1417    }
1418    let out_of_range = syntax.match_.as_ref().is_some_and(|m| {
1419        count < m.min.val_num() || match_max_finite(syntax).is_some_and(|max| count > max)
1420    });
1421    match result {
1422        Some(r) if !out_of_range => r,
1423        _ => {
1424            let mut error = ErrorDescription::drop("could not match syntax");
1425            error.node = context.peek(arena);
1426            ValidationMatch::new(false, true, None, Some(context.clone()), None, vec![error])
1427        }
1428    }
1429}
1430
1431/// index of the first syntax that must be matched, starting at index. -1 if the remaining syntaxes may match no token
1432pub(crate) fn find_mandatory_syntax(syntaxes: &[Syntax], index: usize) -> isize {
1433    (index..syntaxes.len()).find(|&i| !is_nullable(&syntaxes[i])).map_or(-1, |i| i as isize)
1434}
1435
1436/// true if a token is a literal number or dimension of a syntax: `0`, `90deg`
1437pub(crate) fn is_literal_number(arena: &AstArena, token: u32, syntax: &ValidationToken) -> bool {
1438    if arena.has_fraction(token) || arena.numeric_value.get(token) != syntax.val_num() {
1439        return false;
1440    }
1441    if syntax.typ == V::Number {
1442        return arena.data_types.get(token) == EnumToken::NumberTokenType;
1443    }
1444    let typ = syntax.unit.as_deref().and_then(EnumToken::value);
1445    Some(arena.data_types.get(token)) == typ
1446        && arena.with_string(arena.unit.get(token), |u| equals_ignore_case(u, syntax.unit_text.as_deref().unwrap_or("")))
1447}
1448
1449/// true if a numeric token is in the range of the syntax: `<integer [1,∞]>`
1450pub(crate) fn is_in_range(arena: &AstArena, token: u32, syntax: &ValidationToken) -> bool {
1451    let Some(range) = &syntax.range else {
1452        return true;
1453    };
1454    if matches!(
1455        arena.data_types.get(token),
1456        EnumToken::MathFunctionTokenType
1457            | EnumToken::MathFunctionTokenDefType
1458            | EnumToken::WildCardFunctionTokenType
1459            | EnumToken::WildCardFunctionTokenDefType
1460    ) {
1461        return true;
1462    }
1463    let value = arena.numeric_value.get(token);
1464    let mut success = !arena.has_fraction(token) && range.min.as_ref().is_none_or(|m| value >= m.val_num());
1465    if let Some(min) = &range.min {
1466        if min.typ == V::Dimension {
1467            success = Some(arena.data_types.get(token)) == min.unit.as_deref().and_then(EnumToken::value);
1468        }
1469    }
1470    if success {
1471        if let Some(max) = &range.max {
1472            success = value <= max.val_num();
1473        }
1474    }
1475    success
1476}
1477
1478/// the validation syntax of a function token (`name()`): looked up once per function name
1479pub(crate) fn function_syntax(arena: &AstArena, token: u32) -> Option<Rc<Vec<Syntax>>> {
1480    arena.string_derived(arena.string_value.get(token), StringDerived::FunctionSyntax, |id| {
1481        get_parsed_syntax(ValidationSyntaxGroupEnum::Syntaxes, &format!("{}()", arena.resolve_string(id)))
1482    })
1483}
1484
1485/// the validation syntax of a selector function token (`:name()`)
1486pub(crate) fn selector_function_syntax(arena: &AstArena, token: u32) -> Option<Rc<Vec<Syntax>>> {
1487    arena.string_derived(arena.string_value.get(token), StringDerived::SelectorFunctionSyntax, |id| {
1488        get_parsed_syntax(ValidationSyntaxGroupEnum::Selectors, &format!("{}()", arena.resolve_string(id)))
1489    })
1490}
1491
1492/// var(), env() and if() may be substituted by any number of values. None: the syntax at index is skipped
1493#[allow(clippy::too_many_arguments)]
1494pub(crate) fn match_wild_card_function(
1495    arena: &AstArena,
1496    syntaxes: &[Syntax],
1497    index: usize,
1498    context: &Context,
1499    token: u32,
1500    end: Option<u32>,
1501    options: &ParserOptions,
1502) -> Option<ValidationMatch> {
1503    let mut errors: Vec<ErrorDescription> = Vec::new();
1504    let mut candidates: Vec<Context> = Vec::new();
1505    let syntax = &syntaxes[index];
1506    if !matches!(syntax.typ, V::Keyword | V::Comma | V::Separator | V::StringToken | V::OpenParenthesis | V::CloseParenthesis) {
1507        let previous = WILDCARD_PROBES.with(|w| w.borrow_mut().insert(token, syntax.clone()));
1508        let probe = match_syntax(arena, Some(std::slice::from_ref(syntax)), &context.slice(), options);
1509        WILDCARD_PROBES.with(|w| {
1510            let mut w = w.borrow_mut();
1511            match previous {
1512                None => w.remove(&token),
1513                Some(p) => w.insert(token, p),
1514            }
1515        });
1516        if probe.success {
1517            if probe.ctx().done(arena) {
1518                if find_mandatory_syntax(syntaxes, index + 1) == -1 {
1519                    context.end();
1520                    return Some(ValidationMatch::new(true, probe.valid, None, Some(context.clone()), None, probe.errors));
1521                }
1522            } else if probe.ctx().current().is_some() {
1523                candidates.push(probe.ctx().clone());
1524            }
1525        }
1526    }
1527    let next = context.slice();
1528    next.update(end);
1529    if next.done(arena) {
1530        context.end();
1531        return Some(ValidationMatch::new(true, true, None, Some(context.clone()), None, Vec::new()));
1532    }
1533    candidates.push(next);
1534    for candidate in &candidates {
1535        let rest = match_syntax(arena, Some(&syntaxes[index + 1..]), &candidate.slice(), options);
1536        if rest.success {
1537            if rest.ctx().done(arena) {
1538                context.end();
1539            } else {
1540                context.update(rest.ctx().current().or_else(|| candidate.current()));
1541            }
1542            return Some(ValidationMatch::new(true, rest.valid, rest.token, Some(context.clone()), None, rest.errors));
1543        }
1544        errors = rest.errors;
1545    }
1546    if is_nullable(syntax) {
1547        return None;
1548    }
1549    Some(ValidationMatch::new(false, true, Some(token), Some(context.clone()), Some(syntax.clone()), errors))
1550}
1551
1552/// true if a wildcard function is being probed with a syntax
1553pub(crate) fn wild_card_probe(token: u32) -> Option<Syntax> {
1554    WILDCARD_PROBES.with(|w| w.borrow().get(&token).cloned())
1555}
1556
1557/// the tokens are consumed: the match succeeds if the remaining syntaxes, starting at index, are optional
1558pub(crate) fn set_done_match(
1559    syntaxes: &[Syntax],
1560    index: usize,
1561    valid: bool,
1562    token: Option<u32>,
1563    context: &Context,
1564    errors: Vec<ErrorDescription>,
1565) -> ValidationMatch {
1566    let mandatory = find_mandatory_syntax(syntaxes, index);
1567    if mandatory != -1 {
1568        return ValidationMatch::new(false, valid, token, Some(context.clone()), Some(syntaxes[mandatory as usize].clone()), Vec::new());
1569    }
1570    ValidationMatch::new(true, valid, token, Some(context.clone()), syntaxes.get(index).cloned(), errors)
1571}
1572
1573// matchSyntax, the unordered syntaxes and matchProperty: see match_syntax.rs
1574pub use super::match_syntax::{match_syntax, peek_feature_tokens};
1575
1576#[allow(dead_code)]
1577fn _unused(_: ErrorAction, _: Option<&serde_json::Value>, _: &dyn Fn() -> bool) {}
1578
1579#[allow(dead_code)]
1580fn _use_first(arena: &AstArena, s: &[Vec<Syntax>]) -> Option<Rc<Vec<usize>>> {
1581    let _ = may_start_with(arena, &[], None);
1582    matching_alternatives(arena, s, None)
1583}