Skip to main content

css_parse/syntax/
component_value.rs

1use crate::{
2	AssociatedWhitespaceRules, Cursor, CursorSink, Diagnostic, FunctionBlock, Kind, KindSet, Parse, Parser, Peek,
3	Result as ParserResult, SemanticEq, SimpleBlock, Span, State, T, ToCursors, ToSpan,
4};
5
6/// <https://drafts.csswg.org/css-syntax-3/#consume-component-value>
7///
8/// A compatible "Token" per CSS grammar, subsetted to the tokens possibly
9/// rendered by ComponentValue (so no pairwise, function tokens, etc).
10#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
11#[cfg_attr(feature = "serde", derive(serde::Serialize), serde(untagged))]
12pub enum ComponentValue<'a> {
13	SimpleBlock(SimpleBlock<'a>),
14	Function(FunctionBlock<'a>),
15	Whitespace(T![Whitespace]),
16	Number(T![Number]),
17	Dimension(T![Dimension]),
18	Ident(T![Ident]),
19	AtKeyword(T![AtKeyword]),
20	Hash(T![Hash]),
21	String(T![String]),
22	Url(T![Url]),
23	Delim(T![Delim]),
24	Colon(T![:]),
25	Semicolon(T![;]),
26	Comma(T![,]),
27}
28
29impl<'a> Peek<'a> for ComponentValue<'a> {
30	fn peek<Iter>(_: &Parser<'a, Iter>, c: Cursor) -> bool
31	where
32		Iter: Iterator<Item = Cursor> + Clone,
33	{
34		let kindset = KindSet::new(&[
35			Kind::Whitespace,
36			Kind::Number,
37			Kind::Dimension,
38			Kind::Ident,
39			Kind::AtKeyword,
40			Kind::Hash,
41			Kind::String,
42			Kind::Url,
43			Kind::Delim,
44			Kind::Colon,
45			Kind::Semicolon,
46			Kind::Comma,
47			Kind::Function,
48			Kind::LeftCurly,
49			Kind::LeftParen,
50			Kind::LeftSquare,
51		]);
52		c == kindset
53	}
54}
55
56// https://drafts.csswg.org/css-syntax-3/#consume-component-value
57impl<'a> Parse<'a> for ComponentValue<'a> {
58	fn parse<Iter>(p: &mut Parser<'a, Iter>) -> ParserResult<Self>
59	where
60		Iter: Iterator<Item = Cursor> + Clone,
61	{
62		let c = p.peek_n(1);
63		Ok(if <T![' ']>::peek(p, c) {
64			Self::Whitespace(p.parse::<T![' ']>()?)
65		} else if <T![PairWiseStart]>::peek(p, c) {
66			let old_state = p.set_state(State::Nested);
67			let block = p.parse::<SimpleBlock>();
68			p.set_state(old_state);
69			Self::SimpleBlock(block?)
70		} else if <T![Function]>::peek(p, c) {
71			Self::Function(p.parse::<FunctionBlock>()?)
72		} else if <T![Number]>::peek(p, c) {
73			Self::Number(p.parse::<T![Number]>()?)
74		} else if <T![Dimension]>::peek(p, c) {
75			Self::Dimension(p.parse::<T![Dimension]>()?)
76		} else if <T![Ident]>::peek(p, c) {
77			Self::Ident(p.parse::<T![Ident]>()?)
78		} else if <T![AtKeyword]>::peek(p, c) {
79			Self::AtKeyword(p.parse::<T![AtKeyword]>()?)
80		} else if <T![Hash]>::peek(p, c) {
81			Self::Hash(p.parse::<T![Hash]>()?)
82		} else if <T![String]>::peek(p, c) {
83			Self::String(p.parse::<T![String]>()?)
84		} else if <T![Url]>::peek(p, c) {
85			Self::Url(p.parse::<T![Url]>()?)
86		} else if <T![Delim]>::peek(p, c) {
87			p.parse::<T![Delim]>().map(|delim| {
88				// Carefully handle Whitespace rules to ensure whitespace isn't lost when re-serializing
89				let mut rules = AssociatedWhitespaceRules::none();
90				if p.peek_n_with_skip(1, KindSet::COMMENTS) == Kind::Whitespace {
91					rules |= AssociatedWhitespaceRules::EnforceAfter;
92				} else {
93					rules |= AssociatedWhitespaceRules::BanAfter;
94				}
95				Self::Delim(delim.with_associated_whitespace(rules))
96			})?
97		} else if <T![:]>::peek(p, c) {
98			Self::Colon(p.parse::<T![:]>()?)
99		} else if <T![;]>::peek(p, c) {
100			Self::Semicolon(p.parse::<T![;]>()?)
101		} else if <T![,]>::peek(p, c) {
102			Self::Comma(p.parse::<T![,]>()?)
103		} else {
104			Err(Diagnostic::new(p.next(), Diagnostic::unexpected))?
105		})
106	}
107}
108
109impl<'a> ToCursors for ComponentValue<'a> {
110	fn to_cursors(&self, s: &mut impl CursorSink) {
111		match self {
112			Self::SimpleBlock(t) => ToCursors::to_cursors(t, s),
113			Self::Function(t) => ToCursors::to_cursors(t, s),
114			Self::Ident(t) => ToCursors::to_cursors(t, s),
115			Self::AtKeyword(t) => ToCursors::to_cursors(t, s),
116			Self::Hash(t) => ToCursors::to_cursors(t, s),
117			Self::String(t) => ToCursors::to_cursors(t, s),
118			Self::Url(t) => ToCursors::to_cursors(t, s),
119			Self::Delim(t) => ToCursors::to_cursors(t, s),
120			Self::Number(t) => ToCursors::to_cursors(t, s),
121			Self::Dimension(t) => ToCursors::to_cursors(t, s),
122			Self::Whitespace(t) => ToCursors::to_cursors(t, s),
123			Self::Colon(t) => ToCursors::to_cursors(t, s),
124			Self::Semicolon(t) => ToCursors::to_cursors(t, s),
125			Self::Comma(t) => ToCursors::to_cursors(t, s),
126		}
127	}
128}
129
130impl<'a> ToSpan for ComponentValue<'a> {
131	fn to_span(&self) -> Span {
132		match self {
133			Self::SimpleBlock(t) => t.to_span(),
134			Self::Function(t) => t.to_span(),
135			Self::Ident(t) => t.to_span(),
136			Self::AtKeyword(t) => t.to_span(),
137			Self::Hash(t) => t.to_span(),
138			Self::String(t) => t.to_span(),
139			Self::Url(t) => t.to_span(),
140			Self::Delim(t) => t.to_span(),
141			Self::Number(t) => t.to_span(),
142			Self::Dimension(t) => t.to_span(),
143			Self::Whitespace(t) => t.to_span(),
144			Self::Colon(t) => t.to_span(),
145			Self::Semicolon(t) => t.to_span(),
146			Self::Comma(t) => t.to_span(),
147		}
148	}
149}
150
151impl<'a> SemanticEq for ComponentValue<'a> {
152	fn semantic_eq(&self, other: &Self) -> bool {
153		match (self, other) {
154			(Self::SimpleBlock(a), Self::SimpleBlock(b)) => a.semantic_eq(b),
155			(Self::Function(a), Self::Function(b)) => a.semantic_eq(b),
156			(Self::Number(a), Self::Number(b)) => a.semantic_eq(b),
157			(Self::Dimension(a), Self::Dimension(b)) => a.semantic_eq(b),
158			(Self::Ident(a), Self::Ident(b)) => a.semantic_eq(b),
159			(Self::AtKeyword(a), Self::AtKeyword(b)) => a.semantic_eq(b),
160			(Self::Hash(a), Self::Hash(b)) => a.semantic_eq(b),
161			(Self::String(a), Self::String(b)) => a.semantic_eq(b),
162			(Self::Url(a), Self::Url(b)) => a.semantic_eq(b),
163			(Self::Delim(a), Self::Delim(b)) => a.semantic_eq(b),
164			(Self::Colon(a), Self::Colon(b)) => a.semantic_eq(b),
165			(Self::Semicolon(a), Self::Semicolon(b)) => a.semantic_eq(b),
166			(Self::Comma(a), Self::Comma(b)) => a.semantic_eq(b),
167			// Whitespace has no semantic relevance, other than its presence, so it should always be true
168			(Self::Whitespace(_), Self::Whitespace(_)) => true,
169			_ => false, // Different variants are never equal
170		}
171	}
172}
173
174#[cfg(test)]
175mod tests {
176	use super::*;
177	use crate::{EmptyAtomSet, test_helpers::*};
178
179	#[test]
180	fn size_test() {
181		assert_eq!(std::mem::size_of::<ComponentValue>(), 64);
182	}
183
184	#[test]
185	fn test_writes() {
186		assert_parse!(EmptyAtomSet::ATOMS, ComponentValue, "foo");
187		assert_parse!(EmptyAtomSet::ATOMS, ComponentValue, " ");
188		assert_parse!(EmptyAtomSet::ATOMS, ComponentValue, "{block}");
189	}
190}