1use std::borrow::Cow;
20
21use crate::tokenizer::{Span, Token, Tokenizer};
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
25pub enum Bracket {
26 Paren,
28 Square,
30 Curly,
32}
33
34impl Bracket {
35 pub fn open(self) -> char {
36 match self {
37 Bracket::Paren => '(',
38 Bracket::Square => '[',
39 Bracket::Curly => '{',
40 }
41 }
42
43 pub fn close(self) -> char {
44 match self {
45 Bracket::Paren => ')',
46 Bracket::Square => ']',
47 Bracket::Curly => '}',
48 }
49 }
50}
51
52#[derive(Clone, Debug, PartialEq)]
55pub enum ComponentValue<'a> {
56 Token(Token<'a>, Span),
59 Function(Function<'a>),
60 Block(SimpleBlock<'a>),
61}
62
63impl<'a> ComponentValue<'a> {
64 pub fn span(&self) -> Span {
65 match self {
66 ComponentValue::Token(_, span) => *span,
67 ComponentValue::Function(f) => f.span,
68 ComponentValue::Block(b) => b.span,
69 }
70 }
71
72 pub fn token(&self) -> Option<&Token<'a>> {
73 match self {
74 ComponentValue::Token(t, _) => Some(t),
75 _ => None,
76 }
77 }
78
79 pub fn is_whitespace(&self) -> bool {
80 matches!(self, ComponentValue::Token(Token::Whitespace, _))
81 }
82
83 fn is(&self, token: &Token<'_>) -> bool {
85 match (self, token) {
86 (ComponentValue::Token(Token::Delim(a), _), Token::Delim(b)) => a == b,
87 (ComponentValue::Token(t, _), _) => {
88 std::mem::discriminant(t) == std::mem::discriminant(token)
89 }
90 _ => false,
91 }
92 }
93
94 fn is_curly(&self) -> bool {
95 matches!(self, ComponentValue::Block(b) if b.bracket == Bracket::Curly)
96 }
97}
98
99#[derive(Clone, Debug, PartialEq)]
101pub struct Function<'a> {
102 pub name: Cow<'a, str>,
103 pub arguments: Vec<ComponentValue<'a>>,
104 pub span: Span,
106}
107
108#[derive(Clone, Debug, PartialEq)]
110pub struct SimpleBlock<'a> {
111 pub bracket: Bracket,
112 pub contents: Vec<ComponentValue<'a>>,
113 pub span: Span,
114}
115
116fn drop_flat(children: &mut Vec<ComponentValue<'_>>) {
119 if children
120 .iter()
121 .all(|c| matches!(c, ComponentValue::Token(..)))
122 {
123 return;
124 }
125 let mut stack = std::mem::take(children);
126 while let Some(child) = stack.pop() {
127 match child {
128 ComponentValue::Function(mut f) => stack.append(&mut f.arguments),
129 ComponentValue::Block(mut b) => stack.append(&mut b.contents),
130 ComponentValue::Token(..) => {}
131 }
132 }
133}
134
135impl Drop for Function<'_> {
136 fn drop(&mut self) {
137 drop_flat(&mut self.arguments);
138 }
139}
140
141impl Drop for SimpleBlock<'_> {
142 fn drop(&mut self) {
143 drop_flat(&mut self.contents);
144 }
145}
146
147impl<'a> SimpleBlock<'a> {
148 pub fn contents(mut self, src: &'a str) -> BlockContents<'a> {
152 let values = std::mem::take(&mut self.contents);
153 let mut p = Parser::new(src, values.into_iter());
154 let items = p.block_contents();
155 BlockContents {
156 items,
157 errors: p.errors,
158 }
159 }
160}
161
162#[derive(Clone, Debug, PartialEq)]
168pub struct AtRule<'a, B = SimpleBlock<'a>> {
169 pub name: Cow<'a, str>,
170 pub prelude: Vec<ComponentValue<'a>>,
171 pub block: Option<B>,
174 pub span: Span,
175}
176
177#[derive(Clone, Debug, PartialEq)]
180pub struct QualifiedRule<'a, B = SimpleBlock<'a>> {
181 pub prelude: Vec<ComponentValue<'a>>,
182 pub block: B,
185 pub span: Span,
186}
187
188#[derive(Clone, Debug, PartialEq)]
189pub enum Rule<'a, B = SimpleBlock<'a>> {
190 At(AtRule<'a, B>),
191 Qualified(QualifiedRule<'a, B>),
192}
193
194impl<B> Rule<'_, B> {
195 pub fn span(&self) -> Span {
196 match self {
197 Rule::At(r) => r.span,
198 Rule::Qualified(r) => r.span,
199 }
200 }
201}
202
203#[derive(Clone, Debug, PartialEq)]
205pub struct Declaration<'a> {
206 pub name: Cow<'a, str>,
207 pub value: Vec<ComponentValue<'a>>,
209 pub important: bool,
210 pub span: Span,
213}
214
215impl Declaration<'_> {
216 pub fn original_text<'s>(&self, src: &'s str) -> &'s str {
219 match (self.value.first(), self.value.last()) {
220 (Some(first), Some(last)) => &src[first.span().start..last.span().end],
221 _ => "",
222 }
223 }
224}
225
226#[derive(Clone, Debug, PartialEq)]
229pub enum Item<'a, B = SimpleBlock<'a>> {
230 Declaration(Declaration<'a>),
231 Rule(Rule<'a, B>),
232}
233
234#[derive(Clone, Debug, PartialEq, Default)]
237pub struct Block<'a> {
238 pub items: Vec<Item<'a, Block<'a>>>,
239 pub span: Span,
241}
242
243impl Drop for Block<'_> {
244 fn drop(&mut self) {
247 if self.items.iter().all(|i| matches!(i, Item::Declaration(_))) {
248 return;
249 }
250 let mut stack = std::mem::take(&mut self.items);
251 while let Some(item) = stack.pop() {
252 match item {
253 Item::Rule(Rule::Qualified(mut r)) => stack.append(&mut r.block.items),
254 Item::Rule(Rule::At(AtRule {
255 block: Some(mut b), ..
256 })) => stack.append(&mut b.items),
257 _ => {}
258 }
259 }
260 }
261}
262
263#[derive(Clone, Copy, Debug, PartialEq, Eq)]
265pub struct ParseError {
266 pub kind: ErrorKind,
267 pub span: Span,
268}
269
270#[derive(Clone, Copy, Debug, PartialEq, Eq)]
271pub enum ErrorKind {
272 Empty,
274 ExtraInput,
276 InvalidDeclaration,
278 InvalidRule,
280}
281
282impl std::fmt::Display for ParseError {
283 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284 let what = match self.kind {
285 ErrorKind::Empty => "nothing to parse",
286 ErrorKind::ExtraInput => "unexpected input after the end",
287 ErrorKind::InvalidDeclaration => "invalid declaration",
288 ErrorKind::InvalidRule => "invalid rule",
289 };
290 write!(f, "{what} at bytes {}..{}", self.span.start, self.span.end)
291 }
292}
293
294impl std::error::Error for ParseError {}
295
296#[derive(Clone, Debug, PartialEq)]
298pub struct Stylesheet<'a, B = SimpleBlock<'a>> {
299 pub rules: Vec<Rule<'a, B>>,
300 pub errors: Vec<ParseError>,
301}
302
303impl<B> Default for Stylesheet<'_, B> {
304 fn default() -> Self {
305 Stylesheet {
306 rules: Vec::new(),
307 errors: Vec::new(),
308 }
309 }
310}
311
312#[derive(Clone, Debug, PartialEq, Default)]
314pub struct BlockContents<'a> {
315 pub items: Vec<Item<'a>>,
316 pub errors: Vec<ParseError>,
317}
318
319pub(crate) struct Values<'a> {
324 pub(crate) tokens: Tokenizer<'a>,
325 open: Vec<Open<'a>>,
326 buffer: Vec<ComponentValue<'a>>,
327 pub(crate) limit: usize,
330}
331
332pub const MAX_NESTING: usize = 256;
335
336impl<'a> Values<'a> {
337 pub(crate) fn new(tokens: Tokenizer<'a>) -> Values<'a> {
338 Values {
339 tokens,
340 open: Vec::new(),
341 buffer: Vec::new(),
342 limit: MAX_NESTING,
343 }
344 }
345
346 fn skip(&mut self, bracket: Option<Bracket>) -> usize {
350 let mut open = vec![bracket];
351 while let Some((token, span)) = self.tokens.next_token() {
352 let closes = |b: Option<Bracket>| {
353 matches!(
354 (b, &token),
355 (None | Some(Bracket::Paren), Token::RightParen)
356 | (Some(Bracket::Square), Token::RightBracket)
357 | (Some(Bracket::Curly), Token::RightBrace)
358 )
359 };
360 if closes(*open.last().unwrap()) {
361 open.pop();
362 if open.is_empty() {
363 return span.end;
364 }
365 continue;
366 }
367 match token {
368 Token::Function(_) => open.push(None),
369 Token::LeftParen => open.push(Some(Bracket::Paren)),
370 Token::LeftBracket => open.push(Some(Bracket::Square)),
371 Token::LeftBrace => open.push(Some(Bracket::Curly)),
372 _ => {}
373 }
374 }
375 self.tokens.source().len()
376 }
377}
378
379struct Open<'a> {
380 bracket: Option<Bracket>,
382 name: Cow<'a, str>,
383 start: usize,
384 at: usize,
386}
387
388pub(crate) fn take_tail<T>(buf: &mut Vec<T>, at: usize) -> Vec<T> {
391 if at > 0 {
392 return buf.split_off(at);
393 }
394 let mut tail = Vec::with_capacity(buf.len());
396 tail.append(buf);
397 tail
398}
399
400#[inline]
402fn opens<'a>(token: Token<'a>, start: usize, at: usize) -> Result<Open<'a>, Token<'a>> {
403 let (bracket, name) = match token {
404 Token::Function(name) => (None, name),
405 Token::LeftParen => (Some(Bracket::Paren), Cow::Borrowed("")),
406 Token::LeftBracket => (Some(Bracket::Square), Cow::Borrowed("")),
407 Token::LeftBrace => (Some(Bracket::Curly), Cow::Borrowed("")),
408 other => return Err(other),
409 };
410 Ok(Open {
411 bracket,
412 name,
413 start,
414 at,
415 })
416}
417
418impl<'a> Open<'a> {
419 fn closes(&self, token: &Token<'_>) -> bool {
420 matches!(
421 (self.bracket, token),
422 (None | Some(Bracket::Paren), Token::RightParen)
423 | (Some(Bracket::Square), Token::RightBracket)
424 | (Some(Bracket::Curly), Token::RightBrace)
425 )
426 }
427
428 fn finish(self, values: Vec<ComponentValue<'a>>, end: usize) -> ComponentValue<'a> {
429 let span = Span::new(self.start, end);
430 match self.bracket {
431 None => ComponentValue::Function(Function {
432 name: self.name,
433 arguments: values,
434 span,
435 }),
436 Some(bracket) => ComponentValue::Block(SimpleBlock {
437 bracket,
438 contents: values,
439 span,
440 }),
441 }
442 }
443}
444
445impl<'a> Iterator for Values<'a> {
446 type Item = ComponentValue<'a>;
447
448 fn next(&mut self) -> Option<ComponentValue<'a>> {
449 let (token, span) = self.tokens.next_token()?;
450 Some(self.whole(token, span))
451 }
452}
453
454impl<'a> Values<'a> {
455 #[inline]
458 pub(crate) fn whole(&mut self, token: Token<'a>, span: Span) -> ComponentValue<'a> {
459 match opens(token, span.start, 0) {
460 Ok(open) => self.open.push(open),
461 Err(token) => return ComponentValue::Token(token, span),
462 }
463 self.rest_of_open()
464 }
465
466 fn rest_of_open(&mut self) -> ComponentValue<'a> {
467 loop {
468 let Some((token, span)) = self.tokens.next_token() else {
469 let end = self.tokens.source().len();
471 loop {
472 let open = self.open.pop().unwrap();
473 let values = take_tail(&mut self.buffer, open.at);
474 let done = open.finish(values, end);
475 if self.open.is_empty() {
476 return done;
477 }
478 self.buffer.push(done);
479 }
480 };
481 if self.open.last().unwrap().closes(&token) {
482 let open = self.open.pop().unwrap();
483 let values = take_tail(&mut self.buffer, open.at);
484 let done = open.finish(values, span.end);
485 if self.open.is_empty() {
486 return done;
487 }
488 self.buffer.push(done);
489 continue;
490 }
491 if !matches!(
492 token,
493 Token::Function(_) | Token::LeftParen | Token::LeftBracket | Token::LeftBrace
494 ) {
495 self.buffer.push(ComponentValue::Token(token, span));
496 continue;
497 }
498 match opens(token, span.start, self.buffer.len()) {
499 Ok(open) if self.open.len() >= self.limit => {
500 self.skip(open.bracket);
501 }
502 Ok(open) => self.open.push(open),
503 Err(token) => self.buffer.push(ComponentValue::Token(token, span)),
504 }
505 }
506 }
507}
508
509trait Source<'a>: Iterator<Item = ComponentValue<'a>> {
512 fn rest(&self) -> Option<&[ComponentValue<'a>]> {
514 None
515 }
516}
517
518impl<'a> Source<'a> for Values<'a> {}
519
520impl<'a> Source<'a> for std::vec::IntoIter<ComponentValue<'a>> {
521 fn rest(&self) -> Option<&[ComponentValue<'a>]> {
522 Some(self.as_slice())
523 }
524}
525
526fn before_semicolon(values: &[ComponentValue<'_>], nested: bool) -> Option<usize> {
529 let mut watch = Watch::Name;
530 for (i, v) in values.iter().enumerate() {
531 if v.is(&Token::Semicolon) || (nested && v.is(&Token::RightBrace)) {
532 return Some(i);
533 }
534 if nested && !watch.see(v) {
535 return None;
536 }
537 }
538 Some(values.len())
539}
540
541#[derive(Clone, Copy)]
548pub(crate) enum Watch {
549 Name,
550 Colon {
551 custom: bool,
552 },
553 Custom,
555 Value(Seen),
556}
557
558#[derive(Clone, Copy)]
559pub(crate) enum Seen {
560 Nothing,
561 Other,
562 Block(u8),
564}
565
566impl Watch {
567 pub(crate) fn see(&mut self, v: &ComponentValue<'_>) -> bool {
569 if v.is_whitespace() {
570 return true;
571 }
572 *self = match *self {
573 Watch::Name => match v {
574 ComponentValue::Token(Token::Ident(n), _) => Watch::Colon {
575 custom: n.starts_with("--"),
576 },
577 _ => return false,
578 },
579 Watch::Colon { custom } if v.is(&Token::Colon) => match custom {
580 true => Watch::Custom,
581 false => Watch::Value(Seen::Nothing),
582 },
583 Watch::Colon { .. } => return false,
584 Watch::Custom => Watch::Custom,
585 Watch::Value(seen) => Watch::Value(match (seen, v.is_curly()) {
586 (Seen::Nothing, true) => Seen::Block(0),
587 (Seen::Nothing | Seen::Other, false) => Seen::Other,
588 (Seen::Other, true) => return false,
589 (Seen::Block(0), _) if v.is(&Token::Delim('!')) => Seen::Block(1),
590 (Seen::Block(1), _)
591 if matches!(v, ComponentValue::Token(Token::Ident(w), _)
592 if w.eq_ignore_ascii_case("important")) =>
593 {
594 Seen::Block(2)
595 }
596 (Seen::Block(_), _) => return false,
597 }),
598 };
599 true
600 }
601}
602
603struct Parser<'a, I> {
606 src: &'a str,
607 input: I,
608 back: Vec<ComponentValue<'a>>,
609 scratch: Vec<ComponentValue<'a>>,
611 errors: Vec<ParseError>,
612}
613
614fn text(src: &str) -> Parser<'_, Values<'_>> {
615 Parser::new(src, Values::new(Tokenizer::new(src)))
616}
617
618impl<'a, I: Source<'a>> Parser<'a, I> {
619 fn new(src: &'a str, input: I) -> Parser<'a, I> {
620 Parser {
621 src,
622 input,
623 back: Vec::new(),
624 scratch: Vec::new(),
625 errors: Vec::new(),
626 }
627 }
628
629 fn peek(&mut self) -> Option<&ComponentValue<'a>> {
630 if self.back.is_empty() {
631 if self.input.rest().is_some() {
632 return self.input.rest().and_then(<[_]>::first);
633 }
634 let next = self.input.next()?;
635 self.back.push(next);
636 }
637 self.back.last()
638 }
639
640 fn next(&mut self) -> Option<ComponentValue<'a>> {
641 self.back.pop().or_else(|| self.input.next())
642 }
643
644 fn put_back(&mut self, values: Vec<ComponentValue<'a>>) {
645 self.back.extend(values.into_iter().rev());
646 }
647
648 fn skip_whitespace(&mut self) {
649 while self.peek().is_some_and(ComponentValue::is_whitespace) {
650 self.next();
651 }
652 }
653
654 fn error(&mut self, kind: ErrorKind, start: usize, end: usize) {
655 self.errors.push(ParseError {
656 kind,
657 span: Span::new(start, end.max(start)),
658 });
659 }
660
661 fn rules(&mut self, cdo_cdc: bool) -> Vec<Rule<'a>> {
664 let mut rules = Vec::new();
665 while let Some(next) = self.peek() {
666 match next {
667 ComponentValue::Token(Token::Whitespace, _) => {
668 self.next();
669 }
670 ComponentValue::Token(Token::Cdo | Token::Cdc, _) if cdo_cdc => {
671 self.next();
672 }
673 ComponentValue::Token(Token::AtKeyword(_), _) => {
674 let rule = self.at_rule(false);
675 rules.push(Rule::At(rule));
676 }
677 _ => {
678 if let Some(rule) = self.qualified_rule(false, false) {
679 rules.push(Rule::Qualified(rule));
680 }
681 }
682 }
683 }
684 rules
685 }
686
687 fn at_rule(&mut self, nested: bool) -> AtRule<'a> {
690 let Some(ComponentValue::Token(Token::AtKeyword(name), span)) = self.next() else {
691 unreachable!("at_rule is called on an at-keyword");
692 };
693 let mut rule = AtRule {
694 name,
695 prelude: Vec::new(),
696 block: None,
697 span,
698 };
699 while let Some(next) = self.next() {
700 match next {
701 ComponentValue::Token(Token::Semicolon, _) => break,
702 ComponentValue::Token(Token::RightBrace, _) if nested => {
703 self.back.push(next);
704 break;
705 }
706 ComponentValue::Block(block) if block.bracket == Bracket::Curly => {
707 rule.span.end = block.span.end;
708 rule.block = Some(block);
709 break;
710 }
711 other => {
712 rule.span.end = other.span().end;
713 self.scratch.push(other);
714 }
715 }
716 }
717 rule.prelude = take_tail(&mut self.scratch, 0);
718 rule
719 }
720
721 fn qualified_rule(&mut self, stop: bool, nested: bool) -> Option<QualifiedRule<'a>> {
724 let end_of_input = self.src.len();
725 let start = self.peek().map_or(end_of_input, |v| v.span().start);
726 self.scratch.clear();
728 let mut end = start;
729 loop {
730 let Some(next) = self.next() else {
731 self.scratch.clear();
732 self.error(ErrorKind::InvalidRule, start, end);
733 return None;
734 };
735 match next {
736 ComponentValue::Token(Token::Semicolon, _) if stop => {
737 self.back.push(next);
738 self.scratch.clear();
739 self.error(ErrorKind::InvalidRule, start, end);
740 return None;
741 }
742 ComponentValue::Token(Token::RightBrace, _) if nested => {
743 self.back.push(next);
744 self.scratch.clear();
745 self.error(ErrorKind::InvalidRule, start, end);
746 return None;
747 }
748 ComponentValue::Block(block) if block.bracket == Bracket::Curly => {
749 let end = block.span.end;
750 let prelude = take_tail(&mut self.scratch, 0);
751 if looks_like_custom_property(&prelude) {
752 if nested {
755 self.bad_declaration_remnants(true);
756 }
757 self.error(ErrorKind::InvalidRule, start, end);
758 return None;
759 }
760 return Some(QualifiedRule {
761 prelude,
762 block,
763 span: Span::new(start, end),
764 });
765 }
766 other => {
767 end = other.span().end;
768 self.scratch.push(other);
769 }
770 }
771 }
772 }
773
774 fn bad_declaration_remnants(&mut self, nested: bool) {
775 while let Some(next) = self.next() {
776 match next {
777 ComponentValue::Token(Token::Semicolon, _) => return,
778 ComponentValue::Token(Token::RightBrace, _) if nested => {
779 self.back.push(next);
780 return;
781 }
782 _ => {}
783 }
784 }
785 }
786
787 fn up_to_semicolon(
792 &mut self,
793 nested: bool,
794 ) -> Result<Vec<ComponentValue<'a>>, Vec<ComponentValue<'a>>> {
795 let mut values = Vec::new();
796 let mut watch = Watch::Name;
797 while let Some(next) = self.peek() {
798 if next.is(&Token::Semicolon) || (nested && next.is(&Token::RightBrace)) {
799 break;
800 }
801 let next = self.next().unwrap();
802 let hopeless = nested && !watch.see(&next);
803 values.push(next);
804 if hopeless {
805 return Err(values);
806 }
807 }
808 Ok(values)
809 }
810
811 fn declaration(&mut self, nested: bool) -> Result<Declaration<'a>, Vec<ComponentValue<'a>>> {
814 if self.back.is_empty()
816 && let Some(rest) = self.input.rest()
817 {
818 let Some(n) = before_semicolon(rest, nested) else {
819 return Err(Vec::new());
820 };
821 if let Some(plan) = plan(&rest[..n]) {
822 let name = self.input.next().unwrap();
823 for _ in 1..plan.value_start {
826 self.input.next();
827 }
828 let value = self
829 .input
830 .by_ref()
831 .take(plan.value_end - plan.value_start)
832 .collect();
833 for _ in plan.value_end.max(plan.value_start)..n {
835 self.input.next();
836 }
837 return Ok(build(name, value, &plan, self.src));
838 }
839 return Err(self.input.by_ref().take(n).collect());
840 }
841 let values = self.up_to_semicolon(nested)?;
842 declaration_from(values, self.src)
843 }
844
845 fn block_contents(&mut self) -> Vec<Item<'a>> {
847 let mut items = Vec::new();
848 while let Some(next) = self.peek() {
849 match next {
850 ComponentValue::Token(Token::Whitespace | Token::Semicolon, _) => {
851 self.next();
852 }
853 ComponentValue::Token(Token::RightBrace, span) => {
856 let span = *span;
857 self.next();
858 self.error(ErrorKind::InvalidRule, span.start, span.end);
859 }
860 ComponentValue::Token(Token::AtKeyword(_), _) => {
861 let rule = self.at_rule(true);
862 items.push(Item::Rule(Rule::At(rule)));
863 }
864 ComponentValue::Token(Token::Ident(_), _) => match self.declaration(true) {
866 Ok(decl) => items.push(Item::Declaration(decl)),
867 Err(values) => {
868 self.put_back(values);
869 if let Some(rule) = self.qualified_rule(true, true) {
870 items.push(Item::Rule(Rule::Qualified(rule)));
871 }
872 }
873 },
874 _ => {
875 if let Some(rule) = self.qualified_rule(true, true) {
876 items.push(Item::Rule(Rule::Qualified(rule)));
877 }
878 }
879 }
880 }
881 items
882 }
883
884 fn declaration_list(&mut self) -> Vec<Item<'a>> {
887 let mut items = Vec::new();
888 while let Some(next) = self.peek() {
889 match next {
890 ComponentValue::Token(Token::Whitespace | Token::Semicolon, _) => {
891 self.next();
892 }
893 ComponentValue::Token(Token::AtKeyword(_), _) => {
894 let rule = self.at_rule(false);
895 items.push(Item::Rule(Rule::At(rule)));
896 }
897 _ => match self.declaration(false) {
898 Ok(decl) => items.push(Item::Declaration(decl)),
899 Err(values) => {
900 let start = values.first().map_or(0, |v| v.span().start);
901 let end = values.last().map_or(start, |v| v.span().end);
902 self.error(ErrorKind::InvalidDeclaration, start, end);
903 }
904 },
905 }
906 }
907 items
908 }
909
910 fn end<T>(&mut self, value: T) -> Result<T, ParseError> {
912 self.skip_whitespace();
913 match self.peek() {
914 None => Ok(value),
915 Some(v) => {
916 let start = v.span().start;
917 Err(ParseError {
918 kind: ErrorKind::ExtraInput,
919 span: Span::new(start, self.src.len()),
920 })
921 }
922 }
923 }
924
925 fn start(&mut self) -> Result<(), ParseError> {
926 self.skip_whitespace();
927 match self.peek() {
928 Some(_) => Ok(()),
929 None => Err(ParseError {
930 kind: ErrorKind::Empty,
931 span: Span::new(0, self.src.len()),
932 }),
933 }
934 }
935}
936
937pub(crate) fn looks_like_custom_property(prelude: &[ComponentValue<'_>]) -> bool {
939 let mut it = prelude.iter().filter(|v| !v.is_whitespace());
940 matches!(it.next(), Some(ComponentValue::Token(Token::Ident(n), _)) if n.starts_with("--"))
941 && it.next().is_some_and(|v| v.is(&Token::Colon))
942}
943
944struct Plan {
947 value_start: usize,
948 value_end: usize,
949 important: bool,
950 unicode_range: bool,
951 span: Span,
952}
953
954fn plan(values: &[ComponentValue<'_>]) -> Option<Plan> {
956 let Some(ComponentValue::Token(Token::Ident(name), first)) = values.first() else {
957 return None;
958 };
959 let mut colon = 1;
960 while values.get(colon).is_some_and(ComponentValue::is_whitespace) {
961 colon += 1;
962 }
963 let colon_end = match values.get(colon) {
964 Some(ComponentValue::Token(Token::Colon, span)) => span.end,
965 _ => return None,
966 };
967 let after = colon + 1;
968 let v = value_plan(name, &values[after..])?;
969 Some(Plan {
970 value_start: after + v.start,
971 value_end: after + v.end,
972 important: v.important,
973 unicode_range: name.eq_ignore_ascii_case("unicode-range"),
974 span: Span::new(first.start, v.last_end.unwrap_or(colon_end)),
975 })
976}
977
978pub(crate) struct ValuePlan {
980 pub(crate) start: usize,
981 pub(crate) end: usize,
982 pub(crate) important: bool,
983 pub(crate) last_end: Option<usize>,
986}
987
988pub(crate) fn value_plan(name: &str, values: &[ComponentValue<'_>]) -> Option<ValuePlan> {
991 let mut start = 0;
992 while values.get(start).is_some_and(ComponentValue::is_whitespace) {
993 start += 1;
994 }
995 let mut solid = (start..values.len())
997 .rev()
998 .filter(|&i| !values[i].is_whitespace());
999 let last = solid.next();
1000 let before = solid.next();
1001 let important = match (before, last) {
1002 (Some(bang), Some(word))
1003 if values[bang].is(&Token::Delim('!'))
1004 && matches!(&values[word], ComponentValue::Token(Token::Ident(w), _)
1005 if w.eq_ignore_ascii_case("important")) =>
1006 {
1007 Some(bang)
1008 }
1009 _ => None,
1010 };
1011 let mut end = important.unwrap_or(values.len());
1012 while end > start && values[end - 1].is_whitespace() {
1013 end -= 1;
1014 }
1015 if !name.starts_with("--") {
1016 let value = &values[start..end];
1018 if value.len() > 1 && value.iter().any(ComponentValue::is_curly) {
1019 return None;
1020 }
1021 }
1022 Some(ValuePlan {
1023 start,
1024 end,
1025 important: important.is_some(),
1026 last_end: last.map(|i| values[i].span().end),
1027 })
1028}
1029
1030fn build<'a>(
1032 name: ComponentValue<'a>,
1033 mut value: Vec<ComponentValue<'a>>,
1034 plan: &Plan,
1035 src: &'a str,
1036) -> Declaration<'a> {
1037 let ComponentValue::Token(Token::Ident(name), _) = name else {
1038 unreachable!("a plan starts with an ident")
1039 };
1040 if plan.unicode_range && !value.is_empty() {
1041 let from = value[0].span().start;
1043 let to = value[value.len() - 1].span().end;
1044 value = Values::new(unicode_range_tokens(src, from, to)).collect();
1045 }
1046 Declaration {
1047 name,
1048 value,
1049 important: plan.important,
1050 span: plan.span,
1051 }
1052}
1053
1054fn declaration_from<'a>(
1056 mut values: Vec<ComponentValue<'a>>,
1057 src: &'a str,
1058) -> Result<Declaration<'a>, Vec<ComponentValue<'a>>> {
1059 let Some(plan) = plan(&values) else {
1060 return Err(values);
1061 };
1062 let blank = ComponentValue::Token(Token::Whitespace, Span::default());
1063 let name = std::mem::replace(&mut values[0], blank);
1064 values.truncate(plan.value_end);
1066 values.drain(..plan.value_start);
1067 Ok(build(name, values, &plan, src))
1068}
1069
1070pub(crate) fn unicode_range_tokens(src: &str, from: usize, to: usize) -> Tokenizer<'_> {
1073 let mut t = Tokenizer::with_unicode_ranges(&src[..to]);
1074 t.reset(from);
1075 t
1076}
1077
1078pub fn parse_stylesheet(css: &str) -> Stylesheet<'_> {
1087 let mut p = text(css);
1088 let rules = p.rules(true);
1089 Stylesheet {
1090 rules,
1091 errors: p.errors,
1092 }
1093}
1094
1095pub fn parse_rule_list(css: &str) -> Stylesheet<'_> {
1099 let mut p = text(css);
1100 let rules = p.rules(false);
1101 Stylesheet {
1102 rules,
1103 errors: p.errors,
1104 }
1105}
1106
1107pub fn parse_block_contents(css: &str) -> BlockContents<'_> {
1119 let mut p = text(css);
1120 let items = p.block_contents();
1121 BlockContents {
1122 items,
1123 errors: p.errors,
1124 }
1125}
1126
1127pub fn parse_declaration_list(css: &str) -> BlockContents<'_> {
1131 let mut p = text(css);
1132 let items = p.declaration_list();
1133 BlockContents {
1134 items,
1135 errors: p.errors,
1136 }
1137}
1138
1139pub fn parse_rule(css: &str) -> Result<Rule<'_>, ParseError> {
1141 let mut p = text(css);
1142 p.start()?;
1143 let rule = if matches!(
1144 p.peek(),
1145 Some(ComponentValue::Token(Token::AtKeyword(_), _))
1146 ) {
1147 Rule::At(p.at_rule(false))
1148 } else {
1149 match p.qualified_rule(false, false) {
1150 Some(rule) => Rule::Qualified(rule),
1151 None => return Err(p.errors.pop().unwrap()),
1152 }
1153 };
1154 p.end(rule)
1155}
1156
1157pub fn parse_declaration(css: &str) -> Result<Declaration<'_>, ParseError> {
1159 let mut p = text(css);
1160 p.start()?;
1161 match p.declaration(false) {
1162 Ok(decl) => p.end(decl),
1163 Err(values) => {
1164 let start = values.first().map_or(0, |v| v.span().start);
1165 Err(ParseError {
1166 kind: ErrorKind::InvalidDeclaration,
1167 span: Span::new(start, css.len()),
1168 })
1169 }
1170 }
1171}
1172
1173pub fn parse_component_value(css: &str) -> Result<ComponentValue<'_>, ParseError> {
1175 let mut p = text(css);
1176 p.start()?;
1177 let value = p.next().unwrap();
1178 p.end(value)
1179}
1180
1181pub fn parse_component_values(css: &str) -> Vec<ComponentValue<'_>> {
1184 Values::new(Tokenizer::new(css)).collect()
1185}
1186
1187pub fn parse_comma_separated(css: &str) -> Vec<Vec<ComponentValue<'_>>> {
1190 let mut values = Values::new(Tokenizer::new(css)).peekable();
1191 let mut groups = Vec::new();
1192 while values.peek().is_some() {
1193 let mut group = Vec::new();
1194 for v in values.by_ref() {
1195 if v.is(&Token::Comma) {
1196 break;
1197 }
1198 group.push(v);
1199 }
1200 groups.push(group);
1201 }
1202 groups
1203}
1204
1205pub fn parse_unicode_range_value(css: &str) -> Vec<ComponentValue<'_>> {
1208 Values::new(Tokenizer::with_unicode_ranges(css)).collect()
1209}
1210
1211#[cfg(test)]
1212mod tests {
1213 use super::*;
1214
1215 #[test]
1216 fn deep_nesting_parses_and_drops() {
1217 let css = "(".repeat(1_000_000);
1218 let values = parse_component_values(&css);
1219 assert_eq!(values.len(), 1);
1220 drop(values);
1221 let css = format!("a{{b:{}}}", "[".repeat(200_000));
1222 let sheet = parse_stylesheet(&css);
1223 let Rule::Qualified(rule) = sheet.rules.into_iter().next().unwrap() else {
1224 panic!()
1225 };
1226 assert_eq!(rule.block.contents(&css).items.len(), 1);
1227 }
1228
1229 #[test]
1230 fn spans_cover_rules_and_declarations() {
1231 let css = "a { color: red !important; } @x y;";
1232 let sheet = parse_stylesheet(css);
1233 assert_eq!(
1234 sheet.rules[0].span().text(css),
1235 "a { color: red !important; }"
1236 );
1237 assert_eq!(
1238 sheet.rules[1].span().text(css),
1239 "@x y;".trim_end_matches(';')
1240 );
1241 let Rule::Qualified(rule) = sheet.rules.into_iter().next().unwrap() else {
1242 panic!()
1243 };
1244 let Item::Declaration(d) = &rule.block.contents(css).items[0] else {
1245 panic!()
1246 };
1247 assert_eq!(d.span.text(css), "color: red !important");
1248 assert_eq!(d.original_text(css), "red");
1249 assert!(d.important);
1250 }
1251
1252 #[test]
1253 fn block_contents_parsed_later_match_parsing_at_once() {
1254 let css = "color: red; &:hover { b: c } --x: {a} b; d:e{f}; @media x { g: h }";
1255 let at_once = parse_block_contents(css);
1256 let wrapped = format!("{{{css}}}");
1257 let Ok(ComponentValue::Block(block)) = parse_component_value(&wrapped) else {
1258 panic!()
1259 };
1260 let later = block.contents(&wrapped);
1261 assert_eq!(at_once.items.len(), later.items.len());
1262 assert_eq!(at_once.errors.len(), later.errors.len());
1263 }
1264
1265 #[test]
1266 fn unicode_range_descriptor_gets_range_tokens() {
1267 let d = parse_declaration("unicode-range: U+0-7F, u+4??").unwrap();
1268 let ranges: Vec<_> = d
1269 .value
1270 .iter()
1271 .filter_map(|v| match v.token() {
1272 Some(Token::UnicodeRange { start, end }) => Some((*start, *end)),
1273 _ => None,
1274 })
1275 .collect();
1276 assert_eq!(ranges, [(0, 0x7f), (0x400, 0x4ff)]);
1277 }
1278}