Skip to main content

rust_css_parser/validation/
first.rs

1//! Port of `src/validation/first.ts`: first token sets of the validation syntaxes.
2//!
3//! The typescript caches are `WeakMap`s keyed by the syntax objects. The rust caches are keyed by the address of the
4//! shared syntax tokens / sequences: an entry keeps the syntax alive (the address is not reused) and a sequence entry
5//! is checked element by element (`Rc::ptr_eq`).
6
7use super::config::{get_parsed_syntax, get_syntax_config};
8use super::parser::typedef::{ValidationSyntaxGroupEnum, ValidationTokenEnum as V};
9use super::parser::types::{ValidationToken, VVal};
10use crate::ast::arena::AstArena;
11use crate::ast::types::EnumToken;
12use crate::parser::utils::text::{equals_ignore_case, lowercase};
13use crate::syntax::constants::{is_function_def_type, is_function_type, FUNC_LIKE, TOKENS_FUNC_DEF_MAP};
14use std::cell::RefCell;
15use crate::utils::fx::{HashMap, HashSet};
16use std::rc::Rc;
17use std::sync::OnceLock;
18
19/// set of token types (bitset)
20#[derive(Clone, Debug, Default, PartialEq, Eq)]
21pub struct TypeSet([u64; 4]);
22
23impl TypeSet {
24    #[inline]
25    pub fn add(&mut self, t: u8) {
26        self.0[(t >> 6) as usize] |= 1 << (t & 63);
27    }
28
29    #[inline]
30    pub fn has(&self, t: u8) -> bool {
31        self.0[(t >> 6) as usize] & (1 << (t & 63)) != 0
32    }
33
34    fn merge(&mut self, other: &TypeSet) {
35        for i in 0..4 {
36            self.0[i] |= other.0[i];
37        }
38    }
39}
40
41/// the first tokens of a syntax
42#[derive(Clone, Debug, Default)]
43pub struct FirstSet {
44    pub any: bool,
45    pub nullable: bool,
46    pub types: TypeSet,
47    pub keywords: HashSet<String>,
48    pub functions: HashSet<String>,
49}
50
51fn any_token() -> Rc<FirstSet> {
52    thread_local! {
53        static ANY: Rc<FirstSet> = Rc::new(FirstSet { any: true, nullable: true, ..Default::default() });
54    }
55    ANY.with(|a| a.clone())
56}
57
58fn merge(target: &mut FirstSet, source: &FirstSet) {
59    target.any |= source.any;
60    target.types.merge(&source.types);
61    target.keywords.extend(source.keywords.iter().cloned());
62    target.functions.extend(source.functions.iter().cloned());
63}
64
65/// key of a sequence: the address and the length of its elements
66fn seq_key(syntaxes: &[Rc<ValidationToken>]) -> (usize, usize) {
67    (syntaxes.as_ptr() as usize, syntaxes.len())
68}
69
70fn same_seq(a: &[Rc<ValidationToken>], b: &[Rc<ValidationToken>]) -> bool {
71    a.len() == b.len() && a.iter().zip(b).all(|(x, y)| Rc::ptr_eq(x, y))
72}
73
74struct Caches {
75    nullable: HashMap<usize, (Rc<ValidationToken>, bool)>,
76    tokens: HashMap<usize, (Rc<ValidationToken>, Rc<FirstSet>)>,
77    sequences: HashMap<(usize, usize), (Vec<Rc<ValidationToken>>, Rc<FirstSet>)>,
78    computing: HashSet<(usize, usize)>,
79    alternatives: HashMap<(usize, usize), (Vec<Vec<Rc<ValidationToken>>>, Rc<RefCell<AlternativeIndex>>)>,
80}
81
82thread_local! {
83    static CACHES: RefCell<Caches> = RefCell::new(Caches {
84        nullable: HashMap::default(),
85        tokens: HashMap::default(),
86        sequences: HashMap::default(),
87        computing: HashSet::default(),
88        alternatives: HashMap::default(),
89    });
90}
91
92fn match_min_is_zero(syntax: &ValidationToken) -> bool {
93    syntax.match_.as_ref().is_some_and(|m| m.min.val_num() == 0.0)
94}
95
96/// true if the syntax may match no token
97pub fn is_nullable(syntax: &Rc<ValidationToken>) -> bool {
98    if syntax.typ == V::Whitespace {
99        return true;
100    }
101    if syntax.is_mandatatory_group() {
102        return false;
103    }
104    if syntax.is_optional() || syntax.is_repeatable() || match_min_is_zero(syntax) {
105        return true;
106    }
107    let key = Rc::as_ptr(syntax) as usize;
108    if let Some(v) = CACHES.with(|c| c.borrow().nullable.get(&key).map(|e| e.1)) {
109        return v;
110    }
111    let nullable = match syntax.typ {
112        V::Bracket => syntax.children().iter().all(is_nullable),
113        V::PipeToken => syntax.alternatives().iter().any(|s| s.iter().all(is_nullable)),
114        V::AmpersandToken => {
115            syntax.l.as_deref().unwrap_or(&[]).iter().all(is_nullable) && syntax.r.as_deref().unwrap_or(&[]).iter().all(is_nullable)
116        }
117        _ => false,
118    };
119    CACHES.with(|c| c.borrow_mut().nullable.insert(key, (syntax.clone(), nullable)));
120    nullable
121}
122
123/// the types of the function tokens: the types whose name is a key of the sets
124fn function_token_types() -> &'static TypeSet {
125    static SET: OnceLock<TypeSet> = OnceLock::new();
126    SET.get_or_init(|| {
127        let mut set = TypeSet::default();
128        for v in 0..=255u8 {
129            if EnumToken::name(v).is_none() {
130                continue;
131            }
132            let func_type = TOKENS_FUNC_DEF_MAP.iter().any(|(_, t)| *t == v)
133                || v == EnumToken::FunctionTokenType
134                || v == EnumToken::PseudoClassFuncTokenType;
135            if is_function_def_type(v) || is_function_type(v) || FUNC_LIKE.contains(&v) || func_type {
136                set.add(v);
137            }
138        }
139        set
140    })
141}
142
143fn function_def_types() -> Vec<u8> {
144    (0..=255u8).filter(|&v| EnumToken::name(v).is_some() && is_function_def_type(v)).collect()
145}
146
147/// the types of the tokens accepted by the built-in types of the matcher. None: any token. Err: not a built-in type
148fn builtin_type(name: &str) -> Result<Option<Vec<u8>>, ()> {
149    use EnumToken as E;
150    let color = || {
151        let mut v = vec![E::ColorTokenType, E::IdenTokenType, E::FunctionTokenType];
152        v.extend(function_def_types());
153        v
154    };
155    Ok(Some(match name {
156        "dashed-ident" | "extension-name" | "custom-property-name" => vec![E::DashedIdenTokenType],
157        "namespace-prefix" | "ident" | "ident-token" | "custom-ident" | "counter-name" | "counter-style-name" => {
158            vec![E::IdenTokenType, E::DashedIdenTokenType]
159        }
160        "unicode-range-token" => vec![E::UniCodeRange],
161        "hash-token" => vec![E::HashTokenType, E::ColorTokenType],
162        "string" => vec![E::StringTokenType],
163        "wq-name" => vec![E::IdenTokenType],
164        "number" | "zero" | "integer" => vec![E::NumberTokenType],
165        "dimension" => vec![
166            E::DimensionTokenType,
167            E::AngleTokenType,
168            E::LengthTokenType,
169            E::PercentageTokenType,
170            E::ResolutionTokenType,
171            E::TimeTokenType,
172            E::FrequencyTokenType,
173            E::UserDefinedDimensionTokenType,
174            E::FlexTokenType,
175        ],
176        "angle" => vec![E::AngleTokenType, E::UserDefinedDimensionTokenType],
177        "angle-percentage" => vec![E::AngleTokenType, E::UserDefinedDimensionTokenType, E::PercentageTokenType],
178        "percentage" => vec![E::PercentageTokenType],
179        "length-percentage" => vec![E::PercentageTokenType, E::LengthTokenType, E::UserDefinedDimensionTokenType, E::NumberTokenType],
180        "flex" => vec![E::FlexTokenType, E::UserDefinedDimensionTokenType],
181        "length" => vec![E::LengthTokenType, E::UserDefinedDimensionTokenType, E::NumberTokenType],
182        "resolution" => vec![E::ResolutionTokenType],
183        "frequency" => vec![E::FrequencyTokenType],
184        "decibel" | "semitones" => vec![E::DimensionTokenType],
185        "time" => vec![E::TimeTokenType, E::UserDefinedDimensionTokenType],
186        "quote" | "display-box" | "display-inside" | "display-internal" | "display-outside" | "display-legacy"
187        | "content-position" | "mf-name" | "language-code" => vec![E::IdenTokenType],
188        "url" => vec![E::UrlFunctionTokenDefType, E::UrlFunctionTokenType],
189        "color" | "color-function" => color(),
190        "function-token" => function_def_types(),
191        "dashed-function" => vec![E::CustomFunctionTokenDefType, E::CustomFunctionTokenType],
192        "block-contents" => vec![E::StartParensTokenType],
193        "css-type" => vec![E::FunctionTokenDefType, E::FunctionTokenType, E::CssTypeTokenType],
194        "declaration-value" | "calc-sum" | "an+b" | "any-value" | "type-selector" | "compound-selector" | "complex-selector"
195        | "subclass-selector" | "attribute-selector" | "complex-selector-unit" | "pseudo-compound-selector"
196        | "forgiving-relative-selector-list" | "complex-selector-list" | "size-feature" | "style-feature" => return Ok(None),
197        _ => return Err(()),
198    }))
199}
200
201/// first tokens of a sequence of syntaxes
202pub fn first_of_sequence(syntaxes: Option<&[Rc<ValidationToken>]>) -> Rc<FirstSet> {
203    let Some(syntaxes) = syntaxes else {
204        return any_token();
205    };
206    let key = seq_key(syntaxes);
207    let cached = CACHES.with(|c| {
208        let c = c.borrow();
209        if let Some((keep, set)) = c.sequences.get(&key) {
210            if same_seq(keep, syntaxes) {
211                return Some(set.clone());
212            }
213        }
214        if c.computing.contains(&key) {
215            return Some(any_token());
216        }
217        None
218    });
219    if let Some(set) = cached {
220        return set;
221    }
222    CACHES.with(|c| c.borrow_mut().computing.insert(key));
223    let mut set = FirstSet { nullable: true, ..Default::default() };
224    for syntax in syntaxes {
225        let first = first_of(syntax);
226        merge(&mut set, &first);
227        if set.any || !first.nullable {
228            set.nullable = false;
229            break;
230        }
231    }
232    let set = if set.any { any_token() } else { Rc::new(set) };
233    CACHES.with(|c| {
234        let mut c = c.borrow_mut();
235        c.computing.remove(&key);
236        c.sequences.insert(key, (syntaxes.to_vec(), set.clone()));
237    });
238    set
239}
240
241/// first tokens of a syntax token
242pub fn first_of(syntax: &Rc<ValidationToken>) -> Rc<FirstSet> {
243    let key = Rc::as_ptr(syntax) as usize;
244    if let Some(set) = CACHES.with(|c| c.borrow().tokens.get(&key).map(|e| e.1.clone())) {
245        return set;
246    }
247    let mut set = FirstSet::default();
248    let mut nullable = false;
249    match syntax.typ {
250        V::Whitespace => nullable = true,
251        V::Keyword => {
252            set.keywords.insert(lowercase(syntax.val_str()).into_owned());
253        }
254        V::Comma => set.types.add(EnumToken::CommaTokenType),
255        V::Colon => set.types.add(EnumToken::ColonTokenType),
256        V::Separator => set.types.add(EnumToken::LiteralTokenType),
257        V::OpenParenthesis => set.types.add(EnumToken::StartParensTokenType),
258        V::CloseParenthesis => set.types.add(EnumToken::EndParensTokenType),
259        V::OpenCurlyBrace => set.types.add(EnumToken::BlockStartTokenType),
260        V::Number => set.types.add(EnumToken::NumberTokenType),
261        V::Dimension => {
262            // `EnumToken[unit]`: undefined for an unknown name (the set holds `undefined`, it accepts no token)
263            if let Some(t) = syntax.unit.as_deref().and_then(EnumToken::value) {
264                set.types.add(t);
265            }
266        }
267        V::StringToken => {
268            set.types.add(EnumToken::Add);
269            set.types.add(EnumToken::Sub);
270            set.types.add(EnumToken::LiteralTokenType);
271            set.types.add(EnumToken::Plus);
272        }
273        V::Function | V::FunctionDefinition => {
274            set.functions.insert(lowercase(syntax.val_str()).into_owned());
275        }
276        V::Bracket => {
277            let first = first_of_sequence(Some(syntax.children()));
278            merge(&mut set, &first);
279            nullable = first.nullable;
280        }
281        V::OptionalGroupToken => {
282            merge(&mut set, &first_of_sequence(Some(syntax.children())));
283            nullable = true;
284        }
285        V::PipeToken => {
286            for syntaxes in syntax.alternatives() {
287                let first = first_of_sequence(Some(syntaxes));
288                merge(&mut set, &first);
289                nullable |= first.nullable;
290            }
291        }
292        V::ColumnToken => {
293            for syntaxes in syntax.alternatives() {
294                merge(&mut set, &first_of_sequence(Some(syntaxes)));
295            }
296        }
297        V::AmpersandToken => {
298            nullable = true;
299            for syntaxes in [syntax.l.as_deref().unwrap_or(&[]), syntax.r.as_deref().unwrap_or(&[])] {
300                let first = first_of_sequence(Some(syntaxes));
301                merge(&mut set, &first);
302                nullable &= first.nullable;
303            }
304        }
305        V::DeclarationType => {
306            let parsed = get_parsed_syntax(ValidationSyntaxGroupEnum::Declarations, syntax.val_str());
307            let first = first_of_sequence(parsed.as_deref().map(|v| v.as_slice()));
308            merge(&mut set, &first);
309            nullable = first.nullable;
310        }
311        V::PropertyType => {
312            let name = syntax.val_str();
313            match builtin_type(name) {
314                Ok(None) => {
315                    set.any = true;
316                    nullable = true;
317                }
318                Ok(Some(types)) => {
319                    for t in types {
320                        set.types.add(t);
321                    }
322                }
323                Err(()) => {
324                    let parsed = get_parsed_syntax(ValidationSyntaxGroupEnum::Syntaxes, name);
325                    let first = first_of_sequence(parsed.as_deref().map(|v| v.as_slice()));
326                    merge(&mut set, &first);
327                    nullable = first.nullable;
328                }
329            }
330        }
331        _ => {
332            set.any = true;
333            nullable = true;
334        }
335    }
336    set.nullable = nullable || syntax.is_optional() || syntax.is_repeatable() || match_min_is_zero(syntax) || is_nullable(syntax);
337    let set = Rc::new(set);
338    CACHES.with(|c| c.borrow_mut().tokens.insert(key, (syntax.clone(), set.clone())));
339    set
340}
341
342/// the css wide keywords, accepted by every syntax
343fn css_wide_keywords() -> &'static [String] {
344    static KEYWORDS: OnceLock<Vec<String>> = OnceLock::new();
345    KEYWORDS.get_or_init(|| {
346        get_syntax_config()["declarations"]["all"]["syntax"]
347            .as_str()
348            .unwrap_or("")
349            .split(|c: char| c.is_whitespace() || c == '|')
350            .filter(|s| !s.is_empty())
351            .map(String::from)
352            .collect()
353    })
354}
355
356/// the token may match a syntax that does not accept its type
357fn matches_any_syntax(arena: &AstArena, token: u32, typ: u8) -> bool {
358    match typ {
359        EnumToken::WildCardFunctionTokenType
360        | EnumToken::WildCardFunctionTokenDefType
361        | EnumToken::MathFunctionTokenType
362        | EnumToken::MathFunctionTokenDefType
363        // a custom function call is substituted by its result, like var()
364        | EnumToken::CustomFunctionTokenType
365        | EnumToken::CustomFunctionTokenDefType => true,
366        EnumToken::IdenTokenType => arena.with_string(arena.string_value.get(token), |value| {
367            css_wide_keywords().iter().any(|k| equals_ignore_case(k, value))
368        }),
369        _ => false,
370    }
371}
372
373/// true if a set may start with a token
374fn accepts(set: &FirstSet, typ: u8, name: Option<&str>) -> bool {
375    if set.any || set.types.has(typ) {
376        return true;
377    }
378    match name {
379        None => false,
380        Some(name) => {
381            if typ == EnumToken::IdenTokenType {
382                set.keywords.contains(name)
383            } else {
384                set.functions.contains(name)
385            }
386        }
387    }
388}
389
390/// lowercase name of an identifier or of a function token
391fn token_name(arena: &AstArena, token: u32, typ: u8) -> Option<crate::ast::strings::SharedStr> {
392    if typ == EnumToken::IdenTokenType || function_token_types().has(typ) {
393        Some(arena.resolve_string(arena.lower_string_id(arena.string_value.get(token))))
394    } else {
395        None
396    }
397}
398
399const MAX_NAMES: usize = 512;
400
401/// the alternatives of a syntax indexed by their first tokens
402pub struct AlternativeIndex {
403    sets: Vec<Rc<FirstSet>>,
404    filtered: bool,
405    by_type: HashMap<u8, Option<Rc<Vec<usize>>>>,
406    by_name: HashMap<u8, HashMap<crate::ast::strings::SharedStr, Option<Rc<Vec<usize>>>>>,
407    names: usize,
408}
409
410impl AlternativeIndex {
411    fn new(alternatives: &[Vec<Rc<ValidationToken>>]) -> Self {
412        let sets: Vec<Rc<FirstSet>> = alternatives.iter().map(|s| first_of_sequence(Some(s))).collect();
413        let filtered = sets.iter().any(|s| !s.any && !s.nullable);
414        Self { sets, filtered, by_type: HashMap::default(), by_name: HashMap::default(), names: 0 }
415    }
416
417    fn lookup(&mut self, typ: u8, name: Option<crate::ast::strings::SharedStr>) -> Option<Rc<Vec<usize>>> {
418        match name {
419            None => {
420                if let Some(r) = self.by_type.get(&typ) {
421                    return r.clone();
422                }
423                let r = self.compute(typ, None);
424                self.by_type.insert(typ, r.clone());
425                r
426            }
427            Some(name) => {
428                if let Some(r) = self.by_name.get(&typ).and_then(|m| m.get(&name)) {
429                    return r.clone();
430                }
431                let r = self.compute(typ, Some(&name));
432                if self.names < MAX_NAMES {
433                    self.names += 1;
434                    self.by_name.entry(typ).or_default().insert(name, r.clone());
435                }
436                r
437            }
438        }
439    }
440
441    fn compute(&self, typ: u8, name: Option<&str>) -> Option<Rc<Vec<usize>>> {
442        let result: Vec<usize> = (0..self.sets.len()).filter(|&i| self.sets[i].nullable || accepts(&self.sets[i], typ, name)).collect();
443        if result.len() == self.sets.len() {
444            None
445        } else {
446            Some(Rc::new(result))
447        }
448    }
449}
450
451/// the alternatives of a syntax that may match the first token of a value, in order. None when all of them may match
452pub fn matching_alternatives(arena: &AstArena, alternatives: &[Vec<Rc<ValidationToken>>], token: Option<u32>) -> Option<Rc<Vec<usize>>> {
453    let key = (alternatives.as_ptr() as usize, alternatives.len());
454    let index = CACHES.with(|c| {
455        c.borrow().alternatives.get(&key).and_then(|(keep, index)| {
456            (keep.len() == alternatives.len() && keep.iter().zip(alternatives).all(|(a, b)| same_seq(a, b))).then(|| index.clone())
457        })
458    });
459    let index = match index {
460        Some(index) => index,
461        None => {
462            let index = Rc::new(RefCell::new(AlternativeIndex::new(alternatives)));
463            CACHES.with(|c| c.borrow_mut().alternatives.insert(key, (alternatives.to_vec(), index.clone())));
464            index
465        }
466    };
467    let token = token?;
468    if !index.borrow().filtered {
469        return None;
470    }
471    let typ = arena.data_types.get(token);
472    if matches_any_syntax(arena, token, typ) {
473        return None;
474    }
475    let name = token_name(arena, token, typ);
476    let result = index.borrow_mut().lookup(typ, name);
477    result
478}
479
480/// true if a sequence of syntaxes may match tokens starting with a token
481pub fn may_start_with(arena: &AstArena, syntaxes: &[Rc<ValidationToken>], token: Option<u32>) -> bool {
482    let Some(token) = token else {
483        return true;
484    };
485    let set = first_of_sequence(Some(syntaxes));
486    if set.any {
487        return true;
488    }
489    let typ = arena.data_types.get(token);
490    matches_any_syntax(arena, token, typ) || accepts(&set, typ, token_name(arena, token, typ).as_deref())
491}
492
493#[allow(dead_code)]
494fn _unused(_: VVal) {}