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