Skip to main content

rust_css_parser/validation/compiled/
runtime.rs

1//! Port of `src/validation/compiled/runtime.ts`: the matching engine of the compiled syntaxes.
2//!
3//! The syntaxes of the validation data are compiled at build time (`npm run syntax-compile`, `scripts/compile_syntax.rs`)
4//! into a static table of [`Node`]s ([`super::syntaxes`]). A node matches the tokens of a value from a position and
5//! returns the position after the matched tokens, or [`FAIL`]. The positions are indexes in the significant tokens of
6//! the value (the whitespace and the comments are skipped, like the interpreter does). `Err(Bail)` aborts the match:
7//! the interpreter validates the value.
8//!
9//! A compiled matcher mirrors the syntax tree matched by the interpreter ([`crate::validation::match_`]). Its "valid"
10//! answer is final, its "invalid" answer is not: the interpreter validates the value again and reports the errors.
11
12use super::builtins::is_raw_type;
13use super::syntaxes::{KEYS, NODES, ROOTS};
14use crate::ast::arena::AstArena;
15use crate::ast::types::EnumToken;
16use crate::options::ParserOptions;
17use crate::parser::utils::text::{equals_ignore_case, lowercase};
18use crate::syntax::constants::{is_function_def_type, is_function_type, FUNC_LIKE};
19use crate::validation::match_::{is_css_wide_keyword, is_func_type, Context, ContextData, Syntax};
20use crate::validation::match_property::match_property;
21use crate::validation::parser::typedef::ValidationTokenEnum as V;
22use crate::validation::parser::types::{VVal, ValidationToken};
23use std::cell::RefCell;
24use std::collections::HashMap;
25use std::rc::Rc;
26
27/// a syntax node. the children are indexes in [`NODES`], the definitions indexes in [`ROOTS`]
28#[derive(Debug)]
29pub enum Node {
30    /// an empty syntax
31    Empty,
32    /// a definition the compiler could not compile: the interpreter validates it
33    Interpreted,
34    /// a sequence: the items, nullable\[i\]: the items from i are nullable
35    Seq(&'static [u32], &'static [bool]),
36    /// alternatives: the one that matches the most tokens
37    Alt(&'static [u32]),
38    /// a keyword (lowercase), ignoring the case
39    Kw(&'static str),
40    /// alternative keywords (lowercase, sorted)
41    Kws(&'static [&'static str]),
42    /// an optional syntax: skipped when it does not match
43    Opt(u32),
44    /// `*` (zero allowed) or `+`
45    Rep(u32, bool),
46    /// `{min,max}`
47    Occ(u32, u32, f64),
48    /// `#{min,max}`, the number of commas of an item
49    List(u32, u32, f64, u32),
50    /// a type validated by `match_property()`, the kind of its fast path (see [`leaf_kind`])
51    Leaf(&'static str, u8),
52    /// a type with a range: the type, min, max, the unit of a dimension range, optional
53    Rng(u32, f64, f64, Option<&'static str>, bool),
54    /// a reference to a definition
55    Ref(u32),
56    /// a function (lowercase name) and its arguments
57    Fn(&'static str, u32),
58    /// a function definition `<rgb()>`: the definition of the function syntax
59    FnDef(&'static str, Option<u32>),
60    /// a literal number or dimension: the value, the token type name of the unit, the unit
61    Num(f64, Option<&'static str>, Option<&'static str>),
62    /// a quoted literal: `'+'`
63    Str(&'static str),
64    Comma,
65    Colon,
66    Slash,
67    OpenParens,
68    CloseParens,
69    OpenCurly,
70    /// `<bg-layer>#? , <final-bg-layer>`: `[ <bg-layer> , ]*`
71    OptList(u32),
72    /// `||` (any) or `&&` (all): the operands, nullable operands
73    Unordered(&'static [u32], &'static [bool], bool),
74}
75
76/// no match
77pub const FAIL: i32 = -1;
78
79/// the value must be validated by the interpreter
80#[derive(Debug)]
81pub struct Bail;
82
83type Result<T> = std::result::Result<T, Bail>;
84
85/// the maximum depth of the references being matched: deeper, the interpreter validates the value
86const MAX_DEPTH: u32 = 256;
87
88/// the fast path of the numeric types: the tokens that are neither idents (a css wide keyword is accepted by the types)
89/// nor math functions are matched without `match_property()`. 0: no fast path
90pub fn leaf_kind(name: &str) -> u8 {
91    match name {
92        "number" => 1,
93        "integer" => 2,
94        "zero" => 3,
95        "length" => 4,
96        "percentage" => 5,
97        "length-percentage" => 6,
98        "angle" => 7,
99        "angle-percentage" => 8,
100        "time" => 9,
101        "flex" => 10,
102        "resolution" => 11,
103        "frequency" => 12,
104        "string" => 13,
105        "dashed-ident" | "custom-property-name" => 14,
106        _ => 0,
107    }
108}
109
110/// the fast path of a numeric type, see [`leaf_kind`]
111fn fast_leaf(arena: &AstArena, kind: u8, token: u32, t: u8) -> bool {
112    let zero = || t == EnumToken::NumberTokenType && arena.numeric_value.get(token) == 0.0;
113    match kind {
114        1 => t == EnumToken::NumberTokenType,
115        2 => t == EnumToken::NumberTokenType && arena.numeric_value.get(token).fract() == 0.0 && arena.numeric_value.get(token).is_finite(),
116        3 => zero(),
117        4 => t == EnumToken::LengthTokenType || t == EnumToken::UserDefinedDimensionTokenType || zero(),
118        5 => t == EnumToken::PercentageTokenType,
119        6 => t == EnumToken::PercentageTokenType || t == EnumToken::LengthTokenType || t == EnumToken::UserDefinedDimensionTokenType || zero(),
120        7 => t == EnumToken::AngleTokenType || t == EnumToken::UserDefinedDimensionTokenType,
121        8 => t == EnumToken::AngleTokenType || t == EnumToken::UserDefinedDimensionTokenType || t == EnumToken::PercentageTokenType,
122        9 => t == EnumToken::TimeTokenType || t == EnumToken::UserDefinedDimensionTokenType,
123        10 => t == EnumToken::FlexTokenType || t == EnumToken::UserDefinedDimensionTokenType,
124        11 => t == EnumToken::ResolutionTokenType,
125        12 => t == EnumToken::FrequencyTokenType,
126        13 => t == EnumToken::StringTokenType,
127        14 => t == EnumToken::DashedIdenTokenType,
128        _ => false,
129    }
130}
131
132thread_local! {
133    /// the property syntax passed to `match_property()`, by type name
134    static PROPERTIES: RefCell<HashMap<&'static str, Syntax>> = RefCell::new(HashMap::new());
135    /// the definitions, by key (`group/name`)
136    static DEFINITIONS: HashMap<&'static str, u32> = KEYS.iter().enumerate().map(|(i, k)| (*k, i as u32)).collect();
137}
138
139/// the property syntax of a type, see [`PROPERTIES`]
140fn property(name: &'static str) -> Syntax {
141    PROPERTIES.with(|p| {
142        p.borrow_mut()
143            .entry(name)
144            .or_insert_with(|| {
145                let mut token = ValidationToken::new(V::PropertyType);
146                token.val = VVal::Str(Rc::from(name));
147                Rc::new(token)
148            })
149            .clone()
150    })
151}
152
153/// the compiled definition of a key (`declarations/width`), None if it is not compiled
154pub fn compiled_definition(key: &str) -> Option<u32> {
155    DEFINITIONS.with(|d| d.get(key).copied())
156}
157
158/// the significant tokens: the whitespace and the comments are skipped, a trailing `!important` is removed (see
159/// `create_validation_context()`)
160fn significant_tokens(arena: &AstArena, tokens: &[u32]) -> Vec<u32> {
161    let mut result: Vec<u32> = tokens
162        .iter()
163        .copied()
164        .filter(|&t| !matches!(arena.data_types.get(t), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType | EnumToken::CDOCOMMTokenType))
165        .collect();
166    if result.last().is_some_and(|&t| arena.data_types.get(t) == EnumToken::ImportantTokenType) {
167        result.pop();
168    }
169    result
170}
171
172/// the value being matched
173struct Matcher<'a> {
174    arena: &'a AstArena,
175    /// the significant tokens of the value
176    toks: Vec<u32>,
177    /// the end of the tokens being matched: the items of a list are matched up to the next comma
178    len: usize,
179    options: &'a ParserOptions,
180    depth: u32,
181    /// the context passed to `match_property()` and the length of its tokens
182    leaf: Option<(Context, usize)>,
183}
184
185impl<'a> Matcher<'a> {
186    fn new(arena: &'a AstArena, toks: Vec<u32>, options: &'a ParserOptions, depth: u32) -> Self {
187        let len = toks.len();
188        Matcher { arena, toks, len, options, depth, leaf: None }
189    }
190
191    #[inline]
192    fn typ(&self, p: i32) -> u8 {
193        self.arena.data_types.get(self.toks[p as usize])
194    }
195
196    #[inline]
197    fn end(&self) -> i32 {
198        self.len as i32
199    }
200
201    /// the lowercase value of an ident token at a position, compared with a keyword
202    fn ident_is(&self, p: i32, f: impl FnOnce(&str) -> bool) -> bool {
203        let token = self.toks[p as usize];
204        self.arena.data_types.get(token) == EnumToken::IdenTokenType && self.arena.with_string(self.arena.string_value.get(token), |v| f(&lowercase(v)))
205    }
206
207    /// the lowercase name of a function token
208    fn name_is(&self, p: i32, name: &str) -> bool {
209        let token = self.toks[p as usize];
210        self.arena.with_string(self.arena.string_value.get(token), |v| lowercase(v) == name)
211    }
212
213    /// match a node from a position
214    fn m(&mut self, node: u32, p: i32) -> Result<i32> {
215        match &NODES[node as usize] {
216            Node::Empty => Ok(p),
217            Node::Interpreted => Err(Bail),
218            Node::Seq(items, nullable) => {
219                let mut p = p;
220                for (i, &item) in items.iter().enumerate() {
221                    if p >= self.end() {
222                        return Ok(if nullable[i] { p } else { FAIL });
223                    }
224                    p = self.m(item, p)?;
225                    if p < 0 {
226                        return Ok(FAIL);
227                    }
228                }
229                Ok(p)
230            }
231            Node::Alt(alternatives) => {
232                let mut best = FAIL;
233                for &alternative in alternatives.iter() {
234                    let result = self.m(alternative, p)?;
235                    if result > best {
236                        best = result;
237                        if result >= self.end() {
238                            break;
239                        }
240                    }
241                }
242                Ok(best)
243            }
244            Node::Kw(value) => Ok(if self.ident_is(p, |v| v == *value) { p + 1 } else { FAIL }),
245            Node::Kws(values) => Ok(if self.ident_is(p, |v| values.binary_search(&v).is_ok()) { p + 1 } else { FAIL }),
246            Node::Opt(inner) => {
247                let result = self.m(*inner, p)?;
248                Ok(if result < 0 { p } else { result })
249            }
250            Node::Rep(item, zero) => {
251                let mut p = p;
252                let mut matched = false;
253                loop {
254                    let result = self.m(*item, p)?;
255                    if result < 0 {
256                        break;
257                    }
258                    matched = true;
259                    if result >= self.end() {
260                        p = self.end();
261                        break;
262                    }
263                    // no token matched
264                    if result == p {
265                        break;
266                    }
267                    p = result;
268                }
269                Ok(if matched || *zero { p } else { FAIL })
270            }
271            Node::Occ(item, min, max) => {
272                let mut p = p;
273                let mut count: u32 = 0;
274                loop {
275                    let result = self.m(*item, p)?;
276                    if result < 0 {
277                        break;
278                    }
279                    count += 1;
280                    if result >= self.end() {
281                        p = self.end();
282                        break;
283                    }
284                    if result == p {
285                        break;
286                    }
287                    p = result;
288                    if count as f64 == *max || p >= self.end() {
289                        break;
290                    }
291                }
292                Ok(if count == 0 || count < *min || count as f64 > *max { FAIL } else { p })
293            }
294            Node::List(item, min, max, commas) => {
295                let len = self.len;
296                let mut p = p;
297                let mut count: u32 = 0;
298                loop {
299                    let end = self.item_end(p, *commas);
300                    // Bail aborts the whole match: the length is not restored
301                    self.len = end as usize;
302                    let result = self.m(*item, p)?;
303                    self.len = len;
304                    if result < 0 {
305                        break;
306                    }
307                    // the item does not match the tokens before the comma: the list ends with this item
308                    if result < end {
309                        if result > p {
310                            count += 1;
311                            p = result;
312                        }
313                        break;
314                    }
315                    count += 1;
316                    if count as f64 == *max {
317                        p = end;
318                        break;
319                    }
320                    // the comma
321                    p = if end < len as i32 { end + 1 } else { end };
322                    if p >= len as i32 {
323                        break;
324                    }
325                }
326                Ok(if count == 0 || count < *min { FAIL } else { p })
327            }
328            Node::Leaf(name, kind) => self.leaf(name, *kind, p),
329            Node::Rng(inner, min, max, unit, optional) => {
330                let result = self.m(*inner, p)?;
331                if result < 0 {
332                    return Ok(if *optional { p } else { FAIL });
333                }
334                Ok(if self.in_range(self.toks[p as usize], *min, *max, *unit) { result } else { FAIL })
335            }
336            Node::Ref(definition) => {
337                self.depth += 1;
338                if self.depth > MAX_DEPTH {
339                    return Err(Bail);
340                }
341                let result = self.m(ROOTS[*definition as usize], p)?;
342                self.depth -= 1;
343                Ok(result)
344            }
345            Node::Fn(name, args) => {
346                let t = self.typ(p);
347                if (!is_function_def_type(t) && !FUNC_LIKE.contains(&t) && !is_func_type(t)) || !self.name_is(p, name) {
348                    return Ok(FAIL);
349                }
350                if is_function_def_type(t) {
351                    let close = self.closing_parens(p);
352                    return Ok(if close != -1 && self.match_range(*args, p + 1, close)? { close + 1 } else { FAIL });
353                }
354                let toks = significant_tokens(self.arena, &self.arena.tokens(self.toks[p as usize]));
355                let length = toks.len() as i32;
356                let mut sub = Matcher::new(self.arena, toks, self.options, self.depth);
357                Ok(if sub.m(*args, 0)? == length { p + 1 } else { FAIL })
358            }
359            Node::FnDef(name, definition) => {
360                let Some(definition) = definition else {
361                    return Ok(FAIL);
362                };
363                if !self.name_is(p, name) {
364                    return Ok(FAIL);
365                }
366                let root = ROOTS[*definition as usize];
367                let t = self.typ(p);
368                if is_function_def_type(t) {
369                    let close = self.closing_parens(p);
370                    return Ok(if close != -1 && self.match_range(root, p, close + 1)? { close + 1 } else { FAIL });
371                }
372                if !is_function_type(t) {
373                    return Ok(FAIL);
374                }
375                let mut sub = Matcher::new(self.arena, vec![self.toks[p as usize]], self.options, self.depth);
376                Ok(if sub.m(root, 0)? == 1 { p + 1 } else { FAIL })
377            }
378            Node::Num(value, unit, unit_text) => {
379                let token = self.toks[p as usize];
380                if self.arena.has_fraction(token) || self.arena.numeric_value.get(token) != *value {
381                    return Ok(FAIL);
382                }
383                let t = self.arena.data_types.get(token);
384                Ok(match unit {
385                    None => {
386                        if t == EnumToken::NumberTokenType {
387                            p + 1
388                        } else {
389                            FAIL
390                        }
391                    }
392                    Some(unit) => {
393                        if Some(t) == EnumToken::value(unit)
394                            && self.arena.with_string(self.arena.unit.get(token), |u| equals_ignore_case(u, unit_text.unwrap_or("")))
395                        {
396                            p + 1
397                        } else {
398                            FAIL
399                        }
400                    }
401                })
402            }
403            Node::Str(value) => {
404                let token = self.toks[p as usize];
405                Ok(match self.arena.data_types.get(token) {
406                    EnumToken::Add if *value == "+" => p + 1,
407                    EnumToken::Sub if *value == "-" => p + 1,
408                    EnumToken::LiteralTokenType if self.arena.with_string(self.arena.string_value.get(token), |v| v == *value) => p + 1,
409                    EnumToken::Plus => p + 1,
410                    _ => FAIL,
411                })
412            }
413            Node::Comma => Ok(self.token_type(p, EnumToken::CommaTokenType)),
414            Node::Colon => Ok(self.token_type(p, EnumToken::ColonTokenType)),
415            Node::OpenParens => Ok(self.token_type(p, EnumToken::StartParensTokenType)),
416            Node::CloseParens => Ok(self.token_type(p, EnumToken::EndParensTokenType)),
417            Node::OpenCurly => Ok(self.token_type(p, EnumToken::BlockStartTokenType)),
418            Node::Slash => {
419                let token = self.toks[p as usize];
420                Ok(
421                    if self.arena.data_types.get(token) == EnumToken::LiteralTokenType && self.arena.with_string(self.arena.string_value.get(token), |v| v == "/") {
422                        p + 1
423                    } else {
424                        FAIL
425                    },
426                )
427            }
428            Node::OptList(group) => {
429                let mut p = p;
430                while p < self.end() {
431                    let result = self.m(*group, p)?;
432                    if result <= p {
433                        break;
434                    }
435                    p = result;
436                }
437                Ok(p)
438            }
439            Node::Unordered(operands, nullable, all) => {
440                let size = self.len + 1;
441                // the position after an operand, by operand and position. -2: not matched yet
442                let mut memo: Vec<i32> = vec![-2; operands.len() * size];
443                let remaining: Vec<usize> = (0..operands.len()).collect();
444                let best = self.search(operands, nullable, *all, &remaining, p, &mut memo, size)?;
445                if best >= 0 {
446                    return Ok(best);
447                }
448                Ok(if *all && nullable.iter().all(|n| *n) { p } else { FAIL })
449            }
450        }
451    }
452
453    #[inline]
454    fn token_type(&self, p: i32, t: u8) -> i32 {
455        if self.typ(p) == t {
456            p + 1
457        } else {
458            FAIL
459        }
460    }
461
462    /// the position after the operands that match the most tokens, -1 if no operand matches
463    #[allow(clippy::too_many_arguments)]
464    fn search(&mut self, operands: &[u32], nullable: &[bool], all: bool, remaining: &[usize], p: i32, memo: &mut Vec<i32>, size: usize) -> Result<i32> {
465        let mut best: i32 = -1;
466        for k in 0..remaining.len() {
467            let operand = remaining[k];
468            let key = operand * size + p as usize;
469            let mut next = memo[key];
470            if next == -2 {
471                next = if p < self.end() { self.m(operands[operand], p)? } else { FAIL };
472                // the operand must match a token
473                if next <= p {
474                    next = -1;
475                }
476                memo[key] = next;
477            }
478            if next < 0 {
479                continue;
480            }
481            let rest: Vec<usize> = remaining[..k].iter().chain(remaining[k + 1..].iter()).copied().collect();
482            let complete = !all || rest.iter().all(|&i| nullable[i]);
483            if next < self.end() && !rest.is_empty() {
484                let deeper = self.search(operands, nullable, all, &rest, next, memo, size)?;
485                if deeper >= 0 {
486                    if deeper >= self.end() {
487                        return Ok(deeper);
488                    }
489                    if deeper > best {
490                        best = deeper;
491                    }
492                }
493            }
494            if complete {
495                if next >= self.end() {
496                    return Ok(next);
497                }
498                if next > best {
499                    best = next;
500                }
501            }
502        }
503        Ok(best)
504    }
505
506    /// the end of a comma separated item: the position of the comma that follows the item
507    fn item_end(&self, p: i32, mut commas: u32) -> i32 {
508        let mut depth = 0i32;
509        for i in p..self.end() {
510            let t = self.typ(i);
511            if t == EnumToken::StartParensTokenType || is_function_def_type(t) {
512                depth += 1;
513            } else if t == EnumToken::EndParensTokenType {
514                depth -= 1;
515            } else if depth == 0 && t == EnumToken::CommaTokenType {
516                if commas == 0 {
517                    return i;
518                }
519                commas -= 1;
520            }
521        }
522        self.end()
523    }
524
525    /// the position of the parenthesis that closes the function at a position: the arguments of a function follow the
526    /// function token (see `peek_range()`). -1 if the function is not closed
527    fn closing_parens(&self, p: i32) -> i32 {
528        let mut depth = 0i32;
529        for i in p..self.end() {
530            let t = self.typ(i);
531            if t == EnumToken::StartParensTokenType || is_function_def_type(t) {
532                depth += 1;
533            } else if t == EnumToken::EndParensTokenType {
534                depth -= 1;
535                if depth == 0 {
536                    return i;
537                }
538            }
539        }
540        -1
541    }
542
543    /// true if a node matches the tokens from p to end (excluded)
544    fn match_range(&mut self, node: u32, p: i32, end: i32) -> Result<bool> {
545        let len = self.len;
546        // Bail aborts the whole match: the length is not restored
547        self.len = end as usize;
548        let result = self.m(node, p)?;
549        self.len = len;
550        Ok(result == end)
551    }
552
553    /// a type validated by `match_property()`
554    fn leaf(&mut self, name: &'static str, kind: u8, p: i32) -> Result<i32> {
555        let token = self.toks[p as usize];
556        let t = self.arena.data_types.get(token);
557        if kind != 0 && t != EnumToken::IdenTokenType && t != EnumToken::MathFunctionTokenType && t != EnumToken::MathFunctionTokenDefType {
558            return Ok(if fast_leaf(self.arena, kind, token, t) { p + 1 } else { FAIL });
559        }
560        if is_raw_type(name) {
561            return Err(Bail);
562        }
563        let context = match &self.leaf {
564            Some((context, len)) if *len == self.len => {
565                context.borrow_mut().index = p as isize - 1;
566                context.clone()
567            }
568            _ => {
569                let context: Context = Rc::new(RefCell::new(ContextData::from_tokens(self.toks[..self.len].to_vec(), p as isize - 1)));
570                self.leaf = Some((context.clone(), self.len));
571                context
572            }
573        };
574        let result = match_property(self.arena, &property(name), &context, self.options);
575        if !result.success {
576            return Ok(FAIL);
577        }
578        let index = context.borrow().index;
579        Ok(if index >= self.len as isize { self.end() } else { index as i32 + 1 })
580    }
581
582    /// see `is_in_range()`
583    fn in_range(&self, token: u32, min: f64, max: f64, unit: Option<&str>) -> bool {
584        let t = self.arena.data_types.get(token);
585        if matches!(t, EnumToken::MathFunctionTokenType | EnumToken::MathFunctionTokenDefType | EnumToken::WildCardFunctionTokenType | EnumToken::WildCardFunctionTokenDefType) {
586            return true;
587        }
588        let value = self.arena.numeric_value.get(token);
589        let mut success = !self.arena.has_fraction(token) && value >= min;
590        if let Some(unit) = unit {
591            success = Some(t) == EnumToken::value(unit);
592        }
593        success && value <= max
594    }
595}
596
597/// match the tokens of a value with a compiled definition
598///
599/// returns true if the value is valid, false if the interpreter must validate it
600pub fn match_compiled(arena: &AstArena, definition: u32, tokens: &[u32], options: &ParserOptions) -> bool {
601    let toks = significant_tokens(arena, tokens);
602    // a css wide keyword (see `match_syntax()`)
603    if toks.len() == 1
604        && arena.data_types.get(toks[0]) == EnumToken::IdenTokenType
605        && arena.with_string(arena.string_value.get(toks[0]), is_css_wide_keyword)
606    {
607        return true;
608    }
609    let length = toks.len() as i32;
610    let mut matcher = Matcher::new(arena, toks, options, 0);
611    matches!(matcher.m(ROOTS[definition as usize], 0), Ok(result) if result == length)
612}