Skip to main content

css_parse/syntax/
simple_block.rs

1use crate::{
2	CursorSink, KindSet, Parse, Parser, Peek, Result as ParserResult, SemanticEq, Span, T, ToCursors, ToSpan,
3	syntax::ComponentValues,
4};
5use csskit_proc_macro::node;
6
7#[node]
8#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
9#[cfg_attr(feature = "serde", derive(serde::Serialize), serde())]
10pub struct SimpleBlock<'a> {
11	pub open: T![PairWiseStart],
12	pub values: ComponentValues<'a>,
13	pub close: Option<T![PairWiseEnd]>,
14}
15
16impl<'a> Peek<'a> for SimpleBlock<'a> {
17	const PEEK_KINDSET: KindSet = KindSet::PAIRWISE_START;
18}
19
20// https://drafts.csswg.org/css-syntax-3/#consume-a-simple-block
21impl<'a> Parse<'a> for SimpleBlock<'a> {
22	fn parse<Iter>(p: &mut Parser<'a, Iter>) -> ParserResult<Self>
23	where
24		Iter: Iterator<Item = crate::Cursor> + Clone,
25	{
26		let open = p.parse::<T![PairWiseStart]>()?;
27		let stop = p.set_stop(KindSet::new(&[open.end()]));
28		let values = p.parse::<ComponentValues>();
29		p.set_stop(stop);
30		let values = values?;
31		if <T![PairWiseEnd]>::peek(p, p.peek_n(1)) {
32			return Ok(Self { open, values, close: p.parse::<T![PairWiseEnd]>().ok() });
33		}
34		Ok(Self { open, values, close: None })
35	}
36}
37
38impl<'a> ToCursors for SimpleBlock<'a> {
39	fn to_cursors(&self, s: &mut impl CursorSink) {
40		ToCursors::to_cursors(&self.open, s);
41		ToCursors::to_cursors(&self.values, s);
42		ToCursors::to_cursors(&self.close, s);
43	}
44}
45
46impl<'a> ToSpan for SimpleBlock<'a> {
47	fn to_span(&self) -> Span {
48		self.open.to_span() + if let Some(close) = self.close { close.to_span() } else { self.values.to_span() }
49	}
50}
51
52impl<'a> SemanticEq for SimpleBlock<'a> {
53	fn semantic_eq(&self, other: &Self) -> bool {
54		self.open.semantic_eq(&other.open)
55			&& self.values.semantic_eq(&other.values)
56			&& self.close.semantic_eq(&other.close)
57	}
58}
59
60#[cfg(test)]
61mod tests {
62	use super::*;
63	use crate::EmptyAtomSet;
64	use crate::test_helpers::*;
65
66	#[test]
67	fn test_writes() {
68		assert_parse!(EmptyAtomSet::ATOMS, SimpleBlock, "[foo]");
69		assert_parse!(EmptyAtomSet::ATOMS, SimpleBlock, "(one two three)");
70		assert_parse!(EmptyAtomSet::ATOMS, SimpleBlock, "{}");
71		assert_parse!(EmptyAtomSet::ATOMS, SimpleBlock, "{foo}");
72		assert_parse!(EmptyAtomSet::ATOMS, SimpleBlock, "{foo:bar}");
73		assert_parse!(EmptyAtomSet::ATOMS, SimpleBlock, "{one(two)}");
74		assert_parse!(EmptyAtomSet::ATOMS, SimpleBlock, "(one(two))");
75		// Incomplete but recoverable
76		assert_parse!(EmptyAtomSet::ATOMS, SimpleBlock, "[foo");
77		assert_parse!(EmptyAtomSet::ATOMS, SimpleBlock, "{foo:bar");
78		assert_parse!(EmptyAtomSet::ATOMS, SimpleBlock, "(one(two)");
79		// assert_parse!(EmptyAtomSet::ATOMS, SimpleBlock, "(one(two");
80	}
81
82	#[test]
83	fn test_peek() {
84		assert_peek_false!(EmptyAtomSet::ATOMS, SimpleBlock, "foo");
85		assert_peek_false!(EmptyAtomSet::ATOMS, SimpleBlock, "");
86	}
87}