1use std::borrow::Cow;
17
18use crate::tokenizer::{Span, Token, Tokenizer};
19
20#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
22pub enum Bracket {
23 Paren,
25 Square,
27 Curly,
29}
30
31impl Bracket {
32 pub fn open(self) -> char {
33 match self {
34 Bracket::Paren => '(',
35 Bracket::Square => '[',
36 Bracket::Curly => '{',
37 }
38 }
39
40 pub fn close(self) -> char {
41 match self {
42 Bracket::Paren => ')',
43 Bracket::Square => ']',
44 Bracket::Curly => '}',
45 }
46 }
47}
48
49#[derive(Clone, Debug, PartialEq)]
52pub enum ComponentValue<'a> {
53 Token(Token<'a>, Span),
56 Function(Function<'a>),
57 Block(SimpleBlock<'a>),
58}
59
60impl<'a> ComponentValue<'a> {
61 pub fn span(&self) -> Span {
62 match self {
63 ComponentValue::Token(_, span) => *span,
64 ComponentValue::Function(f) => f.span,
65 ComponentValue::Block(b) => b.span,
66 }
67 }
68
69 pub fn token(&self) -> Option<&Token<'a>> {
70 match self {
71 ComponentValue::Token(t, _) => Some(t),
72 _ => None,
73 }
74 }
75
76 pub fn is_whitespace(&self) -> bool {
77 matches!(self, ComponentValue::Token(Token::Whitespace, _))
78 }
79
80 fn is(&self, token: &Token<'_>) -> bool {
82 match (self, token) {
83 (ComponentValue::Token(Token::Delim(a), _), Token::Delim(b)) => a == b,
84 (ComponentValue::Token(t, _), _) => {
85 std::mem::discriminant(t) == std::mem::discriminant(token)
86 }
87 _ => false,
88 }
89 }
90
91 fn is_curly(&self) -> bool {
92 matches!(self, ComponentValue::Block(b) if b.bracket == Bracket::Curly)
93 }
94}
95
96#[derive(Clone, Debug, PartialEq)]
98pub struct Function<'a> {
99 pub name: Cow<'a, str>,
100 pub arguments: Vec<ComponentValue<'a>>,
101 pub span: Span,
103}
104
105#[derive(Clone, Debug, PartialEq)]
107pub struct SimpleBlock<'a> {
108 pub bracket: Bracket,
109 pub contents: Vec<ComponentValue<'a>>,
110 pub span: Span,
111}
112
113fn drop_flat(children: &mut Vec<ComponentValue<'_>>) {
116 if children
117 .iter()
118 .all(|c| matches!(c, ComponentValue::Token(..)))
119 {
120 return;
121 }
122 let mut stack = std::mem::take(children);
123 while let Some(child) = stack.pop() {
124 match child {
125 ComponentValue::Function(mut f) => stack.append(&mut f.arguments),
126 ComponentValue::Block(mut b) => stack.append(&mut b.contents),
127 ComponentValue::Token(..) => {}
128 }
129 }
130}
131
132impl Drop for Function<'_> {
133 fn drop(&mut self) {
134 drop_flat(&mut self.arguments);
135 }
136}
137
138impl Drop for SimpleBlock<'_> {
139 fn drop(&mut self) {
140 drop_flat(&mut self.contents);
141 }
142}
143
144impl<'a> SimpleBlock<'a> {
145 pub fn contents(mut self, src: &'a str) -> BlockContents<'a> {
149 let values = std::mem::take(&mut self.contents);
150 let mut p = Parser::new(src, values.into_iter());
151 let items = p.block_contents();
152 BlockContents {
153 items,
154 errors: p.errors,
155 }
156 }
157}
158
159#[derive(Clone, Debug, PartialEq)]
165pub struct AtRule<'a, B = SimpleBlock<'a>> {
166 pub name: Cow<'a, str>,
167 pub prelude: Vec<ComponentValue<'a>>,
168 pub block: Option<B>,
171 pub span: Span,
172}
173
174#[derive(Clone, Debug, PartialEq)]
177pub struct QualifiedRule<'a, B = SimpleBlock<'a>> {
178 pub prelude: Vec<ComponentValue<'a>>,
179 pub block: B,
182 pub span: Span,
183}
184
185#[derive(Clone, Debug, PartialEq)]
186pub enum Rule<'a, B = SimpleBlock<'a>> {
187 At(AtRule<'a, B>),
188 Qualified(QualifiedRule<'a, B>),
189}
190
191impl<B> Rule<'_, B> {
192 pub fn span(&self) -> Span {
193 match self {
194 Rule::At(r) => r.span,
195 Rule::Qualified(r) => r.span,
196 }
197 }
198}
199
200#[derive(Clone, Debug, PartialEq)]
202pub struct Declaration<'a> {
203 pub name: Cow<'a, str>,
204 pub value: Vec<ComponentValue<'a>>,
206 pub important: bool,
207 pub span: Span,
210}
211
212impl Declaration<'_> {
213 pub fn original_text<'s>(&self, src: &'s str) -> &'s str {
216 match (self.value.first(), self.value.last()) {
217 (Some(first), Some(last)) => &src[first.span().start..last.span().end],
218 _ => "",
219 }
220 }
221}
222
223#[derive(Clone, Debug, PartialEq)]
226pub enum Item<'a, B = SimpleBlock<'a>> {
227 Declaration(Declaration<'a>),
228 Rule(Rule<'a, B>),
229}
230
231#[derive(Clone, Debug, PartialEq, Default)]
234pub struct Block<'a> {
235 pub items: Vec<Item<'a, Block<'a>>>,
236 pub span: Span,
238}
239
240impl Drop for Block<'_> {
241 fn drop(&mut self) {
244 if self.items.iter().all(|i| matches!(i, Item::Declaration(_))) {
245 return;
246 }
247 let mut stack = std::mem::take(&mut self.items);
248 while let Some(item) = stack.pop() {
249 match item {
250 Item::Rule(Rule::Qualified(mut r)) => stack.append(&mut r.block.items),
251 Item::Rule(Rule::At(AtRule {
252 block: Some(mut b), ..
253 })) => stack.append(&mut b.items),
254 _ => {}
255 }
256 }
257 }
258}
259
260#[derive(Clone, Copy, Debug, PartialEq, Eq)]
262pub struct ParseError {
263 pub kind: ErrorKind,
264 pub span: Span,
265}
266
267#[derive(Clone, Copy, Debug, PartialEq, Eq)]
268pub enum ErrorKind {
269 Empty,
271 ExtraInput,
273 InvalidDeclaration,
275 InvalidRule,
277}
278
279impl std::fmt::Display for ParseError {
280 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
281 let what = match self.kind {
282 ErrorKind::Empty => "nothing to parse",
283 ErrorKind::ExtraInput => "unexpected input after the end",
284 ErrorKind::InvalidDeclaration => "invalid declaration",
285 ErrorKind::InvalidRule => "invalid rule",
286 };
287 write!(f, "{what} at bytes {}..{}", self.span.start, self.span.end)
288 }
289}
290
291impl std::error::Error for ParseError {}
292
293#[derive(Clone, Debug, PartialEq)]
295pub struct Stylesheet<'a, B = SimpleBlock<'a>> {
296 pub rules: Vec<Rule<'a, B>>,
297 pub errors: Vec<ParseError>,
298}
299
300impl<B> Default for Stylesheet<'_, B> {
301 fn default() -> Self {
302 Stylesheet {
303 rules: Vec::new(),
304 errors: Vec::new(),
305 }
306 }
307}
308
309#[derive(Clone, Debug, PartialEq, Default)]
311pub struct BlockContents<'a> {
312 pub items: Vec<Item<'a>>,
313 pub errors: Vec<ParseError>,
314}
315
316pub(crate) struct Values<'a> {
321 pub(crate) tokens: Tokenizer<'a>,
322 open: Vec<Open<'a>>,
323 buffer: Vec<ComponentValue<'a>>,
324}
325
326impl<'a> Values<'a> {
327 pub(crate) fn new(tokens: Tokenizer<'a>) -> Values<'a> {
328 Values {
329 tokens,
330 open: Vec::new(),
331 buffer: Vec::new(),
332 }
333 }
334}
335
336struct Open<'a> {
337 bracket: Option<Bracket>,
339 name: Cow<'a, str>,
340 start: usize,
341 at: usize,
343}
344
345pub(crate) fn take_tail<T>(buf: &mut Vec<T>, at: usize) -> Vec<T> {
348 if at > 0 {
349 return buf.split_off(at);
350 }
351 let mut tail = Vec::with_capacity(buf.len());
353 tail.append(buf);
354 tail
355}
356
357#[inline]
359fn opens<'a>(token: Token<'a>, start: usize, at: usize) -> Result<Open<'a>, Token<'a>> {
360 let (bracket, name) = match token {
361 Token::Function(name) => (None, name),
362 Token::LeftParen => (Some(Bracket::Paren), Cow::Borrowed("")),
363 Token::LeftBracket => (Some(Bracket::Square), Cow::Borrowed("")),
364 Token::LeftBrace => (Some(Bracket::Curly), Cow::Borrowed("")),
365 other => return Err(other),
366 };
367 Ok(Open {
368 bracket,
369 name,
370 start,
371 at,
372 })
373}
374
375impl<'a> Open<'a> {
376 fn closes(&self, token: &Token<'_>) -> bool {
377 matches!(
378 (self.bracket, token),
379 (None | Some(Bracket::Paren), Token::RightParen)
380 | (Some(Bracket::Square), Token::RightBracket)
381 | (Some(Bracket::Curly), Token::RightBrace)
382 )
383 }
384
385 fn finish(self, values: Vec<ComponentValue<'a>>, end: usize) -> ComponentValue<'a> {
386 let span = Span::new(self.start, end);
387 match self.bracket {
388 None => ComponentValue::Function(Function {
389 name: self.name,
390 arguments: values,
391 span,
392 }),
393 Some(bracket) => ComponentValue::Block(SimpleBlock {
394 bracket,
395 contents: values,
396 span,
397 }),
398 }
399 }
400}
401
402impl<'a> Iterator for Values<'a> {
403 type Item = ComponentValue<'a>;
404
405 fn next(&mut self) -> Option<ComponentValue<'a>> {
406 let (token, span) = self.tokens.next_token()?;
407 Some(self.whole(token, span))
408 }
409}
410
411impl<'a> Values<'a> {
412 #[inline]
415 pub(crate) fn whole(&mut self, token: Token<'a>, span: Span) -> ComponentValue<'a> {
416 match opens(token, span.start, 0) {
417 Ok(open) => self.open.push(open),
418 Err(token) => return ComponentValue::Token(token, span),
419 }
420 self.rest_of_open()
421 }
422
423 fn rest_of_open(&mut self) -> ComponentValue<'a> {
424 loop {
425 let Some((token, span)) = self.tokens.next_token() else {
426 let end = self.tokens.source().len();
428 loop {
429 let open = self.open.pop().unwrap();
430 let values = take_tail(&mut self.buffer, open.at);
431 let done = open.finish(values, end);
432 if self.open.is_empty() {
433 return done;
434 }
435 self.buffer.push(done);
436 }
437 };
438 if self.open.last().unwrap().closes(&token) {
439 let open = self.open.pop().unwrap();
440 let values = take_tail(&mut self.buffer, open.at);
441 let done = open.finish(values, span.end);
442 if self.open.is_empty() {
443 return done;
444 }
445 self.buffer.push(done);
446 continue;
447 }
448 if !matches!(
449 token,
450 Token::Function(_) | Token::LeftParen | Token::LeftBracket | Token::LeftBrace
451 ) {
452 self.buffer.push(ComponentValue::Token(token, span));
453 continue;
454 }
455 match opens(token, span.start, self.buffer.len()) {
456 Ok(open) => self.open.push(open),
457 Err(token) => self.buffer.push(ComponentValue::Token(token, span)),
458 }
459 }
460 }
461}
462
463trait Source<'a>: Iterator<Item = ComponentValue<'a>> {
466 fn rest(&self) -> Option<&[ComponentValue<'a>]> {
468 None
469 }
470}
471
472impl<'a> Source<'a> for Values<'a> {}
473
474impl<'a> Source<'a> for std::vec::IntoIter<ComponentValue<'a>> {
475 fn rest(&self) -> Option<&[ComponentValue<'a>]> {
476 Some(self.as_slice())
477 }
478}
479
480fn before_semicolon(values: &[ComponentValue<'_>], nested: bool) -> usize {
482 values
483 .iter()
484 .position(|v| v.is(&Token::Semicolon) || (nested && v.is(&Token::RightBrace)))
485 .unwrap_or(values.len())
486}
487
488struct Parser<'a, I> {
491 src: &'a str,
492 input: I,
493 back: Vec<ComponentValue<'a>>,
494 scratch: Vec<ComponentValue<'a>>,
496 errors: Vec<ParseError>,
497}
498
499fn text(src: &str) -> Parser<'_, Values<'_>> {
500 Parser::new(src, Values::new(Tokenizer::new(src)))
501}
502
503impl<'a, I: Source<'a>> Parser<'a, I> {
504 fn new(src: &'a str, input: I) -> Parser<'a, I> {
505 Parser {
506 src,
507 input,
508 back: Vec::new(),
509 scratch: Vec::new(),
510 errors: Vec::new(),
511 }
512 }
513
514 fn peek(&mut self) -> Option<&ComponentValue<'a>> {
515 if self.back.is_empty() {
516 if self.input.rest().is_some() {
517 return self.input.rest().and_then(<[_]>::first);
518 }
519 let next = self.input.next()?;
520 self.back.push(next);
521 }
522 self.back.last()
523 }
524
525 fn next(&mut self) -> Option<ComponentValue<'a>> {
526 self.back.pop().or_else(|| self.input.next())
527 }
528
529 fn put_back(&mut self, values: Vec<ComponentValue<'a>>) {
530 self.back.extend(values.into_iter().rev());
531 }
532
533 fn skip_whitespace(&mut self) {
534 while self.peek().is_some_and(ComponentValue::is_whitespace) {
535 self.next();
536 }
537 }
538
539 fn error(&mut self, kind: ErrorKind, start: usize, end: usize) {
540 self.errors.push(ParseError {
541 kind,
542 span: Span::new(start, end.max(start)),
543 });
544 }
545
546 fn rules(&mut self, cdo_cdc: bool) -> Vec<Rule<'a>> {
549 let mut rules = Vec::new();
550 while let Some(next) = self.peek() {
551 match next {
552 ComponentValue::Token(Token::Whitespace, _) => {
553 self.next();
554 }
555 ComponentValue::Token(Token::Cdo | Token::Cdc, _) if cdo_cdc => {
556 self.next();
557 }
558 ComponentValue::Token(Token::AtKeyword(_), _) => {
559 let rule = self.at_rule(false);
560 rules.push(Rule::At(rule));
561 }
562 _ => {
563 if let Some(rule) = self.qualified_rule(false, false) {
564 rules.push(Rule::Qualified(rule));
565 }
566 }
567 }
568 }
569 rules
570 }
571
572 fn at_rule(&mut self, nested: bool) -> AtRule<'a> {
575 let Some(ComponentValue::Token(Token::AtKeyword(name), span)) = self.next() else {
576 unreachable!("at_rule is called on an at-keyword");
577 };
578 let mut rule = AtRule {
579 name,
580 prelude: Vec::new(),
581 block: None,
582 span,
583 };
584 while let Some(next) = self.next() {
585 match next {
586 ComponentValue::Token(Token::Semicolon, _) => break,
587 ComponentValue::Token(Token::RightBrace, _) if nested => {
588 self.back.push(next);
589 break;
590 }
591 ComponentValue::Block(block) if block.bracket == Bracket::Curly => {
592 rule.span.end = block.span.end;
593 rule.block = Some(block);
594 break;
595 }
596 other => {
597 rule.span.end = other.span().end;
598 self.scratch.push(other);
599 }
600 }
601 }
602 rule.prelude = take_tail(&mut self.scratch, 0);
603 rule
604 }
605
606 fn qualified_rule(&mut self, stop: bool, nested: bool) -> Option<QualifiedRule<'a>> {
609 let end_of_input = self.src.len();
610 let start = self.peek().map_or(end_of_input, |v| v.span().start);
611 self.scratch.clear();
613 let mut end = start;
614 loop {
615 let Some(next) = self.next() else {
616 self.scratch.clear();
617 self.error(ErrorKind::InvalidRule, start, end);
618 return None;
619 };
620 match next {
621 ComponentValue::Token(Token::Semicolon, _) if stop => {
622 self.back.push(next);
623 self.scratch.clear();
624 self.error(ErrorKind::InvalidRule, start, end);
625 return None;
626 }
627 ComponentValue::Token(Token::RightBrace, _) if nested => {
628 self.back.push(next);
629 self.scratch.clear();
630 self.error(ErrorKind::InvalidRule, start, end);
631 return None;
632 }
633 ComponentValue::Block(block) if block.bracket == Bracket::Curly => {
634 let end = block.span.end;
635 let prelude = take_tail(&mut self.scratch, 0);
636 if looks_like_custom_property(&prelude) {
637 if nested {
640 self.bad_declaration_remnants(true);
641 }
642 self.error(ErrorKind::InvalidRule, start, end);
643 return None;
644 }
645 return Some(QualifiedRule {
646 prelude,
647 block,
648 span: Span::new(start, end),
649 });
650 }
651 other => {
652 end = other.span().end;
653 self.scratch.push(other);
654 }
655 }
656 }
657 }
658
659 fn bad_declaration_remnants(&mut self, nested: bool) {
660 while let Some(next) = self.next() {
661 match next {
662 ComponentValue::Token(Token::Semicolon, _) => return,
663 ComponentValue::Token(Token::RightBrace, _) if nested => {
664 self.back.push(next);
665 return;
666 }
667 _ => {}
668 }
669 }
670 }
671
672 fn up_to_semicolon(&mut self, nested: bool) -> Vec<ComponentValue<'a>> {
675 let mut values = Vec::new();
676 while let Some(next) = self.peek() {
677 if next.is(&Token::Semicolon) || (nested && next.is(&Token::RightBrace)) {
678 break;
679 }
680 values.push(self.next().unwrap());
681 }
682 values
683 }
684
685 fn declaration(&mut self, nested: bool) -> Result<Declaration<'a>, Vec<ComponentValue<'a>>> {
688 if self.back.is_empty()
690 && let Some(rest) = self.input.rest()
691 {
692 let n = before_semicolon(rest, nested);
693 if let Some(plan) = plan(&rest[..n]) {
694 let name = self.input.next().unwrap();
695 for _ in 1..plan.value_start {
698 self.input.next();
699 }
700 let value = self
701 .input
702 .by_ref()
703 .take(plan.value_end - plan.value_start)
704 .collect();
705 for _ in plan.value_end.max(plan.value_start)..n {
707 self.input.next();
708 }
709 return Ok(build(name, value, &plan, self.src));
710 }
711 return Err(self.input.by_ref().take(n).collect());
712 }
713 let values = self.up_to_semicolon(nested);
714 declaration_from(values, self.src)
715 }
716
717 fn block_contents(&mut self) -> Vec<Item<'a>> {
719 let mut items = Vec::new();
720 while let Some(next) = self.peek() {
721 match next {
722 ComponentValue::Token(Token::Whitespace | Token::Semicolon, _) => {
723 self.next();
724 }
725 ComponentValue::Token(Token::RightBrace, span) => {
728 let span = *span;
729 self.next();
730 self.error(ErrorKind::InvalidRule, span.start, span.end);
731 }
732 ComponentValue::Token(Token::AtKeyword(_), _) => {
733 let rule = self.at_rule(true);
734 items.push(Item::Rule(Rule::At(rule)));
735 }
736 ComponentValue::Token(Token::Ident(_), _) => match self.declaration(true) {
738 Ok(decl) => items.push(Item::Declaration(decl)),
739 Err(values) => {
740 self.put_back(values);
741 if let Some(rule) = self.qualified_rule(true, true) {
742 items.push(Item::Rule(Rule::Qualified(rule)));
743 }
744 }
745 },
746 _ => {
747 if let Some(rule) = self.qualified_rule(true, true) {
748 items.push(Item::Rule(Rule::Qualified(rule)));
749 }
750 }
751 }
752 }
753 items
754 }
755
756 fn declaration_list(&mut self) -> Vec<Item<'a>> {
759 let mut items = Vec::new();
760 while let Some(next) = self.peek() {
761 match next {
762 ComponentValue::Token(Token::Whitespace | Token::Semicolon, _) => {
763 self.next();
764 }
765 ComponentValue::Token(Token::AtKeyword(_), _) => {
766 let rule = self.at_rule(false);
767 items.push(Item::Rule(Rule::At(rule)));
768 }
769 _ => match self.declaration(false) {
770 Ok(decl) => items.push(Item::Declaration(decl)),
771 Err(values) => {
772 let start = values.first().map_or(0, |v| v.span().start);
773 let end = values.last().map_or(start, |v| v.span().end);
774 self.error(ErrorKind::InvalidDeclaration, start, end);
775 }
776 },
777 }
778 }
779 items
780 }
781
782 fn end<T>(&mut self, value: T) -> Result<T, ParseError> {
784 self.skip_whitespace();
785 match self.peek() {
786 None => Ok(value),
787 Some(v) => {
788 let start = v.span().start;
789 Err(ParseError {
790 kind: ErrorKind::ExtraInput,
791 span: Span::new(start, self.src.len()),
792 })
793 }
794 }
795 }
796
797 fn start(&mut self) -> Result<(), ParseError> {
798 self.skip_whitespace();
799 match self.peek() {
800 Some(_) => Ok(()),
801 None => Err(ParseError {
802 kind: ErrorKind::Empty,
803 span: Span::new(0, self.src.len()),
804 }),
805 }
806 }
807}
808
809pub(crate) fn looks_like_custom_property(prelude: &[ComponentValue<'_>]) -> bool {
811 let mut it = prelude.iter().filter(|v| !v.is_whitespace());
812 matches!(it.next(), Some(ComponentValue::Token(Token::Ident(n), _)) if n.starts_with("--"))
813 && it.next().is_some_and(|v| v.is(&Token::Colon))
814}
815
816struct Plan {
819 value_start: usize,
820 value_end: usize,
821 important: bool,
822 unicode_range: bool,
823 span: Span,
824}
825
826fn plan(values: &[ComponentValue<'_>]) -> Option<Plan> {
828 let Some(ComponentValue::Token(Token::Ident(name), first)) = values.first() else {
829 return None;
830 };
831 let mut colon = 1;
832 while values.get(colon).is_some_and(ComponentValue::is_whitespace) {
833 colon += 1;
834 }
835 let colon_end = match values.get(colon) {
836 Some(ComponentValue::Token(Token::Colon, span)) => span.end,
837 _ => return None,
838 };
839 let after = colon + 1;
840 let v = value_plan(name, &values[after..])?;
841 Some(Plan {
842 value_start: after + v.start,
843 value_end: after + v.end,
844 important: v.important,
845 unicode_range: name.eq_ignore_ascii_case("unicode-range"),
846 span: Span::new(first.start, v.last_end.unwrap_or(colon_end)),
847 })
848}
849
850pub(crate) struct ValuePlan {
852 pub(crate) start: usize,
853 pub(crate) end: usize,
854 pub(crate) important: bool,
855 pub(crate) last_end: Option<usize>,
858}
859
860pub(crate) fn value_plan(name: &str, values: &[ComponentValue<'_>]) -> Option<ValuePlan> {
863 let mut start = 0;
864 while values.get(start).is_some_and(ComponentValue::is_whitespace) {
865 start += 1;
866 }
867 let mut solid = (start..values.len())
869 .rev()
870 .filter(|&i| !values[i].is_whitespace());
871 let last = solid.next();
872 let before = solid.next();
873 let important = match (before, last) {
874 (Some(bang), Some(word))
875 if values[bang].is(&Token::Delim('!'))
876 && matches!(&values[word], ComponentValue::Token(Token::Ident(w), _)
877 if w.eq_ignore_ascii_case("important")) =>
878 {
879 Some(bang)
880 }
881 _ => None,
882 };
883 let mut end = important.unwrap_or(values.len());
884 while end > start && values[end - 1].is_whitespace() {
885 end -= 1;
886 }
887 if !name.starts_with("--") {
888 let value = &values[start..end];
890 if value.len() > 1 && value.iter().any(ComponentValue::is_curly) {
891 return None;
892 }
893 }
894 Some(ValuePlan {
895 start,
896 end,
897 important: important.is_some(),
898 last_end: last.map(|i| values[i].span().end),
899 })
900}
901
902fn build<'a>(
904 name: ComponentValue<'a>,
905 mut value: Vec<ComponentValue<'a>>,
906 plan: &Plan,
907 src: &'a str,
908) -> Declaration<'a> {
909 let ComponentValue::Token(Token::Ident(name), _) = name else {
910 unreachable!("a plan starts with an ident")
911 };
912 if plan.unicode_range && !value.is_empty() {
913 let from = value[0].span().start;
915 let to = value[value.len() - 1].span().end;
916 value = Values::new(unicode_range_tokens(src, from, to)).collect();
917 }
918 Declaration {
919 name,
920 value,
921 important: plan.important,
922 span: plan.span,
923 }
924}
925
926fn declaration_from<'a>(
928 mut values: Vec<ComponentValue<'a>>,
929 src: &'a str,
930) -> Result<Declaration<'a>, Vec<ComponentValue<'a>>> {
931 let Some(plan) = plan(&values) else {
932 return Err(values);
933 };
934 let blank = ComponentValue::Token(Token::Whitespace, Span::default());
935 let name = std::mem::replace(&mut values[0], blank);
936 values.truncate(plan.value_end);
938 values.drain(..plan.value_start);
939 Ok(build(name, values, &plan, src))
940}
941
942pub(crate) fn unicode_range_tokens(src: &str, from: usize, to: usize) -> Tokenizer<'_> {
945 let mut t = Tokenizer::with_unicode_ranges(&src[..to]);
946 t.reset(from);
947 t
948}
949
950pub fn parse_stylesheet(css: &str) -> Stylesheet<'_> {
959 let mut p = text(css);
960 let rules = p.rules(true);
961 Stylesheet {
962 rules,
963 errors: p.errors,
964 }
965}
966
967pub fn parse_rule_list(css: &str) -> Stylesheet<'_> {
971 let mut p = text(css);
972 let rules = p.rules(false);
973 Stylesheet {
974 rules,
975 errors: p.errors,
976 }
977}
978
979pub fn parse_block_contents(css: &str) -> BlockContents<'_> {
991 let mut p = text(css);
992 let items = p.block_contents();
993 BlockContents {
994 items,
995 errors: p.errors,
996 }
997}
998
999pub fn parse_declaration_list(css: &str) -> BlockContents<'_> {
1003 let mut p = text(css);
1004 let items = p.declaration_list();
1005 BlockContents {
1006 items,
1007 errors: p.errors,
1008 }
1009}
1010
1011pub fn parse_rule(css: &str) -> Result<Rule<'_>, ParseError> {
1013 let mut p = text(css);
1014 p.start()?;
1015 let rule = if matches!(
1016 p.peek(),
1017 Some(ComponentValue::Token(Token::AtKeyword(_), _))
1018 ) {
1019 Rule::At(p.at_rule(false))
1020 } else {
1021 match p.qualified_rule(false, false) {
1022 Some(rule) => Rule::Qualified(rule),
1023 None => return Err(p.errors.pop().unwrap()),
1024 }
1025 };
1026 p.end(rule)
1027}
1028
1029pub fn parse_declaration(css: &str) -> Result<Declaration<'_>, ParseError> {
1031 let mut p = text(css);
1032 p.start()?;
1033 match p.declaration(false) {
1034 Ok(decl) => p.end(decl),
1035 Err(values) => {
1036 let start = values.first().map_or(0, |v| v.span().start);
1037 Err(ParseError {
1038 kind: ErrorKind::InvalidDeclaration,
1039 span: Span::new(start, css.len()),
1040 })
1041 }
1042 }
1043}
1044
1045pub fn parse_component_value(css: &str) -> Result<ComponentValue<'_>, ParseError> {
1047 let mut p = text(css);
1048 p.start()?;
1049 let value = p.next().unwrap();
1050 p.end(value)
1051}
1052
1053pub fn parse_component_values(css: &str) -> Vec<ComponentValue<'_>> {
1056 Values::new(Tokenizer::new(css)).collect()
1057}
1058
1059pub fn parse_comma_separated(css: &str) -> Vec<Vec<ComponentValue<'_>>> {
1062 let mut values = Values::new(Tokenizer::new(css)).peekable();
1063 let mut groups = Vec::new();
1064 while values.peek().is_some() {
1065 let mut group = Vec::new();
1066 for v in values.by_ref() {
1067 if v.is(&Token::Comma) {
1068 break;
1069 }
1070 group.push(v);
1071 }
1072 groups.push(group);
1073 }
1074 groups
1075}
1076
1077pub fn parse_unicode_range_value(css: &str) -> Vec<ComponentValue<'_>> {
1080 Values::new(Tokenizer::with_unicode_ranges(css)).collect()
1081}
1082
1083#[cfg(test)]
1084mod tests {
1085 use super::*;
1086
1087 #[test]
1088 fn deep_nesting_parses_and_drops() {
1089 let css = "(".repeat(1_000_000);
1090 let values = parse_component_values(&css);
1091 assert_eq!(values.len(), 1);
1092 drop(values);
1093 let css = format!("a{{b:{}}}", "[".repeat(200_000));
1094 let sheet = parse_stylesheet(&css);
1095 let Rule::Qualified(rule) = sheet.rules.into_iter().next().unwrap() else {
1096 panic!()
1097 };
1098 assert_eq!(rule.block.contents(&css).items.len(), 1);
1099 }
1100
1101 #[test]
1102 fn spans_cover_rules_and_declarations() {
1103 let css = "a { color: red !important; } @x y;";
1104 let sheet = parse_stylesheet(css);
1105 assert_eq!(
1106 sheet.rules[0].span().text(css),
1107 "a { color: red !important; }"
1108 );
1109 assert_eq!(
1110 sheet.rules[1].span().text(css),
1111 "@x y;".trim_end_matches(';')
1112 );
1113 let Rule::Qualified(rule) = sheet.rules.into_iter().next().unwrap() else {
1114 panic!()
1115 };
1116 let Item::Declaration(d) = &rule.block.contents(css).items[0] else {
1117 panic!()
1118 };
1119 assert_eq!(d.span.text(css), "color: red !important");
1120 assert_eq!(d.original_text(css), "red");
1121 assert!(d.important);
1122 }
1123
1124 #[test]
1125 fn block_contents_parsed_later_match_parsing_at_once() {
1126 let css = "color: red; &:hover { b: c } --x: {a} b; d:e{f}; @media x { g: h }";
1127 let at_once = parse_block_contents(css);
1128 let wrapped = format!("{{{css}}}");
1129 let Ok(ComponentValue::Block(block)) = parse_component_value(&wrapped) else {
1130 panic!()
1131 };
1132 let later = block.contents(&wrapped);
1133 assert_eq!(at_once.items.len(), later.items.len());
1134 assert_eq!(at_once.errors.len(), later.errors.len());
1135 }
1136
1137 #[test]
1138 fn unicode_range_descriptor_gets_range_tokens() {
1139 let d = parse_declaration("unicode-range: U+0-7F, u+4??").unwrap();
1140 let ranges: Vec<_> = d
1141 .value
1142 .iter()
1143 .filter_map(|v| match v.token() {
1144 Some(Token::UnicodeRange { start, end }) => Some((*start, *end)),
1145 _ => None,
1146 })
1147 .collect();
1148 assert_eq!(ranges, [(0, 0x7f), (0x400, 0x4ff)]);
1149 }
1150}