Skip to main content

rust_css_parser/validation/
match_property.rs

1//! Port of `matchProperty()` (the built-in types) and `matchRepeatableSyntax()` of `src/validation/match.ts`.
2
3use super::config::{get_parsed_syntax, get_syntax, get_syntax_config, has_syntax};
4use super::match_::{
5    create_validation_context, is_css_wide_keyword, match_selector_syntax, Context, ContextExt, Syntax, ValidationMatch, function_syntax,
6};
7use super::match_syntax::{match_syntax, peek_feature_tokens};
8use super::parser::typedef::ValidationSyntaxGroupEnum;
9use crate::ast::arena::{AstArena, TokenField};
10use crate::ast::types::{ColorType, EnumToken};
11use crate::options::ParserOptions;
12use crate::parser::utils::text::equals_ignore_case;
13use crate::syntax::constants::{is_function_def_type, mFGT, mFLT};
14use crate::syntax::syntax::is_color;
15use crate::types::ErrorDescription;
16use std::cell::RefCell;
17use crate::utils::fx::{HashMap, HashSet};
18use std::rc::Rc;
19
20fn ok(context: &Context, token: Option<u32>) -> ValidationMatch {
21    ValidationMatch::new(true, true, token, Some(context.clone()), None, Vec::new())
22}
23
24fn ko(context: &Context, token: Option<u32>, property: &Syntax) -> ValidationMatch {
25    ValidationMatch::new(false, true, token, Some(context.clone()), Some(property.clone()), Vec::new())
26}
27
28/// first item of a function syntax (`name()`): the arguments are its children, borrowed by the callers
29fn function_head(syntax: Option<Rc<Vec<Syntax>>>) -> Option<Syntax> {
30    syntax.and_then(|s| s.first().cloned())
31}
32
33fn is_integer(n: f64) -> bool {
34    n.is_finite() && n.fract() == 0.0
35}
36
37/// `/^(([+-]?[0-9]*)?n)?([+-]?[0-9]+)?$/`: None when it does not match, Some(has the third group)
38fn match_an_plus_b(value: &str) -> Option<bool> {
39    let b = value.as_bytes();
40    // try the `...n` prefix (greedy), then the optional integer
41    let rest_after_n = |start: usize| -> Option<bool> {
42        let r = &b[start..];
43        if r.is_empty() {
44            return Some(false);
45        }
46        let mut i = 0;
47        if matches!(r[0], b'+' | b'-') {
48            i = 1;
49        }
50        if i < r.len() && r[i..].iter().all(|c| c.is_ascii_digit()) {
51            Some(true)
52        } else {
53            None
54        }
55    };
56    if let Some(n) = b.iter().position(|&c| c == b'n') {
57        let prefix = &b[..n];
58        let mut i = 0;
59        if !prefix.is_empty() && matches!(prefix[0], b'+' | b'-') {
60            i = 1;
61        }
62        if prefix[i..].iter().all(|c| c.is_ascii_digit()) {
63            if let Some(g3) = rest_after_n(n + 1) {
64                return Some(g3);
65            }
66        }
67    }
68    rest_after_n(0)
69}
70
71thread_local! {
72    static PROPERTY_KEYWORD_VALUES: RefCell<HashMap<String, Rc<HashSet<String>>>> = RefCell::new(HashMap::default());
73}
74
75/// matches a built-in type (`<length>`, `<color>`, ...) or the syntax of a type
76pub fn match_property(arena: &AstArena, property: &Syntax, context: &Context, options: &ParserOptions) -> ValidationMatch {
77    let mut success = false;
78    let token = context.peek(arena);
79    let typ = |t: Option<u32>| t.map_or(0u8, |t| arena.data_types.get(t));
80    let t = typ(token);
81    let val = property.val_str();
82    let str_of = |tk: u32| arena.resolve_string(arena.string_value.get(tk));
83    let mut check_calc = (t == EnumToken::MathFunctionTokenDefType || t == EnumToken::MathFunctionTokenType)
84        && ["number", "zero", "integer", "percentage", "dimension", "length-percentage", "length", "time", "calc-sum", "calc-product"]
85            .contains(&val);
86    if check_calc && !["number", "zero", "integer", "percentage", "length-percentage"].contains(&val) {
87        check_calc = token.is_some_and(|tk| arena.string_equals(arena.string_value.get(tk), "calc"));
88    }
89    if check_calc {
90        let tk = token.unwrap();
91        // looked up once per function name
92        let head = function_head(function_syntax(arena, tk));
93        let syntax = head.as_ref().map(|f| f.children());
94        if t == EnumToken::MathFunctionTokenType {
95            let r = match_syntax(arena, syntax, &create_validation_context(arena, &arena.tokens(tk)), options);
96            if r.success && r.ctx().done(arena) {
97                context.next_token(arena);
98                return ok(context, token);
99            }
100        } else {
101            let range = context.borrow().peek_range(arena, EnumToken::EndParensTokenType, 0);
102            let inner: &[u32] = if range.len() >= 2 { &range[1..range.len() - 1] } else { &[] };
103            let r = match_syntax(arena, syntax, &create_validation_context(arena, inner), options);
104            if r.success {
105                context.update(range.last().copied());
106                return ok(context, range.last().copied());
107            }
108        }
109        return ko(context, context.peek(arena), property);
110    }
111    match val {
112        "declaration-value" => {
113            let mut expect_token = true;
114            let mut consumed = 0;
115            let mut stack: Vec<u32> = Vec::new();
116            while let Some(tk) = context.peek(arena) {
117                let tt = arena.data_types.get(tk);
118                if tt == EnumToken::StartParensTokenType || is_function_def_type(tt) {
119                    stack.push(tk);
120                }
121                expect_token = false;
122                if tt == EnumToken::CommaTokenType {
123                    expect_token = true;
124                }
125                if tt == EnumToken::EndParensTokenType {
126                    if stack.pop().is_none() {
127                        expect_token = false;
128                        break;
129                    }
130                }
131                context.next_token(arena);
132                consumed += 1;
133            }
134            success = consumed > 0 && !expect_token;
135            if success {
136                return ValidationMatch::new(true, true, None, Some(context.clone()), Some(property.clone()), Vec::new());
137            }
138        }
139        "calc-sum" => {
140            let calc_sum = get_parsed_syntax(ValidationSyntaxGroupEnum::Syntaxes, "calc-sum");
141            if typ(token) == EnumToken::BinaryExpressionTokenType {
142                let tk = token.unwrap();
143                let mut r = match_syntax(arena, calc_sum.as_deref().map(|v| v.as_slice()), &create_validation_context(arena, &[arena.field(tk, TokenField::L)]), options);
144                if r.success {
145                    r = match_syntax(arena, calc_sum.as_deref().map(|v| v.as_slice()), &create_validation_context(arena, &[arena.field(tk, TokenField::R)]), options);
146                }
147                success = r.success;
148            } else {
149                let r = match_syntax(arena, calc_sum.as_deref().map(|v| v.as_slice()), &context.slice(), options);
150                success = r.success;
151                if success {
152                    if r.ctx().done(arena) {
153                        context.end();
154                    } else {
155                        context.update(r.ctx().current());
156                    }
157                    return ok(context, None);
158                }
159            }
160        }
161        "an+b" => 'anb: {
162            let tk = token;
163            let tt = typ(tk);
164            if tt == EnumToken::IdenTokenType && tk.is_some_and(|tk| matches!(&*str_of(tk), "even" | "odd")) {
165                success = true;
166                break 'anb;
167            }
168            if tt == EnumToken::NumberTokenType && is_integer(arena.numeric_value.get(tk.unwrap())) {
169                success = true;
170                break 'anb;
171            }
172            if tt == EnumToken::LiteralTokenType || tt == EnumToken::IdenTokenType {
173                let m = match_an_plus_b(&str_of(tk.unwrap()));
174                success = m.is_some();
175                if m == Some(false) {
176                    let sign = context.borrow().peek(arena, 1);
177                    let st = typ(sign);
178                    if st == EnumToken::NumberTokenType {
179                        if !is_integer(arena.numeric_value.get(sign.unwrap())) {
180                            success = false;
181                            break 'anb;
182                        }
183                        context.update(sign);
184                        return ValidationMatch::new(true, true, None, Some(context.clone()), Some(property.clone()), Vec::new());
185                    }
186                    if st == EnumToken::Add || st == EnumToken::NextSiblingCombinatorTokenType || st == EnumToken::Sub {
187                        let next = context.borrow().peek(arena, 2);
188                        success = typ(next) == EnumToken::NumberTokenType && is_integer(arena.numeric_value.get(next.unwrap()));
189                        if success {
190                            context.update(next);
191                            return ValidationMatch::new(true, true, None, Some(context.clone()), Some(property.clone()), Vec::new());
192                        }
193                    }
194                }
195                break 'anb;
196            }
197            if tt == EnumToken::DimensionTokenType && arena.string_equals(arena.unit.get(tk.unwrap()), "n") {
198                success = is_integer(arena.numeric_value.get(tk.unwrap()));
199                let Some(next) = context.borrow().peek(arena, 1) else {
200                    break 'anb;
201                };
202                if arena.data_types.get(next) == EnumToken::NumberTokenType {
203                    if is_integer(arena.numeric_value.get(next)) {
204                        context.next_token(arena);
205                    } else {
206                        success = false;
207                    }
208                    break 'anb;
209                }
210                if arena.data_types.get(next) == EnumToken::NextSiblingCombinatorTokenType {
211                    arena.data_types.set(next, EnumToken::Add);
212                }
213                let next = context.borrow().peek(arena, 2);
214                if typ(next) == EnumToken::NumberTokenType && is_integer(arena.numeric_value.get(next.unwrap())) {
215                    success = true;
216                    context.next_token(arena);
217                    context.next_token(arena);
218                }
219            }
220        }
221        "quote" | "display-box" | "display-inside" | "display-internal" | "display-outside" | "display-legacy" | "content-position" => {
222            let values = PROPERTY_KEYWORD_VALUES.with(|p| {
223                p.borrow_mut()
224                    .entry(val.to_string())
225                    .or_insert_with(|| {
226                        Rc::new(get_syntax(val).unwrap_or("").split(|c: char| c.is_whitespace() || c == '|').map(String::from).collect())
227                    })
228                    .clone()
229            });
230            success = t == EnumToken::IdenTokenType && values.contains(&str_of(token.unwrap()).to_lowercase());
231        }
232        "mf-name" => {
233            success = t == EnumToken::IdenTokenType
234                && get_syntax_config()["mediaFeatures"].get(str_of(token.unwrap()).to_lowercase()).is_some();
235        }
236        "dashed-ident" | "extension-name" | "custom-property-name" => success = t == EnumToken::DashedIdenTokenType,
237        "namespace-prefix" | "ident" | "ident-token" | "custom-ident" | "counter-name" | "counter-style-name" => {
238            success = t == EnumToken::IdenTokenType || t == EnumToken::DashedIdenTokenType;
239            if success && t == EnumToken::IdenTokenType {
240                let v = str_of(token.unwrap()).to_lowercase();
241                success = v != "none" && !is_css_wide_keyword_exact(&v);
242            }
243        }
244        "any-value" => {
245            success = token.is_none()
246                || [
247                    EnumToken::String,
248                    EnumToken::NumberTokenType,
249                    EnumToken::DashedIdenTokenType,
250                    EnumToken::IdenTokenType,
251                    EnumToken::FunctionTokenType,
252                    EnumToken::ImageFunctionTokenType,
253                    EnumToken::UrlFunctionTokenType,
254                    EnumToken::TimingFunctionTokenType,
255                    EnumToken::TimelineFunctionTokenType,
256                    EnumToken::TransformFunctionTokenType,
257                ]
258                .contains(&t);
259        }
260        "unicode-range-token" => success = t == EnumToken::UniCodeRange,
261        "hash-token" => {
262            success = t == EnumToken::HashTokenType || (t == EnumToken::ColorTokenType && arena.color_type.get(token.unwrap()) == ColorType::HEX);
263        }
264        "string" => success = t == EnumToken::StringTokenType,
265        "wq-name" => {
266            let success = t == EnumToken::IdenTokenType;
267            let token = if success { context.next_token(arena) } else { context.peek(arena) };
268            return ValidationMatch::new(success, true, token, Some(context.clone()), Some(property.clone()), Vec::new());
269        }
270        "number" => success = t == EnumToken::NumberTokenType,
271        "zero" => success = t == EnumToken::NumberTokenType && arena.numeric_value.get(token.unwrap()) == 0.0,
272        "integer" => success = t == EnumToken::NumberTokenType && is_integer(arena.numeric_value.get(token.unwrap())),
273        "dimension" => {
274            success = matches!(
275                t,
276                EnumToken::DimensionTokenType
277                    | EnumToken::AngleTokenType
278                    | EnumToken::LengthTokenType
279                    | EnumToken::PercentageTokenType
280                    | EnumToken::ResolutionTokenType
281                    | EnumToken::TimeTokenType
282                    | EnumToken::FrequencyTokenType
283                    | EnumToken::UserDefinedDimensionTokenType
284                    | EnumToken::FlexTokenType
285            )
286        }
287        "angle" => success = t == EnumToken::AngleTokenType || t == EnumToken::UserDefinedDimensionTokenType,
288        "angle-percentage" => {
289            success = matches!(t, EnumToken::AngleTokenType | EnumToken::UserDefinedDimensionTokenType | EnumToken::PercentageTokenType)
290        }
291        "percentage" => success = token.is_some() && t == EnumToken::PercentageTokenType,
292        "length-percentage" => {
293            success = matches!(t, EnumToken::PercentageTokenType | EnumToken::LengthTokenType | EnumToken::UserDefinedDimensionTokenType)
294                || (t == EnumToken::NumberTokenType && arena.numeric_value.get(token.unwrap()) == 0.0)
295        }
296        "flex" => success = t == EnumToken::FlexTokenType || t == EnumToken::UserDefinedDimensionTokenType,
297        "length" => {
298            success = matches!(t, EnumToken::LengthTokenType | EnumToken::UserDefinedDimensionTokenType)
299                || (t == EnumToken::NumberTokenType && arena.numeric_value.get(token.unwrap()) == 0.0)
300        }
301        "resolution" => success = t == EnumToken::ResolutionTokenType,
302        "frequency" => success = t == EnumToken::FrequencyTokenType,
303        "decibel" | "semitones" => {
304            success = t == EnumToken::DimensionTokenType
305                && arena.with_string(arena.unit.get(token.unwrap()), |u| equals_ignore_case(u, if val == "decibel" { "dB" } else { "st" }));
306        }
307        "time" => success = token.is_some() && (t == EnumToken::TimeTokenType || t == EnumToken::UserDefinedDimensionTokenType),
308        "color" | "color-function" => {
309            let mut errors: Vec<ErrorDescription> = Vec::new();
310            if token.is_some() && is_function_def_type(t) {
311                let range = context.borrow().peek_range(arena, EnumToken::EndParensTokenType, 0);
312                let mut new_range: Vec<u32> = range.iter().map(|&r| arena.clone_node_deep(r, true, None)).collect();
313                let parse_options = ParserOptions { parse_color: Some(true), ..Default::default() };
314                crate::parser::parse::parse_tokens(arena, &mut new_range, Some(&parse_options), Some(&mut errors));
315                let success = new_range.len() == 1 && is_color(arena, new_range[0], Some(&mut errors));
316                if success {
317                    context.update(range.last().copied());
318                }
319                return ValidationMatch::new(success, true, context.peek(arena), Some(context.clone()), None, errors);
320            }
321            success = token.is_some_and(|tk| is_color(arena, tk, Some(&mut errors)));
322            if !success {
323                return ValidationMatch::new(false, false, token, Some(context.clone()), Some(property.clone()), errors);
324            }
325        }
326        "type-selector" | "compound-selector" | "complex-selector" | "subclass-selector" | "attribute-selector"
327        | "complex-selector-unit" | "pseudo-compound-selector" | "forgiving-relative-selector-list" | "complex-selector-list" => {
328            let mut tokens = context.borrow().get_remaining_tokens();
329            let forgiving = val == "forgiving-relative-selector-list";
330            let (result_success, errors) = match_selector_syntax(arena, &mut tokens, &mut Vec::new(), options, val.starts_with("forgiving-relative-selector-list"));
331            if result_success || forgiving {
332                context.update(tokens.last().copied());
333            }
334            return ValidationMatch::new(result_success || forgiving, true, context.peek(arena), Some(context.clone()), Some(property.clone()), errors);
335        }
336        "function-token" => {
337            if is_function_def_type(t) && token.is_some() {
338                success = true;
339            } else {
340                return ko(context, context.peek(arena), property);
341            }
342        }
343        "language-code" => {
344            success = t == EnumToken::IdenTokenType && {
345                let v = str_of(token.unwrap());
346                get_syntax_config()["languages"]
347                    .as_array()
348                    .is_some_and(|a| a.iter().filter_map(|l| l.as_str()).any(|l| *v == *l || v.starts_with(&format!("{}-", l))))
349            };
350        }
351        "size-feature" | "style-feature" => {
352            let filtered = peek_feature_tokens(arena, context);
353            let ft = |i: usize| arena.data_types.get(filtered[i]);
354            let size = val == "size-feature";
355            success = if filtered.len() == 1 {
356                ft(0) == EnumToken::IdenTokenType || ft(0) == EnumToken::DashedIdenTokenType
357            } else {
358                filtered.len() > 2
359                    && (mFLT.contains(&ft(1))
360                        || mFGT.contains(&ft(1))
361                        || ft(1) == EnumToken::ColonTokenType
362                        || (size && ft(1) == EnumToken::DelimTokenType))
363            };
364            if success {
365                context.update(filtered.last().copied());
366            }
367            let token = if success { None } else if size { filtered.get(1).copied().or_else(|| context.peek(arena)) } else { context.peek(arena) };
368            return ValidationMatch::new(success, if size { true } else { success }, token, Some(context.clone()), Some(property.clone()), Vec::new());
369        }
370        "url" => 'url: {
371            if t == EnumToken::UrlFunctionTokenDefType {
372                let mut l = 0isize;
373                let peek = |l: isize| context.borrow().peek(arena, l);
374                let mut tk;
375                loop {
376                    l += 1;
377                    tk = peek(l);
378                    match tk {
379                        Some(x) if matches!(arena.data_types.get(x), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType) => continue,
380                        _ => break,
381                    }
382                }
383                if tk.is_some_and(|x| matches!(arena.data_types.get(x), EnumToken::StringTokenType | EnumToken::IdenTokenType | EnumToken::UrlTokenTokenType)) {
384                    loop {
385                        l += 1;
386                        tk = peek(l);
387                        match tk {
388                            Some(x) if matches!(arena.data_types.get(x), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType) => continue,
389                            _ => break,
390                        }
391                    }
392                    if typ(tk) == EnumToken::EndParensTokenType {
393                        context.update(tk);
394                        return ok(context, None);
395                    }
396                }
397                break 'url;
398            }
399            if t != EnumToken::UrlFunctionTokenType {
400                success = false;
401                break 'url;
402            }
403            let url_tokens = arena.tokens(token.unwrap());
404            if url_tokens.iter().any(|&u| !matches!(arena.data_types.get(u), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType)) {
405                context.next_token(arena);
406                return ok(context, None);
407            }
408        }
409        "css-type" => {
410            if (t == EnumToken::FunctionTokenDefType || t == EnumToken::FunctionTokenType)
411                && arena.with_string(arena.string_value.get(token.unwrap()), |v| equals_ignore_case(v, "type"))
412            {
413                if t == EnumToken::FunctionTokenDefType {
414                    let last = context.borrow().peek_range(arena, EnumToken::EndParensTokenType, 0).last().copied();
415                    context.update(last);
416                } else {
417                    context.next_token(arena);
418                }
419                return ok(context, None);
420            }
421            success = t == EnumToken::CssTypeTokenType;
422            if success {
423                context.next_token(arena);
424                let multiplier = {
425                    let c = context.borrow();
426                    let i = c.index + 1;
427                    if i >= 0 { c.tokens().get(i as usize).copied() } else { None }
428                };
429                if let Some(m) = multiplier {
430                    if arena.data_types.get(m) == EnumToken::Plus
431                        || (arena.data_types.get(m) == EnumToken::LiteralTokenType && arena.string_equals(arena.string_value.get(m), "#"))
432                    {
433                        context.next_token(arena);
434                    }
435                }
436                return ok(context, None);
437            }
438        }
439        "dashed-function" => {
440            success = t == EnumToken::CustomFunctionTokenDefType || t == EnumToken::CustomFunctionTokenType;
441            if success {
442                if t == EnumToken::CustomFunctionTokenDefType {
443                    let last = context.borrow().peek_range(arena, EnumToken::EndParensTokenType, 0).last().copied();
444                    context.update(last);
445                } else {
446                    context.next_token(arena);
447                }
448                return ok(context, token);
449            }
450        }
451        "block-contents" => {
452            if t == EnumToken::StartParensTokenType && token.is_some() {
453                context.next_token(arena);
454                return ok(context, None);
455            }
456            return ko(context, token, property);
457        }
458        _ => {
459            if !has_syntax(val) {
460                // typescript throws `Unexpected validation property`
461                return ko(context, context.peek(arena), property);
462            }
463            let parsed = get_parsed_syntax(ValidationSyntaxGroupEnum::Syntaxes, val);
464            return match_syntax(arena, parsed.as_deref().map(|v| v.as_slice()), context, options);
465        }
466    }
467    let peeked = context.peek(arena);
468    if !success && typ(peeked) == EnumToken::IdenTokenType && is_css_wide_keyword_exact(&str_of(peeked.unwrap())) {
469        success = true;
470    }
471    if success {
472        context.next_token(arena);
473        return ok(context, None);
474    }
475    ko(context, context.peek(arena), property)
476}
477
478/// `allValues.includes(value)`: case sensitive
479fn is_css_wide_keyword_exact(value: &str) -> bool {
480    let _ = is_css_wide_keyword;
481    get_syntax_config()["declarations"]["all"]["syntax"]
482        .as_str()
483        .unwrap_or("")
484        .split(|c: char| c.is_whitespace() || c == '|')
485        .any(|v| v == value)
486}
487
488/// matches a repeatable syntax (`*`, `+`)
489pub fn match_repeatable_syntax(arena: &AstArena, syntax: &Syntax, context: &Context, options: &ParserOptions) -> ValidationMatch {
490    let mut rest = (**syntax).clone();
491    let is_repeatable = rest.is_repeatable();
492    rest.is_repeatable = None;
493    rest.is_optional = None;
494    rest.is_mandatatory_group = None;
495    rest.is_repeatable_at_least_once = None;
496    let rest = [Rc::new(rest)];
497    let mut result: Option<ValidationMatch> = None;
498    let mut success = is_repeatable;
499    loop {
500        let tmp = match_syntax(arena, Some(&rest), &context.slice(), options);
501        if tmp.success {
502            result = Some(tmp.clone());
503            success = true;
504            if tmp.ctx().done(arena) {
505                context.end();
506                break;
507            }
508            if tmp.ctx().current() == context.current() {
509                break;
510            }
511            context.update(tmp.ctx().current());
512        }
513        if !(tmp.success && !context.done(arena)) {
514            break;
515        }
516    }
517    ValidationMatch::new(
518        success,
519        true,
520        context.peek(arena),
521        Some(context.clone()),
522        Some(syntax.clone()),
523        result.map(|r| r.errors).unwrap_or_default(),
524    )
525}