Skip to main content

css_parse/syntax/
declaration.rs

1use crate::{
2	BangImportant, Cursor, CursorSink, DeclarationValue, Kind, KindSet, NodeMetadata, NodeWithMetadata, Parse, Parser,
3	Peek, Result, SemanticEq, Span, T, ToCursors, ToSpan, token_macros,
4};
5use csskit_proc_macro::node;
6use std::marker::PhantomData;
7
8/// This is a generic type that can be used for AST nodes representing a [Declaration][1], aka "property". This is
9/// defined as:
10///
11/// ```md
12/// <property-id>
13///  │├─ <ident> ─┤│
14///
15/// <declaration>
16///  │├─ <property-id> ─ ":" ─ <V> ──╮─────────────────────────────╭──╮───────╭┤│
17///                                  ╰─ "!" ─ <ident "important"> ─╯  ╰─ ";" ─╯
18/// ```
19///
20/// An ident is parsed first, as the property name, followed by a `:`. After this the given `<V>` will be parsed as the
21/// style value. Parsing may continue to a `!important`, or the optional trailing semi `;`, if either are present.
22///
23/// The grammar of `<V>` isn't defined here - it'll be dependant on the property name. Consequently, `<V>` must
24/// implement the [DeclarationValue] trait, which must provide the
25/// `parse_declaration_value(&mut Parser<'a>, Cursor) -> Result<Self>` method - the [Cursor] given to said method
26/// represents the Ident of the property name, so it can be reasoned about in order to dispatch to the right
27/// declaration value parsing step.
28///
29/// [1]: https://drafts.csswg.org/css-syntax-3/#consume-a-declaration
30#[node]
31#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
32#[cfg_attr(feature = "serde", derive(serde::Serialize), serde())]
33pub struct Declaration<'a, V, M>
34where
35	V: DeclarationValue<'a, M>,
36	M: NodeMetadata,
37{
38	pub name: token_macros::Ident,
39	pub colon: token_macros::Colon,
40	pub value: V,
41	pub important: Option<BangImportant>,
42	pub semicolon: Option<token_macros::Semicolon>,
43	#[cfg_attr(feature = "serde", serde(skip))]
44	_phantom: PhantomData<&'a M>,
45}
46
47impl<'a, V, M> Declaration<'a, V, M>
48where
49	V: DeclarationValue<'a, M>,
50	M: NodeMetadata,
51{
52	pub fn is_unknown(&self) -> bool {
53		self.value.is_unknown()
54	}
55}
56
57impl<'a, V, M> NodeWithMetadata<M> for Declaration<'a, V, M>
58where
59	V: DeclarationValue<'a, M>,
60	M: NodeMetadata,
61{
62	fn self_metadata(&self) -> M {
63		// Declaration's self_metadata should return the declaration-specific metadata
64		// (includes !important, property info, etc.) for selector matching.
65		DeclarationValue::declaration_metadata(self)
66	}
67
68	fn metadata(&self) -> M {
69		DeclarationValue::declaration_metadata(self)
70	}
71}
72
73impl<'a, V, M> Peek<'a> for Declaration<'a, V, M>
74where
75	V: DeclarationValue<'a, M>,
76	M: NodeMetadata,
77{
78	const PEEK_KINDSET: KindSet = KindSet::new(&[Kind::Ident]);
79
80	#[inline(always)]
81	fn peek<Iter>(p: &Parser<'a, Iter>, c: Cursor) -> bool
82	where
83		Iter: Iterator<Item = crate::Cursor> + Clone,
84	{
85		// A declaration must be an Ident followed by a Colon (with any number of whitespace inbetween). If that is not the
86		// case then it definitely cannot be parsed as a Declaration.
87		//
88		// https://drafts.csswg.org/css-syntax-3/#consume-a-blocks-contents
89		// ... "If the next non-whitespace token isn’t a <colon-token>, you can similarly immediately stop parsing as a
90		// declaration." ... "(That is, font+ ... is guaranteed to not be a property"...
91		if c != Kind::Ident || p.peek_n(2) != Kind::Colon {
92			return false;
93		}
94
95		// https://drafts.csswg.org/css-syntax-3/#consume-a-blocks-contents
96		// ... "If the first two non-whitespace tokens are a custom property name and a colon, it’s definitely a custom
97		// property and won’t ever produce a valid rule" ... "(That is, --foo:hover {...} is guaranteed to be a custom
98		// property, not a rule.)".
99		if c.token().is_dashed_ident() {
100			return true;
101		}
102
103		// If the third token is a `Colon` then it's likely a Pseudo Element selector. Colons are not valid value tokens
104		// inside of a declaration at current, however this is _technically_ a non-standard affordance that may be removed
105		// in future.
106		if p.peek_n(3) == Kind::Colon {
107			return false;
108		}
109
110		// https://drafts.csswg.org/css-syntax-3/#consume-a-blocks-contents
111		// ... "If the first three non-whitespace tokens are a valid property name, a colon, and anything other than a
112		// <{-token>, and then while parsing the declaration's value you encounter a <{-token>, you can immediately stop
113		// parsing as a declaration and reparse as a rule instead.
114		// (That is, font:bar {... is guaranteed to be an invalid property.)"
115		if p.peek_n(4) == Kind::LeftCurly || p.peek_n(5) == Kind::LeftCurly {
116			return false;
117		}
118
119		// All early checks have been exhausted, so the next step is to parse the Declaration to see if it is valid.
120		true
121	}
122}
123
124impl<'a, V, M> Parse<'a> for Declaration<'a, V, M>
125where
126	V: DeclarationValue<'a, M>,
127	M: NodeMetadata,
128{
129	fn parse<Iter>(p: &mut Parser<'a, Iter>) -> Result<Self>
130	where
131		Iter: Iterator<Item = crate::Cursor> + Clone,
132	{
133		let name = p.parse::<T![Ident]>()?;
134		let colon = p.parse::<T![:]>()?;
135		let c: Cursor = name.into();
136		let value = <V>::parse_declaration_value(p, c)?;
137		let important = p.parse_if_peek::<BangImportant>()?;
138		let semicolon = p.parse_if_peek::<T![;]>()?;
139		Ok(Self { name, colon, value, important, semicolon, _phantom: PhantomData })
140	}
141}
142
143impl<'a, V, M> ToCursors for Declaration<'a, V, M>
144where
145	V: DeclarationValue<'a, M> + ToCursors,
146	M: NodeMetadata,
147{
148	fn to_cursors(&self, s: &mut impl CursorSink) {
149		ToCursors::to_cursors(&self.name, s);
150		ToCursors::to_cursors(&self.colon, s);
151		ToCursors::to_cursors(&self.value, s);
152		ToCursors::to_cursors(&self.important, s);
153		ToCursors::to_cursors(&self.semicolon, s);
154	}
155}
156
157impl<'a, V, M> ToSpan for Declaration<'a, V, M>
158where
159	V: DeclarationValue<'a, M> + ToSpan,
160	M: NodeMetadata,
161{
162	fn to_span(&self) -> Span {
163		self.name.to_span() + self.value.to_span() + self.important.to_span() + self.semicolon.to_span()
164	}
165}
166
167impl<'a, V, M> SemanticEq for Declaration<'a, V, M>
168where
169	V: DeclarationValue<'a, M>,
170	M: NodeMetadata,
171{
172	fn semantic_eq(&self, other: &Self) -> bool {
173		// Semicolon is not semantically relevant!
174		self.name.semantic_eq(&other.name)
175			&& self.value.semantic_eq(&other.value)
176			&& self.important.semantic_eq(&other.important)
177	}
178}
179
180#[cfg(test)]
181mod tests {
182	use super::*;
183	use crate::EmptyAtomSet;
184	use crate::SemanticEq;
185	use crate::test_helpers::*;
186
187	#[derive(Debug)]
188	struct Decl(T![Ident]);
189
190	impl<M: NodeMetadata> NodeWithMetadata<M> for Decl {
191		fn metadata(&self) -> M {
192			M::default()
193		}
194	}
195
196	impl<'a, M: NodeMetadata> DeclarationValue<'a, M> for Decl {
197		fn is_initial(&self) -> bool {
198			false
199		}
200
201		fn is_inherit(&self) -> bool {
202			false
203		}
204
205		fn is_unset(&self) -> bool {
206			false
207		}
208
209		fn is_revert(&self) -> bool {
210			false
211		}
212
213		fn is_revert_layer(&self) -> bool {
214			false
215		}
216
217		fn needs_computing(&self) -> bool {
218			false
219		}
220
221		fn parse_specified_declaration_value<Iter>(p: &mut Parser<'a, Iter>, _name: Cursor) -> Result<Self>
222		where
223			Iter: Iterator<Item = crate::Cursor> + Clone,
224		{
225			p.parse::<T![Ident]>().map(Self)
226		}
227	}
228
229	impl ToCursors for Decl {
230		fn to_cursors(&self, s: &mut impl CursorSink) {
231			s.append(self.0.into())
232		}
233	}
234
235	impl ToSpan for Decl {
236		fn to_span(&self) -> Span {
237			self.0.to_span()
238		}
239	}
240
241	impl SemanticEq for Decl {
242		fn semantic_eq(&self, other: &Self) -> bool {
243			self.0.semantic_eq(&other.0)
244		}
245	}
246
247	#[test]
248	fn test_writes() {
249		assert_parse!(EmptyAtomSet::ATOMS, Declaration<Decl, ()>, "color:black;");
250	}
251}