Skip to main content

rust_css_parser/validation/
match_syntax.rs

1//! Port of the second half of `src/validation/match.ts`: `matchSyntax()`, the unordered syntaxes (`||`, `&&`)
2//! and `matchProperty()` (the built-in types, see `match_property.rs`).
3
4use super::config::get_parsed_syntax;
5use super::first::{is_nullable, matching_alternatives, may_start_with};
6use super::match_::{
7    create_validation_context, find_mandatory_syntax, function_syntax, is_css_wide_keyword, is_func_type, is_in_range,
8    is_literal_number, match_list_syntax, match_occurence_syntax, match_wild_card_function, set_done_match, trim_array,
9    wild_card_probe, Context, ContextExt, Syntax, ValidationMatch,
10};
11use super::parser::typedef::{ValidationSyntaxGroupEnum, ValidationTokenEnum as V};
12use super::parser::types::ValidationToken;
13use crate::ast::arena::AstArena;
14use crate::ast::types::EnumToken;
15use crate::options::ParserOptions;
16use crate::parser::utils::text::{equals_ignore_case, lowercase};
17use crate::syntax::constants::{is_function_def_type, is_function_type, FUNC_LIKE};
18use crate::types::{ErrorDescription, ErrorSyntax};
19use crate::utils::fx::HashMap;
20use std::rc::Rc;
21
22pub use super::match_property::match_property;
23
24fn fail(token: Option<u32>, context: &Context, syntax: Option<Syntax>, errors: Vec<ErrorDescription>) -> ValidationMatch {
25    ValidationMatch::new(false, true, token, Some(context.clone()), syntax, errors)
26}
27
28fn syntax_error(message: &str, token: Option<u32>, syntax: &Syntax) -> ErrorDescription {
29    let mut error = ErrorDescription::drop(message);
30    error.node = token;
31    error.syntax = Some(ErrorSyntax::Token(syntax.clone()));
32    error
33}
34
35/// first item of a function syntax (`name()`): the arguments are its children, borrowed by the callers
36fn function_head(syntax: Option<Rc<Vec<Syntax>>>) -> Option<Syntax> {
37    syntax.and_then(|s| s.first().cloned())
38}
39
40/// outcome of a syntax of the sequence
41enum Step {
42    /// continue with the next syntax. `success`: the syntax matched
43    Next(bool),
44    /// return this result
45    Return(ValidationMatch),
46}
47
48/// match a sequence of syntaxes
49pub fn match_syntax(arena: &AstArena, syntaxes: Option<&[Syntax]>, context: &Context, options: &ParserOptions) -> ValidationMatch {
50    let Some(syntaxes) = syntaxes else {
51        return ValidationMatch::new(true, false, context.peek(arena), Some(context.clone()), None, Vec::new());
52    };
53    let mut i: isize = -1;
54    let mut token: Option<u32> = None;
55    let mut result: Option<ValidationMatch> = None;
56    {
57        let ctx = context.borrow();
58        let tokens = ctx.tokens();
59        if tokens.len() == 1
60            && arena.data_types.get(tokens[0]) == EnumToken::IdenTokenType
61            && arena.with_string(arena.string_value.get(tokens[0]), is_css_wide_keyword)
62        {
63            drop(ctx);
64            context.end();
65            return ValidationMatch::new(true, true, context.peek(arena), Some(context.clone()), None, Vec::new());
66        }
67    }
68    loop {
69        i += 1;
70        if i as usize >= syntaxes.len() {
71            break;
72        }
73        let iu = i as usize;
74        let syntax = &syntaxes[iu];
75        if syntax.typ == V::Whitespace {
76            continue;
77        }
78        let is_optional = (syntax.is_optional() || syntax.is_repeatable()) && !syntax.is_mandatatory_group();
79        token = context.peek(arena);
80        let Some(tk) = token else {
81            let mandatory = find_mandatory_syntax(syntaxes, if is_optional { iu + 1 } else { iu });
82            if mandatory != -1 {
83                let m = syntaxes[mandatory as usize].clone();
84                return ValidationMatch::new(false, true, None, Some(context.clone()), Some(m.clone()), vec![syntax_error("could not match syntax", None, &m)]);
85            }
86            break;
87        };
88        let probe = wild_card_probe(tk);
89        let probed = probe.as_ref().is_some_and(|p| Rc::ptr_eq(p, syntax));
90        if arena.data_types.get(tk) == EnumToken::WildCardFunctionTokenType && arena.string_equals(arena.string_value.get(tk), "var") && !probed {
91            let r = match_syntax(
92                arena,
93                function_head(function_syntax(arena, tk)).as_ref().map(|f| f.children()),
94                &create_validation_context(arena, &arena.tokens(tk)),
95                options,
96            );
97            let ok = r.success && r.ctx().done(arena);
98            result = Some(r);
99            if ok {
100                match match_wild_card_function(arena, syntaxes, iu, context, tk, Some(tk), options) {
101                    None => continue,
102                    Some(w) => return w,
103                }
104            }
105        }
106        // a custom function call (`--fn()`) is substituted by the result of the function: like var(), it may be
107        // substituted by any number of values
108        let custom = arena.data_types.get(tk);
109        if (custom == EnumToken::CustomFunctionTokenType || custom == EnumToken::CustomFunctionTokenDefType) && !probed {
110            // the arguments of the call are not validated: they are the arguments of the custom function
111            let end = if custom == EnumToken::CustomFunctionTokenDefType {
112                let mut range = context.borrow().peek_range(arena, EnumToken::EndParensTokenType, 0);
113                trim_array(arena, &mut range);
114                range.last().copied()
115            } else {
116                Some(tk)
117            };
118            match match_wild_card_function(arena, syntaxes, iu, context, tk, end, options) {
119                None => continue,
120                Some(w) => return w,
121            }
122        }
123        if arena.data_types.get(tk) == EnumToken::WildCardFunctionTokenDefType && !probed {
124            let mut range = context.borrow().peek_range(arena, EnumToken::EndParensTokenType, 0);
125            trim_array(arena, &mut range);
126            let inner: &[u32] = if range.len() >= 2 { &range[1..range.len() - 1] } else { &[] };
127            let r = match_syntax(arena, function_head(function_syntax(arena, tk)).as_ref().map(|f| f.children()), &create_validation_context(arena, inner), options);
128            let ok = r.success;
129            result = Some(r);
130            if ok {
131                match match_wild_card_function(arena, syntaxes, iu, context, tk, range.last().copied(), options) {
132                    None => continue,
133                    Some(w) => return w,
134                }
135            }
136        }
137        if syntax.is_repeatable_at_least_once() || syntax.is_repeatable() {
138            let r = match_repeatable_syntax(arena, syntax, &context.slice(), options);
139            if r.success {
140                if r.ctx().done(arena) {
141                    context.end();
142                    let ctx = r.ctx().clone();
143                    return set_done_match(syntaxes, iu + 1, r.valid, r.token, &ctx, r.errors);
144                }
145                context.update(r.ctx().current());
146                result = Some(r);
147                continue;
148            }
149            if is_optional {
150                result = Some(r);
151                continue;
152            }
153            return r;
154        }
155        if syntax.is_list() {
156            let r = match_list_syntax(arena, syntax, &context.slice(), options);
157            if r.success {
158                if r.ctx().done(arena) {
159                    context.end();
160                    return set_done_match(syntaxes, iu + 1, true, None, context, r.errors);
161                }
162                context.update(r.ctx().current());
163                result = Some(r);
164                continue;
165            }
166            if is_optional {
167                result = Some(r);
168                continue;
169            }
170            return fail(Some(tk), context, Some(syntax.clone()), r.errors);
171        }
172        if syntax.match_.is_some() {
173            let r = match_occurence_syntax(arena, syntax, &context.slice(), options);
174            if r.success {
175                if r.ctx().done(arena) {
176                    context.end();
177                    return set_done_match(syntaxes, iu + 1, r.valid, r.token, context, r.errors);
178                }
179                context.update(r.ctx().current());
180                result = Some(r);
181                continue;
182            }
183            if is_optional {
184                result = Some(r);
185                continue;
186            }
187            return fail(Some(tk), context, Some(syntax.clone()), r.errors);
188        }
189        if super::match_::is_visited(tk, syntax) {
190            return fail(Some(tk), context, Some(syntax.clone()), Vec::new());
191        }
192        let visit = super::match_::enter_syntax(tk, syntax);
193        let step = match_one(arena, syntaxes, iu, syntax, tk, is_optional, context, options, visit, &mut result);
194        // finally: the syntax is no longer being matched
195        super::match_::leave_syntax(visit);
196        match step {
197            Step::Return(r) => return r,
198            Step::Next(success) => {
199                if success && !is_in_range(arena, tk, syntax) {
200                    return fail(Some(tk), context, Some(syntax.clone()), Vec::new());
201                }
202            }
203        }
204    }
205    let (valid, errors) = match &result {
206        Some(r) if r.success => (r.valid, r.errors.clone()),
207        _ => (true, Vec::new()),
208    };
209    ValidationMatch::new(true, valid, token, Some(context.clone()), syntaxes.get(i.max(0) as usize).cloned(), errors)
210}
211
212/// match the syntax at index (the body of the `switch` of `matchSyntax()`)
213#[allow(clippy::too_many_arguments)]
214fn match_one(
215    arena: &AstArena,
216    syntaxes: &[Syntax],
217    i: usize,
218    syntax: &Syntax,
219    token: u32,
220    is_optional: bool,
221    context: &Context,
222    options: &ParserOptions,
223    visit: usize,
224    result: &mut Option<ValidationMatch>,
225) -> Step {
226    let t = arena.data_types.get(token);
227    let matched = |visit: usize| super::match_::clear_visited(visit);
228    let no = || Step::Return(fail(Some(token), context, Some(syntax.clone()), Vec::new()));
229    match syntax.typ {
230        V::Colon => {
231            if t == EnumToken::ColonTokenType {
232                context.next_token(arena);
233                return Step::Next(true);
234            }
235            if is_optional {
236                return Step::Next(false);
237            }
238            no()
239        }
240        V::Comma => {
241            if t == EnumToken::CommaTokenType {
242                matched(visit);
243                context.next_token(arena);
244                return Step::Next(true);
245            }
246            no()
247        }
248        V::Keyword => {
249            if t == EnumToken::IdenTokenType && arena.with_string(arena.string_value.get(token), |v| lowercase(v) == lowercase(syntax.val_str())) {
250                matched(visit);
251                context.next_token(arena);
252                return Step::Next(true);
253            }
254            if is_optional {
255                return Step::Next(false);
256            }
257            no()
258        }
259        V::DeclarationType => {
260            let r = match_syntax(
261                arena,
262                get_parsed_syntax(ValidationSyntaxGroupEnum::Declarations, syntax.val_str()).as_deref().map(|v| v.as_slice()),
263                context,
264                options,
265            );
266            let mut success = false;
267            if r.success {
268                success = true;
269                matched(visit);
270                if r.ctx().done(arena) {
271                    context.end();
272                    return Step::Return(set_done_match(syntaxes, i + 1, r.valid, Some(token), context, r.errors));
273                } else if r.ctx().current().is_some() {
274                    context.update(r.ctx().current());
275                }
276            }
277            let errors = r.errors.clone();
278            *result = Some(r);
279            if success || is_optional {
280                return Step::Next(success);
281            }
282            Step::Return(fail(Some(token), context, Some(syntax.clone()), errors))
283        }
284        V::OptionalGroupToken => {
285            let chi = syntax.children();
286            if chi.len() == 1 && chi[0].is_list() {
287                let mut item = (*chi[0]).clone();
288                item.is_list = None;
289                item.is_optional = None;
290                item.match_ = None;
291                let group = [Rc::new(item), Rc::new(ValidationToken::new(V::Comma))];
292                while context.peek(arena).is_some() {
293                    let tmp = match_syntax(arena, Some(&group), &context.slice(), options);
294                    if !tmp.success || tmp.ctx().current().is_none() {
295                        break;
296                    }
297                    context.update(tmp.ctx().current());
298                    if tmp.ctx().done(arena) {
299                        break;
300                    }
301                }
302                return Step::Next(true);
303            }
304            let r = match_syntax(arena, Some(chi), &context.slice(), options);
305            let mut success = false;
306            if r.success {
307                success = true;
308                if r.ctx().done(arena) {
309                    context.end();
310                    return Step::Return(set_done_match(syntaxes, i + 1, true, None, context, r.errors));
311                }
312                context.update(r.ctx().current());
313            }
314            *result = Some(r);
315            Step::Next(success)
316        }
317        V::StringToken => {
318            let val = syntax.val_str();
319            let inner: String = {
320                let chars: Vec<char> = val.chars().collect();
321                if chars.len() >= 2 { chars[1..chars.len() - 1].iter().collect() } else { String::new() }
322            };
323            let success = match t {
324                EnumToken::Add => inner == "+",
325                EnumToken::Sub => inner == "-",
326                EnumToken::LiteralTokenType => arena.string_equals(arena.string_value.get(token), &inner),
327                EnumToken::Plus => true,
328                _ => false,
329            };
330            if success {
331                context.next_token(arena);
332                return Step::Next(true);
333            }
334            if is_optional {
335                return Step::Next(false);
336            }
337            no()
338        }
339        V::PropertyType => {
340            let r = match_property(arena, syntax, context, options);
341            if !r.success {
342                *result = Some(r);
343                if is_optional {
344                    return Step::Next(false);
345                }
346                return Step::Return(fail(context.current().or(Some(token)), context, Some(syntax.clone()), Vec::new()));
347            }
348            matched(visit);
349            if r.ctx().done(arena) {
350                if !is_in_range(arena, token, syntax) {
351                    return no();
352                }
353                context.end();
354                return Step::Return(set_done_match(syntaxes, i + 1, true, None, context, Vec::new()));
355            }
356            context.update(r.ctx().current());
357            *result = Some(r);
358            Step::Next(true)
359        }
360        V::PipeToken => {
361            let alternatives = syntax.alternatives();
362            let candidates = matching_alternatives(arena, alternatives, Some(token));
363            let count = candidates.as_ref().map_or(alternatives.len(), |c| c.len());
364            let mut best: Option<ValidationMatch> = None;
365            for k in 0..count {
366                let alternative = &alternatives[candidates.as_ref().map_or(k, |c| c[k])];
367                let tmp = match_syntax(arena, Some(alternative), &context.slice(), options);
368                if tmp.success {
369                    if tmp.ctx().done(arena) && find_mandatory_syntax(syntaxes, i + 1) != -1 {
370                        continue;
371                    }
372                    if best.as_ref().is_none_or(|b| tmp.ctx().index() >= b.ctx().index()) {
373                        best = Some(tmp.clone());
374                    }
375                    if tmp.ctx().done(arena) {
376                        context.end();
377                        return Step::Return(ValidationMatch::new(
378                            tmp.success,
379                            tmp.valid,
380                            tmp.token,
381                            Some(context.clone()),
382                            syntaxes.get(i + 1).cloned(),
383                            tmp.errors,
384                        ));
385                    }
386                }
387            }
388            *result = best.clone();
389            if let Some(b) = best.filter(|b| b.success) {
390                matched(visit);
391                context.update(b.ctx().current());
392                return Step::Next(true);
393            }
394            Step::Return(fail(Some(token), context, Some(syntax.clone()), vec![syntax_error("could not match syntax", Some(token), syntax)]))
395        }
396        V::Bracket => {
397            let r = match_syntax(arena, Some(syntax.children()), &context.slice(), options);
398            if r.success {
399                matched(visit);
400                if r.ctx().done(arena) {
401                    context.end();
402                    return Step::Return(set_done_match(syntaxes, i + 1, true, None, context, Vec::new()));
403                }
404                context.update(r.ctx().current());
405                *result = Some(r);
406                return Step::Next(true);
407            }
408            *result = Some(r);
409            if is_optional {
410                return Step::Next(false);
411            }
412            no()
413        }
414        V::ColumnToken | V::AmpersandToken => {
415            let r = if syntax.typ == V::ColumnToken {
416                match_column_syntax(arena, syntax, &context.slice(), options)
417            } else {
418                match_ampersand_syntax(arena, syntax, &context.slice(), options)
419            };
420            if r.success {
421                matched(visit);
422                if r.ctx().done(arena) {
423                    context.end();
424                    return Step::Return(set_done_match(syntaxes, i + 1, true, None, context, Vec::new()));
425                }
426                context.update(r.ctx().current());
427                *result = Some(r);
428                return Step::Next(true);
429            }
430            *result = Some(r);
431            no()
432        }
433        V::Function => {
434            let is_func = is_function_def_type(t) || FUNC_LIKE.contains(&t) || is_func_type(t);
435            let name_ok = arena.with_string(arena.string_value.get(token), |v| equals_ignore_case(syntax.val_str(), &v.to_lowercase()));
436            if !is_func || !name_ok {
437                let mut error = ErrorDescription::drop(format!("Expecting a function {}", EnumToken::name(t).unwrap_or("undefined")));
438                error.node = Some(token);
439                return Step::Return(fail(Some(token), context, Some(syntax.clone()), vec![error]));
440            }
441            let r = if is_function_def_type(t) {
442                let range = context.borrow().peek_range(arena, EnumToken::EndParensTokenType, 0);
443                let inner: &[u32] = if range.len() >= 2 { &range[1..range.len() - 1] } else { &[] };
444                let r = match_syntax(arena, Some(syntax.children()), &create_validation_context(arena, inner), options);
445                if r.success && r.ctx().done(arena) {
446                    context.update(range.last().copied());
447                    matched(visit);
448                    *result = Some(r);
449                    // typescript: `success` is not set for a function definition token
450                    return Step::Next(false);
451                }
452                r
453            } else {
454                let r = match_syntax(arena, Some(syntax.children()), &create_validation_context(arena, &arena.tokens(token)), options);
455                if r.success && r.ctx().done(arena) {
456                    matched(visit);
457                    context.next_token(arena);
458                    *result = Some(r);
459                    return Step::Next(true);
460                }
461                r
462            };
463            let errors = r.errors.clone();
464            *result = Some(r);
465            Step::Return(fail(Some(token), context, Some(syntax.clone()), errors))
466        }
467        V::Number | V::Dimension => {
468            if is_literal_number(arena, token, syntax) {
469                matched(visit);
470                context.next_token(arena);
471                return Step::Next(true);
472            }
473            if is_optional {
474                return Step::Next(false);
475            }
476            no()
477        }
478        V::Separator => {
479            if t == EnumToken::LiteralTokenType && arena.string_equals(arena.string_value.get(token), "/") {
480                matched(visit);
481                context.next_token(arena);
482                return Step::Next(false);
483            }
484            no()
485        }
486        V::FunctionDefinition => {
487            let name = arena.resolve_string(arena.string_value.get(token));
488            if !name.is_empty() && equals_ignore_case(&name, syntax.val_str()) {
489                let parsed = get_parsed_syntax(ValidationSyntaxGroupEnum::Syntaxes, &format!("{}()", syntax.val_str()));
490                if is_function_def_type(t) {
491                    let mut children = context.borrow().peek_range(arena, EnumToken::EndParensTokenType, 0);
492                    trim_array(arena, &mut children);
493                    let chi: &[Syntax] = parsed.as_ref().and_then(|p| p.first()).map_or(&[], |f| f.children());
494                    let inner: &[u32] = if children.len() >= 2 { &children[1..children.len() - 1] } else { &[] };
495                    let r = match_syntax(arena, Some(chi), &create_validation_context(arena, inner), options);
496                    let ok = r.success && r.ctx().done(arena);
497                    *result = Some(r);
498                    if ok {
499                        matched(visit);
500                        context.update(children.last().copied());
501                        return Step::Next(true);
502                    }
503                } else if is_function_type(t) {
504                    let all: Vec<Syntax> = parsed.as_deref().cloned().unwrap_or_default();
505                    let r = match_syntax(arena, Some(&all), &create_validation_context(arena, &[token]), options);
506                    let ok = r.success && r.ctx().done(arena);
507                    *result = Some(r);
508                    if ok {
509                        matched(visit);
510                        context.next_token(arena);
511                        return Step::Next(true);
512                    }
513                }
514            }
515            no()
516        }
517        V::OpenParenthesis | V::OpenCurlyBrace | V::CloseParenthesis => {
518            let expected = match syntax.typ {
519                V::OpenParenthesis => EnumToken::StartParensTokenType,
520                V::OpenCurlyBrace => EnumToken::BlockStartTokenType,
521                _ => EnumToken::EndParensTokenType,
522            };
523            if t == expected {
524                matched(visit);
525                context.next_token(arena);
526                return Step::Next(false);
527            }
528            no()
529        }
530        // typescript throws `Unexpected syntax`
531        _ => no(),
532    }
533}
534
535/// matches a column of syntaxes: `<a> || <b> || <c>`, one or more syntaxes in any order
536fn match_column_syntax(arena: &AstArena, syntax: &Syntax, context: &Context, options: &ParserOptions) -> ValidationMatch {
537    match_unordered_syntaxes(arena, syntax, syntax.alternatives(), false, context, options)
538}
539
540/// matches syntaxes in any order: all the syntaxes (`&&`) or one or more syntaxes (`||`)
541fn match_unordered_syntaxes(
542    arena: &AstArena,
543    syntax: &Syntax,
544    syntaxes: &[Vec<Syntax>],
545    all: bool,
546    context: &Context,
547    options: &ParserOptions,
548) -> ValidationMatch {
549    let remaining: Vec<usize> = (0..syntaxes.len()).collect();
550    let mut cache: HashMap<(usize, i64), Option<Context>> = HashMap::default();
551    let best = search_unordered_syntaxes(arena, syntaxes, &remaining, all, context, context, options, &mut cache);
552    if let Some(best) = &best {
553        if best.done(arena) {
554            context.end();
555        } else {
556            context.update(best.current());
557        }
558    }
559    let success = best.is_some() || (all && syntaxes.iter().all(|s| find_mandatory_syntax(s, 0) == -1));
560    ValidationMatch::new(success, true, context.current(), Some(context.clone()), Some(syntax.clone()), Vec::new())
561}
562
563/// position of a context in the tokens of the unordered syntaxes
564fn unordered_position(arena: &AstArena, base: &Context, context: &Context) -> i64 {
565    if context.done(arena) {
566        return i64::MAX;
567    }
568    let current = context.current();
569    base.borrow().tokens().iter().position(|&t| Some(t) == current).map_or(-1, |p| p as i64)
570}
571
572/// the context after the unordered syntaxes that match the most tokens. None if the syntaxes do not match
573#[allow(clippy::too_many_arguments)]
574fn search_unordered_syntaxes(
575    arena: &AstArena,
576    syntaxes: &[Vec<Syntax>],
577    remaining: &[usize],
578    all: bool,
579    base: &Context,
580    context: &Context,
581    options: &ParserOptions,
582    cache: &mut HashMap<(usize, i64), Option<Context>>,
583) -> Option<Context> {
584    let position = unordered_position(arena, base, context);
585    let mut best: Option<Context> = None;
586    for k in 0..remaining.len() {
587        let key = (remaining[k], position);
588        let next = match cache.get(&key) {
589            Some(n) => n.clone(),
590            None => {
591                let mut next = None;
592                let result = if may_start_with(arena, &syntaxes[remaining[k]], context.peek(arena)) {
593                    Some(match_syntax(arena, Some(&syntaxes[remaining[k]]), &context.slice(), options))
594                } else {
595                    None
596                };
597                if let Some(r) = result {
598                    if r.success && (r.ctx().done(arena) || r.ctx().current() != context.current()) {
599                        let n = context.slice();
600                        if r.ctx().done(arena) {
601                            n.end();
602                        } else {
603                            n.update(r.ctx().current());
604                        }
605                        next = Some(n);
606                    }
607                }
608                cache.insert(key, next.clone());
609                next
610            }
611        };
612        let Some(next) = next else {
613            continue;
614        };
615        let rest: Vec<usize> = remaining[..k].iter().chain(&remaining[k + 1..]).copied().collect();
616        let complete = !all || rest.iter().all(|&index| find_mandatory_syntax(&syntaxes[index], 0) == -1);
617        let mut candidates: Vec<Context> = Vec::new();
618        if !next.done(arena) && !rest.is_empty() {
619            if let Some(deeper) = search_unordered_syntaxes(arena, syntaxes, &rest, all, base, &next, options, cache) {
620                candidates.push(deeper);
621            }
622        }
623        if complete {
624            candidates.push(next);
625        }
626        for candidate in candidates {
627            if candidate.done(arena) {
628                return Some(candidate);
629            }
630            if best.as_ref().is_none_or(|b| unordered_position(arena, base, &candidate) > unordered_position(arena, base, b)) {
631                best = Some(candidate);
632            }
633        }
634    }
635    best
636}
637
638/// the operands of chained ampersands: `<a> && <b> && <c>` is parsed as `[ <a> && <b> ] && <c>`
639fn ampersand_operands(syntax: &ValidationToken, operands: &mut Vec<Vec<Syntax>>) {
640    for side in [syntax.l.as_deref().unwrap_or(&[]), syntax.r.as_deref().unwrap_or(&[])] {
641        let tokens: Vec<&Syntax> = side.iter().filter(|t| t.typ != V::Whitespace).collect();
642        if tokens.len() == 1
643            && tokens[0].typ == V::AmpersandToken
644            && !tokens[0].is_optional()
645            && !tokens[0].is_repeatable()
646            && !tokens[0].is_repeatable_at_least_once()
647            && !tokens[0].is_list()
648            && tokens[0].match_.is_none()
649        {
650            ampersand_operands(tokens[0], operands);
651        } else {
652            operands.push(side.to_vec());
653        }
654    }
655}
656
657/// matches an ampersand of syntaxes: `<a> && <b> && <c>`
658fn match_ampersand_syntax(arena: &AstArena, syntax: &Syntax, context: &Context, options: &ParserOptions) -> ValidationMatch {
659    thread_local! {
660        /// the operands are shared by the matches of the syntax (the unordered caches are keyed by their address)
661        static OPERANDS: std::cell::RefCell<HashMap<usize, (Syntax, Rc<Vec<Vec<Syntax>>>)>> = std::cell::RefCell::new(HashMap::default());
662    }
663    let key = Rc::as_ptr(syntax) as usize;
664    let operands = OPERANDS.with(|o| {
665        o.borrow_mut()
666            .entry(key)
667            .or_insert_with(|| {
668                let mut operands = Vec::new();
669                ampersand_operands(syntax, &mut operands);
670                (syntax.clone(), Rc::new(operands))
671            })
672            .1
673            .clone()
674    });
675    match_unordered_syntaxes(arena, syntax, &operands, true, context, options)
676}
677
678/// the tokens of a media / container feature: the tokens before the closing parenthesis
679pub fn peek_feature_tokens(arena: &AstArena, context: &Context) -> Vec<u32> {
680    let ctx = context.borrow();
681    let tokens = ctx.tokens();
682    let mut result = Vec::new();
683    let mut depth = 0i32;
684    let mut index = ctx.index + 1;
685    while (index as usize) < tokens.len() {
686        let token = tokens[index as usize];
687        let t = arena.data_types.get(token);
688        if t == EnumToken::StartParensTokenType || is_function_def_type(t) {
689            depth += 1;
690        } else if t == EnumToken::EndParensTokenType {
691            if depth == 0 {
692                break;
693            }
694            depth -= 1;
695        }
696        if t != EnumToken::WhitespaceTokenType && t != EnumToken::CommentTokenType {
697            result.push(token);
698        }
699        index += 1;
700    }
701    result
702}
703
704pub use super::match_property::match_repeatable_syntax;
705
706#[allow(dead_code)]
707fn _unused(s: &Syntax) -> bool {
708    is_nullable(s)
709}