Skip to main content

css_parse/syntax/
simple_block.rs

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