1use super::typedef::ValidationTokenEnum as V;
8use super::types::{MatchMax, Position, VVal, ValidationMatch, ValidationRange, ValidationToken};
9use crate::ast::types::EnumToken;
10use crate::syntax::syntax::{is_ident, is_ident_start, is_pseudo, parse_dimension};
11use std::rc::Rc;
12
13fn symbol_type(code: u32) -> Option<u8> {
15 Some(match code {
16 0x7c => V::Pipe,
17 0x2a => V::Star,
18 0x2c => V::Comma,
19 0x2f => V::Separator,
20 0x2b => V::Plus,
21 0x3b => V::SemiColon,
22 0x28 => V::OpenParenthesis,
23 0x29 => V::CloseParenthesis,
24 0x5b => V::OpenBracket,
25 0x5d => V::CloseBracket,
26 0x7b => V::OpenCurlyBrace,
27 0x7d => V::CloseCurlyBrace,
28 0x3f => V::QuestionMark,
29 0x21 => V::Exclamation,
30 0x23 => V::HashMark,
31 0x3c => V::LessThan,
32 0x3e => V::GreaterThan,
33 0x20 | 0x09 | 0x0d | 0x0a | 0x0c => V::Whitespace,
34 0x221e => V::InfinityToken,
35 _ => return None,
36 })
37}
38
39fn pair_symbol_type(syntax: &[u16], index: usize) -> Option<u8> {
41 if index + 1 >= syntax.len() {
42 return symbol_type(syntax[index] as u32);
43 }
44 match (syntax[index], syntax[index + 1]) {
45 (0x26, 0x26) => Some(V::Ampersand),
46 (0x2020, 0x20) => Some(V::DisallowWhitespace),
47 (0x7c, 0x7c) => Some(V::Column),
48 _ => None,
49 }
50}
51
52fn is_digits(str: &str) -> bool {
53 !str.is_empty() && str.bytes().all(|b| b.is_ascii_digit())
54}
55
56#[derive(Clone, Debug, Default)]
58struct Node {
59 t: ValidationToken,
60 chi: Option<Vec<usize>>,
61 chi_list: Option<Vec<Vec<usize>>>,
62 l: Option<Vec<usize>>,
63 r: Option<Vec<usize>>,
64 match_: Option<(usize, NodeMax)>,
65 range: Option<(Option<usize>, Option<usize>)>,
66}
67
68#[derive(Clone, Copy, Debug)]
69enum NodeMax {
70 Token(usize),
71 Infinity,
72}
73
74struct Nodes(Vec<Node>);
76
77impl Nodes {
78 fn push(&mut self, t: ValidationToken) -> usize {
79 self.0.push(Node { t, ..Default::default() });
80 self.0.len() - 1
81 }
82
83 fn typ(&self, i: usize) -> u8 {
84 self.0[i].t.typ
85 }
86
87 fn freeze(&self, i: usize) -> Rc<ValidationToken> {
88 let node = &self.0[i];
89 let mut t = node.t.clone();
90 let list = |v: &Vec<usize>| v.iter().map(|&c| self.freeze(c)).collect::<Vec<_>>();
91 if let Some(chi) = &node.chi {
92 t.chi = Some(list(chi));
93 }
94 if let Some(chi) = &node.chi_list {
95 t.chi_list = Some(chi.iter().map(list).collect());
96 }
97 if let Some(l) = &node.l {
98 t.l = Some(list(l));
99 }
100 if let Some(r) = &node.r {
101 t.r = Some(list(r));
102 }
103 if let Some((min, max)) = node.match_ {
104 t.match_ = Some(ValidationMatch {
105 min: self.freeze(min),
106 max: match max {
107 NodeMax::Token(m) => MatchMax::Token(self.freeze(m)),
108 NodeMax::Infinity => MatchMax::Infinity,
109 },
110 });
111 }
112 if let Some((min, max)) = node.range {
113 t.range = Some(ValidationRange { min: min.map(|m| self.freeze(m)), max: max.map(|m| self.freeze(m)) });
114 }
115 Rc::new(t)
116 }
117}
118
119fn get_token_type(token: &str, loc: Position) -> ValidationToken {
121 let mut t = ValidationToken { loc, ..Default::default() };
122 if token == "<an+b>" {
123 t.typ = V::PropertyType;
124 t.val = VVal::Str(Rc::from("an+b"));
125 return t;
126 }
127 let first = token.chars().next().map_or(0, |c| c as u32);
128 if first == 34 || first == 39 {
129 t.typ = V::StringToken;
130 t.val = VVal::Str(Rc::from(token));
131 return t;
132 }
133 if is_digits(token) || (first == 45 && is_digits(&token[1..])) {
134 t.typ = V::Number;
135 t.val = VVal::Num(crate::utils::number::js_parse_number(token));
136 return t;
137 }
138 if let Some(dimension) = parse_dimension(token) {
139 t.typ = V::Dimension;
140 t.unit = EnumToken::name(dimension.typ).map(Rc::from);
141 t.val = VVal::Num(dimension.val);
142 t.unit_text = Some(Rc::from(dimension.unit.as_str()));
143 return t;
144 }
145 if is_pseudo(token) {
146 t.typ = V::PseudoClassToken;
147 t.val = VVal::Str(Rc::from(token));
148 return t;
149 }
150 if first == 64 && is_ident(&token[1..]) {
151 t.typ = V::AtRule;
152 t.val = VVal::Str(Rc::from(&token[1..]));
153 return t;
154 }
155 t.typ = V::Keyword;
156 t.val = VVal::Str(Rc::from(token));
157 t
158}
159
160pub fn trim_syntax_array(tokens: &mut Vec<Rc<ValidationToken>>) {
162 trim_by(tokens, |t| t.typ);
163}
164
165fn trim_by<T>(tokens: &mut Vec<T>, typ: impl Fn(&T) -> u8) {
166 while tokens.first().is_some_and(|t| typ(t) == V::Whitespace) {
167 tokens.remove(0);
168 }
169 while tokens.last().is_some_and(|t| typ(t) == V::Whitespace) {
170 tokens.pop();
171 }
172 let mut i: isize = 0;
173 while (i as usize) < tokens.len() {
174 let iu = i as usize;
175 if typ(&tokens[iu]) == V::Comma {
176 if iu + 1 < tokens.len() && typ(&tokens[iu + 1]) == V::Whitespace {
177 tokens.remove(iu + 1);
178 }
179 if iu > 0 && typ(&tokens[iu - 1]) == V::Whitespace {
180 i -= 1;
181 tokens.remove(i as usize);
182 }
183 }
184 i += 1;
185 }
186}
187
188fn trim(nodes: &Nodes, mut tokens: Vec<usize>) -> Vec<usize> {
189 trim_by(&mut tokens, |&t| nodes.typ(t));
190 tokens
191}
192
193fn splice(v: &mut Vec<usize>, start: isize, count: isize) -> Vec<usize> {
195 let len = v.len() as isize;
196 let start = if start < 0 { (len + start).max(0) } else { start.min(len) } as usize;
197 let count = count.clamp(0, len - start as isize) as usize;
198 v.drain(start..start + count).collect()
199}
200
201fn at(v: &[usize], i: isize) -> Option<usize> {
203 let len = v.len() as isize;
204 let i = if i < 0 { len + i } else { i };
205 if i < 0 || i >= len {
206 None
207 } else {
208 Some(v[i as usize])
209 }
210}
211
212fn last_index_of(v: &[usize], value: Option<usize>) -> isize {
214 value.and_then(|value| v.iter().rposition(|&x| x == value)).map_or(-1, |i| i as isize)
215}
216
217fn get(v: &[usize], i: isize) -> Option<usize> {
218 if i < 0 {
219 None
220 } else {
221 v.get(i as usize).copied()
222 }
223}
224
225pub fn tokenize_syntax(syntax: &str) -> Vec<ValidationToken> {
227 let units: Vec<u16> = syntax.encode_utf16().collect();
228 let length = units.len();
229 let mut tokens: Vec<ValidationToken> = Vec::new();
230 let (mut pos_ind, pos_lin, mut pos_col): (i64, i64, i64) = (0, 1, 0);
231 let (mut cur_ind, cur_lin, mut cur_col): (i64, i64, i64) = (-1, 1, 0);
232 let mut prefix = String::new();
233 let mut buffer_start = 0usize;
234 let mut buffer_end = 0usize;
235 let mut i: isize = -1;
236 let code_at = |k: usize| units.get(k).map_or(u32::MAX, |&c| c as u32);
237 let slice = |a: usize, b: usize| String::from_utf16_lossy(&units[a..b]);
238
239 macro_rules! buffer_length {
240 () => {
241 prefix.encode_utf16().count() + buffer_end - buffer_start
242 };
243 }
244 macro_rules! buffer {
245 () => {
246 if prefix.is_empty() {
247 slice(buffer_start, buffer_end)
248 } else {
249 format!("{}{}", prefix, slice(buffer_start, buffer_end))
250 }
251 };
252 }
253 macro_rules! append {
254 ($index:expr) => {{
255 let index = $index;
256 if buffer_end == buffer_start {
257 buffer_start = index;
258 }
259 buffer_end = index + 1;
260 }};
261 }
262 macro_rules! clear {
263 () => {{
264 prefix.clear();
265 buffer_start = 0;
266 buffer_end = 0;
267 }};
268 }
269 macro_rules! start_token {
270 () => {{
271 let loc = Position { ind: pos_ind, lin: pos_lin, col: pos_col };
272 pos_ind = cur_ind;
273 pos_col = cur_col;
274 loc
275 }};
276 }
277
278 loop {
279 i += 1;
280 if i as usize >= length {
281 break;
282 }
283 let iu = i as usize;
284 let code = units[iu] as u32;
285 cur_col += 1;
286 cur_ind += 1;
287 if code == 60 && units[iu + 1..].starts_with(&"an+b>".encode_utf16().collect::<Vec<_>>()) {
288 if buffer_length!() > 0 {
289 prefix = buffer!();
290 buffer_start = 0;
291 buffer_end = 0;
292 }
293 tokens.push(get_token_type("<an+b>", start_token!()));
294 cur_col += 5;
295 cur_ind += 5;
296 i += 5;
297 continue;
298 }
299 if let Some(typ) = pair_symbol_type(&units, iu) {
300 if iu + 1 < length {
301 i += 1;
302 cur_col += 1;
303 cur_ind += 1;
304 }
305 let loc = start_token!();
306 if buffer_length!() > 0 {
307 let b = buffer!();
308 tokens.push(get_token_type(&b, start_token!()));
309 clear!();
310 }
311 tokens.push(ValidationToken { typ, loc, ..Default::default() });
312 continue;
313 }
314 if code == 58 {
315 if code_at(iu + 1) == 58 && (is_ident_start(code_at(iu + 2)) || (code_at(iu + 2) == 45 && is_ident_start(code_at(iu + 3)))) {
316 append!(iu);
317 i += 1;
318 append!(i as usize);
319 continue;
320 }
321 if is_ident_start(code_at(iu + 1)) || (code_at(iu + 1) == 45 && is_ident_start(code_at(iu + 2))) {
322 append!(iu);
323 continue;
324 }
325 }
326 if let Some(typ) = symbol_type(code) {
327 if typ == V::Whitespace {
328 let mut k = iu;
329 while k + 1 < length && symbol_type(units[k + 1] as u32) == Some(V::Whitespace) {
330 k += 1;
331 }
332 if k != iu {
333 cur_col += (k - iu) as i64;
334 cur_ind += (k - iu) as i64;
335 i = k as isize;
336 }
337 }
338 let loc = start_token!();
339 if buffer_length!() > 0 {
340 let b = buffer!();
341 tokens.push(get_token_type(&b, start_token!()));
342 clear!();
343 }
344 tokens.push(ValidationToken { typ, loc, ..Default::default() });
345 continue;
346 }
347 match code {
348 58 => {
349 let loc = start_token!();
350 if buffer_length!() > 0 {
351 let b = buffer!();
352 tokens.push(get_token_type(&b, start_token!()));
353 clear!();
354 }
355 tokens.push(ValidationToken { typ: V::Colon, loc, ..Default::default() });
356 }
357 34 | 39 => {
358 let quote = if buffer_length!() > 0 { buffer!().encode_utf16().next().map_or(code, |c| c as u32) } else { code };
359 append!(i as usize);
360 while (i as usize) + 1 < length {
361 i += 1;
362 append!(i as usize);
363 if units[i as usize] as u32 == quote {
364 break;
365 }
366 }
367 let str = buffer!();
368 tokens.push(get_token_type(&str, start_token!()));
369 cur_col += str.chars().count() as i64;
370 cur_ind += str.encode_utf16().count() as i64;
371 clear!();
372 }
373 _ => append!(i as usize),
374 }
375 }
376 if buffer_length!() > 0 {
377 let b = buffer!();
378 tokens.push(get_token_type(&b, start_token!()));
379 }
380 tokens.push(ValidationToken { typ: V::EOF, loc: Position { ind: pos_ind, lin: pos_lin, col: pos_col }, ..Default::default() });
381 let _ = cur_lin;
382 tokens
383}
384
385pub fn parse_syntax(syntax: &str) -> Vec<Rc<ValidationToken>> {
387 let mut nodes = Nodes(Vec::new());
388 let mut stack: Vec<usize> = Vec::new();
389 let mut tokens: Vec<usize> = Vec::new();
390 let top = |stack: &Vec<usize>| stack.last().copied();
391
392 for token in tokenize_syntax(syntax) {
393 let token = nodes.push(token);
394 tokens.push(token);
395 let len = |tokens: &Vec<usize>| tokens.len() as isize;
396 match nodes.typ(token) {
397 V::EOF => {
398 if let Some(s) = top(&stack) {
399 let typ = nodes.typ(s);
400 if typ == V::PipeToken || typ == V::AmpersandToken || typ == V::ColumnToken {
401 let index = last_index_of(&tokens, Some(s));
402 let n = len(&tokens) - index - 2;
403 let part = splice(&mut tokens, index + 1, n);
404 let part = trim(&nodes, part);
405 if typ == V::AmpersandToken {
406 nodes.0[s].r = Some(part);
407 } else {
408 nodes.0[s].chi_list.get_or_insert_with(Vec::new).push(part);
409 }
410 stack.pop();
411 }
412 }
413 tokens.pop();
414 }
415 V::Pipe => {
416 while let Some(s) = top(&stack).filter(|&s| matches!(nodes.typ(s), V::AmpersandToken | V::ColumnToken)) {
417 let index = last_index_of(&tokens, Some(s));
418 let n = len(&tokens) - index - 2;
419 let part = trim(&nodes, splice(&mut tokens, index + 1, n));
420 if nodes.typ(s) == V::AmpersandToken {
421 nodes.0[s].r = Some(part);
422 } else {
423 nodes.0[s].chi_list.get_or_insert_with(Vec::new).push(part);
424 }
425 stack.pop();
426 }
427 let index = if stack.is_empty() { -1 } else { last_index_of(&tokens, top(&stack)) };
428 if top(&stack).map(|s| nodes.typ(s)) != Some(V::PipeToken) {
429 let n = len(&tokens) - index - 2;
430 let part = trim(&nodes, splice(&mut tokens, index + 1, n));
431 nodes.0[token].t.typ = V::PipeToken;
432 nodes.0[token].chi_list = Some(vec![part]);
433 stack.push(token);
434 continue;
435 }
436 tokens.pop();
437 let n = len(&tokens) - index - 1;
438 let part = trim(&nodes, splice(&mut tokens, index + 1, n));
439 let s = top(&stack).unwrap();
440 nodes.0[s].chi_list.get_or_insert_with(Vec::new).push(part);
441 }
442 V::Ampersand => {
443 let index = if stack.is_empty() { -1 } else { last_index_of(&tokens, top(&stack)) };
444 if top(&stack).map(|s| nodes.typ(s)) == Some(V::AmpersandToken) {
445 let s = top(&stack).unwrap();
446 let n = len(&tokens) - index - 2;
447 let part = trim(&nodes, splice(&mut tokens, index + 1, n));
448 nodes.0[s].r = Some(part);
449 stack.pop();
450 let l = splice(&mut tokens, index, 1);
451 nodes.0[token].t.typ = V::AmpersandToken;
452 nodes.0[token].l = Some(l);
453 nodes.0[token].r = Some(Vec::new());
454 stack.push(token);
455 } else {
456 let n = len(&tokens) - index - 2;
457 let part = trim(&nodes, splice(&mut tokens, index + 1, n));
458 nodes.0[token].t.typ = V::AmpersandToken;
459 nodes.0[token].l = Some(part);
460 nodes.0[token].r = Some(Vec::new());
461 stack.push(token);
462 }
463 }
464 V::Column => {
465 let index = if stack.is_empty() { -1 } else { last_index_of(&tokens, top(&stack)) };
466 if top(&stack).map(|s| nodes.typ(s)) == Some(V::ColumnToken) {
467 let s = top(&stack).unwrap();
468 let n = len(&tokens) - index - 2;
469 let part = trim(&nodes, splice(&mut tokens, index + 1, n));
470 nodes.0[s].chi_list.get_or_insert_with(Vec::new).push(part);
471 tokens.pop();
472 } else {
473 let part = if index != -1 {
474 let n = len(&tokens) - index - 2;
475 trim(&nodes, splice(&mut tokens, index + 1, n))
476 } else {
477 let n = len(&tokens) - 2;
478 trim(&nodes, splice(&mut tokens, 0, n))
479 };
480 nodes.0[token].t.typ = V::ColumnToken;
481 nodes.0[token].chi_list = Some(vec![part]);
482 stack.push(token);
483 }
484 }
485 V::OpenParenthesis => {
486 if let Some(prev) = at(&tokens, -2) {
487 let typ = nodes.typ(prev);
488 if typ == V::Keyword || typ == V::PseudoClassToken {
489 nodes.0[prev].t.typ = if typ == V::Keyword { V::Function } else { V::PseudoClassFunctionToken };
490 nodes.0[prev].chi = Some(Vec::new());
491 stack.push(prev);
492 tokens.pop();
493 continue;
494 }
495 }
496 stack.push(token);
497 }
498 V::CloseParenthesis => {
499 if let Some(s) = top(&stack).filter(|&s| nodes.typ(s) == V::PipeToken) {
500 let index = last_index_of(&tokens, Some(s));
501 let n = len(&tokens) - index - 2;
502 let part = trim(&nodes, splice(&mut tokens, index + 1, n));
503 nodes.0[s].chi_list.get_or_insert_with(Vec::new).push(part);
504 stack.pop();
505 }
506 let s = top(&stack);
507 if s.is_some_and(|s| {
508 nodes.typ(s) == V::OpenParenthesis || (nodes.typ(s) == V::PropertyType && nodes.0[s].t.val_str() == "function-token")
509 }) {
510 stack.pop();
511 } else if let Some(s) = s.filter(|&s| nodes.typ(s) == V::AmpersandToken) {
512 let index = last_index_of(&tokens, Some(s));
513 let n = len(&tokens) - index - 2;
514 let part = trim(&nodes, splice(&mut tokens, index + 1, n));
515 nodes.0[s].r = Some(part);
516 stack.pop();
517 }
518 if let Some(s) = top(&stack).filter(|&s| matches!(nodes.typ(s), V::Function | V::PseudoClassFunctionToken)) {
519 let index = last_index_of(&tokens, Some(s));
520 tokens.pop();
521 let n = len(&tokens);
522 let part = trim(&nodes, splice(&mut tokens, index + 1, n));
523 nodes.0[s].chi = Some(part);
524 stack.pop();
525 }
526 }
527 V::GreaterThan => {
528 let n = len(&tokens);
529 if let (Some(lt), Some(prev)) = (get(&tokens, n - 3), get(&tokens, n - 2)) {
530 if nodes.typ(lt) == V::LessThan {
531 match nodes.typ(prev) {
532 V::Keyword => {
533 let val = nodes.0[prev].t.val.clone();
534 nodes.0[lt].t.typ = V::PropertyType;
535 nodes.0[lt].t.val = val;
536 if nodes.0[prev].range.is_some() {
537 nodes.0[lt].range = nodes.0[prev].range;
538 }
539 tokens.truncate(tokens.len() - 2);
540 let last = *tokens.last().unwrap();
541 if nodes.0[last].t.val_str() == "function-token" {
542 stack.push(last);
543 }
544 }
545 V::StringToken => {
546 let val = nodes.0[prev].t.val_str().to_string();
547 let inner: String = {
548 let chars: Vec<char> = val.chars().collect();
549 if chars.len() >= 2 { chars[1..chars.len() - 1].iter().collect() } else { String::new() }
550 };
551 nodes.0[lt].t.typ = V::DeclarationType;
552 nodes.0[lt].t.val = VVal::Str(Rc::from(inner));
553 tokens.truncate(tokens.len() - 2);
554 }
555 V::Function => {
556 let val = nodes.0[prev].t.val.clone();
557 nodes.0[lt].t.typ = V::FunctionDefinition;
558 nodes.0[lt].t.val = val;
559 tokens.truncate(tokens.len() - 2);
560 }
561 _ => {}
562 }
563 }
564 }
565 }
566 V::OpenBracket | V::OpenCurlyBrace => stack.push(token),
567 V::CloseBracket => {
568 loop {
569 let Some(s) = top(&stack) else { break };
570 let typ = nodes.typ(s);
571 if typ == V::AmpersandToken || typ == V::ColumnToken || typ == V::PipeToken {
572 let index = last_index_of(&tokens, Some(s));
573 let n = len(&tokens) - index - 2;
574 let part = trim(&nodes, splice(&mut tokens, index + 1, n));
575 if typ == V::AmpersandToken {
576 nodes.0[s].r = Some(part);
577 } else {
578 nodes.0[s].chi_list.get_or_insert_with(Vec::new).push(part);
579 }
580 stack.pop();
581 continue;
582 }
583 break;
584 }
585 let current = top(&stack);
586 let index = last_index_of(&tokens, current);
587 let t = |k: isize| get(&tokens, index + k).map(|x| nodes.typ(x));
588 let is_negative_infinity = t(1) == Some(V::Keyword)
589 && get(&tokens, index + 1).is_some_and(|x| nodes.0[x].t.val_str() == "-")
590 && t(2) == Some(V::InfinityToken);
591 let name_before = matches!(t(-2), Some(V::Keyword) | Some(V::StringToken)) && t(-1) == Some(V::Whitespace);
592 if is_negative_infinity
593 && name_before
594 && t(3) == Some(V::Comma)
595 && matches!(t(4), Some(V::Number) | Some(V::Dimension) | Some(V::InfinityToken))
596 && t(5) == Some(V::CloseBracket)
597 {
598 stack.pop();
599 let name = get(&tokens, index - 2).unwrap();
600 let max = if t(4) == Some(V::InfinityToken) { None } else { get(&tokens, index + 4) };
601 nodes.0[name].range = Some((None, max));
602 splice(&mut tokens, index - 1, 8);
603 continue;
604 }
605 if name_before
606 && matches!(t(1), Some(V::Number) | Some(V::Dimension))
607 && t(2) == Some(V::Comma)
608 && (t(3) == t(1) || t(3) == Some(V::InfinityToken))
609 && t(4) == Some(V::CloseBracket)
610 {
611 stack.pop();
612 let name = get(&tokens, index - 2).unwrap();
613 let min = get(&tokens, index + 1);
614 let max = if t(3) == t(1) { get(&tokens, index + 3) } else { None };
615 nodes.0[name].range = Some((min, max));
616 splice(&mut tokens, index - 1, 7);
617 continue;
618 }
619 stack.pop();
620 let start_index = last_index_of(&tokens, current);
621 let end_index = tokens.iter().position(|&x| x == token).map_or(-1, |i| i as isize);
622 let chi: Vec<usize> = if start_index + 1 <= end_index && end_index >= 0 {
623 tokens[(start_index + 1) as usize..end_index as usize].to_vec()
624 } else {
625 Vec::new()
626 };
627 let chi = trim(&nodes, chi);
628 if let Some(c) = current {
629 nodes.0[c].t.typ = V::Bracket;
630 nodes.0[c].chi = Some(chi);
631 }
632 let n = len(&tokens);
633 splice(&mut tokens, start_index + 1, n);
634 }
635 V::CloseCurlyBrace => {
636 loop {
637 let Some(s) = top(&stack) else { break };
638 let typ = nodes.typ(s);
639 if typ == V::ColumnToken || typ == V::PipeToken {
640 let index = last_index_of(&tokens, Some(s));
641 let n = len(&tokens) - index - 2;
642 let part = trim(&nodes, splice(&mut tokens, index + 1, n));
643 nodes.0[s].chi_list.get_or_insert_with(Vec::new).push(part);
644 stack.pop();
645 continue;
646 }
647 break;
648 }
649 let index = last_index_of(&tokens, top(&stack));
650 let end = tokens.len().saturating_sub(1);
651 let start = (index + 1).max(0) as usize;
652 let slice: Vec<usize> = if start < end { tokens[start..end].to_vec() } else { Vec::new() };
653 if (slice.len() == 1 || slice.len() == 3) && nodes.typ(slice[0]) == V::Number {
654 if let Some(target) = get(&tokens, index - 1) {
655 let max = if slice.len() == 3 {
656 if nodes.typ(slice[2]) == V::InfinityToken {
657 NodeMax::Infinity
658 } else {
659 NodeMax::Token(slice[2])
660 }
661 } else {
662 NodeMax::Token(slice[0])
663 };
664 nodes.0[target].match_ = Some((slice[0], max));
665 }
666 stack.pop();
667 tokens.truncate(index.max(0) as usize);
668 continue;
669 }
670 stack.pop();
671 }
672 V::Star | V::HashMark | V::Exclamation | V::Plus => {
673 let typ = nodes.typ(token);
674 tokens.pop();
675 if let Some(&last) = tokens.last() {
676 let t = &mut nodes.0[last].t;
677 match typ {
678 V::Star => t.is_repeatable = Some(true),
679 V::HashMark => t.is_list = Some(true),
680 V::Exclamation => t.is_mandatatory_group = Some(true),
681 _ => t.is_repeatable_at_least_once = Some(true),
682 }
683 }
684 }
685 V::QuestionMark => {
686 tokens.pop();
687 let is_group = at(&tokens, -3).is_some_and(|t| nodes.typ(t) == V::Comma);
688 if is_group {
689 let slice_index = tokens.len() - 3;
690 let chi = trim(&nodes, tokens[slice_index..].to_vec());
691 tokens.truncate(slice_index);
692 let group = nodes.push(ValidationToken { typ: V::OptionalGroupToken, is_optional: Some(true), ..Default::default() });
693 nodes.0[group].chi = Some(chi);
694 tokens.push(group);
695 } else if let Some(&last) = tokens.last() {
696 nodes.0[last].t.is_optional = Some(true);
697 }
698 }
699 V::Comma => {
700 let before = at(&tokens, -2).map(|t| nodes.typ(t));
701 let prev = at(&tokens, -3);
702 if before == Some(V::Whitespace)
703 && prev.is_some_and(|p| nodes.0[p].t.is_optional() && nodes.typ(p) != V::OptionalGroupToken)
704 {
705 let slice_index = tokens.len() - 3;
706 if nodes.0[tokens[slice_index]].t.is_list() {
707 tokens.pop();
708 }
709 let members: Vec<usize> = tokens[slice_index..].to_vec();
710 for &m in &members {
711 nodes.0[m].t.is_optional = None;
712 }
713 let chi = trim(&nodes, members);
714 tokens.truncate(slice_index);
715 let group = nodes.push(ValidationToken { typ: V::OptionalGroupToken, is_optional: Some(true), ..Default::default() });
716 nodes.0[group].chi = Some(chi);
717 tokens.push(group);
718 }
719 }
720 _ => {}
721 }
722 }
723 if let Some(s) = top(&stack).filter(|&s| nodes.typ(s) == V::PipeToken) {
724 let index = last_index_of(&tokens, Some(s));
725 let n = tokens.len() as isize - index - 1;
726 let part = trim(&nodes, splice(&mut tokens, index + 1, n));
727 nodes.0[s].chi_list.get_or_insert_with(Vec::new).push(part);
728 }
729 let tokens = trim(&nodes, tokens);
730 tokens.into_iter().map(|t| nodes.freeze(t)).collect()
731}
732
733#[derive(Clone, Copy, Debug)]
735pub struct RenderSyntaxOptions {
736 pub minify: bool,
737 pub indent: i64,
738}
739
740impl Default for RenderSyntaxOptions {
741 fn default() -> Self {
742 Self { minify: true, indent: 1 }
743 }
744}
745
746fn render_list(tokens: &[Rc<ValidationToken>], options: &mut RenderSyntaxOptions) -> String {
747 tokens.iter().map(|t| render_syntax(t, options)).collect()
748}
749
750pub fn render_syntax(token: &ValidationToken, options: &mut RenderSyntaxOptions) -> String {
752 let glue = if options.minify { String::new() } else { " ".repeat(options.indent.max(0) as usize) };
753 match token.typ {
754 V::InfinityToken => "\u{221e}".into(),
755 V::Root => render_list(token.children(), options),
756 V::Whitespace => " ".into(),
757 V::FunctionDefinition => format!("<{}()>", token.val_str()),
758 V::HashMark => "#".into(),
759 V::Colon => ":".into(),
760 V::Pipe => format!("{glue}|{glue}"),
761 V::Column => format!("{glue}||{glue}"),
762 V::PipeToken => {
763 let mut acc = String::new();
764 for curr in token.alternatives() {
765 if !acc.trim().is_empty() {
766 acc.push_str(&format!("{glue}|{glue}"));
767 }
768 acc.push_str(&render_list(curr, options));
769 }
770 acc
771 }
772 V::ColumnToken => {
773 let sep = format!("{glue}||{glue}");
774 let mut acc = String::new();
775 for curr in token.alternatives() {
776 if !acc.is_empty() {
777 acc.push_str(&sep);
778 }
779 acc.push_str(&render_list(curr, options));
780 }
781 acc
782 }
783 V::AmpersandToken => {
784 let sep = format!("{glue}&&{glue}");
785 format!(
786 "{}{}{}",
787 render_list(token.l.as_deref().unwrap_or(&[]), options),
788 sep,
789 render_list(token.r.as_deref().unwrap_or(&[]), options)
790 )
791 }
792 V::Function | V::PseudoClassFunctionToken | V::Parens => {
793 format!("{}({}){}", token.val_str(), render_list(token.children(), options), render_attributes(token))
794 }
795 V::Comma => format!(",{glue}"),
796 V::Keyword => format!("{}{}", token.val_str(), render_attributes(token)),
797 V::OpenBracket => format!("[{glue}"),
798 V::Ampersand => format!("{glue}&&{glue}"),
799 V::Plus => "+".into(),
800 V::QuestionMark => "?".into(),
801 V::Separator => "/".into(),
802 V::Bracket => format!("[{glue}{}{glue}]{}", render_list(token.children(), options), render_attributes(token)),
803 V::PropertyType | V::DeclarationType => {
804 let q = if token.typ == V::DeclarationType { "'" } else { "" };
805 let range = match &token.range {
806 None => String::new(),
807 Some(range) => format!(
808 " [{},{}]",
809 range.min.as_ref().map_or("-\u{221e}".into(), |m| render_syntax(m, &mut RenderSyntaxOptions::default())),
810 range.max.as_ref().map_or("\u{221e}".into(), |m| render_syntax(m, &mut RenderSyntaxOptions::default()))
811 ),
812 };
813 format!("<{q}{}{q}{range}>{}", token.val_str(), render_attributes(token))
814 }
815 V::Number => crate::utils::number::js_number_to_string(token.val_num()),
816 V::PseudoClassToken | V::StringToken => token.val_str().to_string(),
817 V::SemiColon => ";".into(),
818 V::AtRule => format!("@{}", token.val_str()),
819 V::AtRuleDefinition => {
820 let prelude = token.prelude.as_ref().map_or(String::new(), |p| format!(" {}", render_list(p, options)));
821 let chi = token.chi.as_ref().map_or(String::new(), |c| format!(" {{\n{}", render_list(c, options)));
822 let chi: String = {
824 let chars: Vec<char> = chi.chars().collect();
825 if chars.len() >= 2 { chars[1..chars.len() - 1].iter().collect() } else { String::new() }
826 };
827 format!("@{}{}{}\n}}", token.val_str(), prelude, chi)
828 }
829 V::Block => {
830 let nl = if options.minify { "" } else { "\n" };
831 format!("{{{nl}{}{nl}}}", render_list(token.children(), options))
832 }
833 V::DeclarationDefinitionToken => {
834 let val = match &token.val {
835 VVal::Token(t) => render_syntax(t, options),
836 _ => String::new(),
837 };
838 format!("{}: {}", token.nam.as_deref().unwrap_or(""), val)
839 }
840 V::LessThan => "<".into(),
841 V::GreaterThan => ">".into(),
842 V::CloseParenthesis => ")".into(),
843 V::OpenParenthesis => "(".into(),
844 V::DisallowWhitespace => "\u{2020} ".into(),
845 V::Dimension => format!("{}{}", crate::utils::number::js_number_to_string(token.val_num()), token.unit_text.as_deref().unwrap_or("")),
846 V::OpenCurlyBrace => {
847 options.indent += 1;
848 format!("{{{}}}", if options.minify { "" } else { "\n" })
849 }
850 V::CloseCurlyBrace => {
851 options.indent -= 1;
852 format!("{}}}", if options.minify { "" } else { "\n" })
853 }
854 V::DeclarationNameToken => format!("{}:", token.val_str()),
855 V::OptionalGroupToken => {
856 let chi = token.children();
857 let mut acc = String::new();
858 for (index, curr) in chi.iter().enumerate() {
859 if index == chi.len() - 1 {
860 if curr.typ == V::Comma {
861 acc.push_str("?,");
862 } else {
863 acc.push_str(&render_syntax(curr, options));
864 acc.push('?');
865 }
866 } else {
867 acc.push_str(&render_syntax(curr, options));
868 }
869 }
870 acc
871 }
872 _ => String::new(),
874 }
875}
876
877fn render_attributes(token: &ValidationToken) -> String {
879 let mut result = String::new();
880 if token.is_list() {
881 result.push('#');
882 }
883 if token.is_optional() {
884 result.push('?');
885 }
886 if token.is_mandatatory_group() {
887 result.push('!');
888 }
889 if token.is_repeatable() {
890 result.push('*');
891 }
892 if token.is_repeatable_at_least_once() {
893 result.push('+');
894 }
895 if let Some(m) = &token.match_ {
896 let min = render_syntax(&m.min, &mut RenderSyntaxOptions::default());
897 match &m.max {
898 MatchMax::Null => result.push_str(&format!("{{{}}}", min)),
899 MatchMax::Token(max) if max.val_num() == m.min.val_num() || max.val_num().is_nan() => {
900 result.push_str(&format!("{{{}}}", min))
901 }
902 MatchMax::Token(max) if max.val_num().is_finite() => {
903 result.push_str(&format!("{{{},{}}}", min, render_syntax(max, &mut RenderSyntaxOptions::default())))
904 }
905 _ => result.push_str(&format!("{{{},\u{221e}}}", min)),
906 }
907 }
908 result
909}