style/properties_and_values/
rule.rs1use super::{
10 registry::PropertyRegistration,
11 value::{
12 AllowComputationallyDependent, ComputedValue as ComputedRegisteredValue,
13 SpecifiedValue as SpecifiedRegisteredValue,
14 },
15};
16use crate::custom_properties::{Name as CustomPropertyName, SpecifiedValue};
17use crate::derives::*;
18use crate::error_reporting::ContextualParseError;
19use crate::parser::{Parse, ParserContext};
20use crate::properties::PropertyIdRef;
21use crate::shared_lock::{SharedRwLockReadGuard, ToCssWithGuard};
22use crate::values::{computed, serialize_atom_name};
23use cssparser::{BasicParseErrorKind, ParseErrorKind, Parser, RuleBodyParser, SourceLocation};
24use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
25use servo_arc::Arc;
26use std::fmt::{self, Write};
27use style_traits::{
28 CssStringWriter, CssWriter, ParseError, PropertyInheritsParseError, PropertySyntaxParseError,
29 StyleParseErrorKind, ToCss,
30};
31use to_shmem::{SharedMemoryBuilder, ToShmem};
32
33pub use super::syntax::Descriptor as SyntaxDescriptor;
34pub use crate::properties::property::{DescriptorId, DescriptorParser, Descriptors};
35
36pub fn parse_property_block(
41 context: &ParserContext,
42 input: &mut Parser,
43 name: PropertyRuleName,
44 source_location: SourceLocation,
45) -> Result<PropertyRegistration, ParseError> {
46 let mut descriptors = Descriptors::default();
47 let mut parser = DescriptorParser {
48 context,
49 descriptors: &mut descriptors,
50 };
51 let iter = RuleBodyParser::new(input, &mut parser);
52 let mut syntax_err = None;
53 let mut inherits_err = None;
54 for declaration in iter {
55 if !context.error_reporting_enabled() {
56 continue;
57 }
58 if let Err((error, slice, location)) = declaration {
59 let error = match error.kind {
60 ParseErrorKind::Custom(StyleParseErrorKind::PropertySyntaxField(_)) => {
64 syntax_err = Some(error.clone());
65 ContextualParseError::UnsupportedValue(slice, error)
66 },
67
68 ParseErrorKind::Custom(StyleParseErrorKind::PropertyInheritsField(_)) => {
71 inherits_err = Some(error.clone());
72 ContextualParseError::UnsupportedValue(slice, error)
73 },
74
75 _ => ContextualParseError::UnsupportedPropertyDescriptor(slice, error),
78 };
79 context.log_css_error(location, error);
80 }
81 }
82
83 let Some(ref syntax) = descriptors.syntax else {
88 return Err(if let Some(err) = syntax_err {
89 err
90 } else {
91 let err = ParseError::custom(StyleParseErrorKind::PropertySyntaxField(
92 PropertySyntaxParseError::NoSyntax,
93 ));
94 context.log_css_error(
95 source_location,
96 ContextualParseError::UnsupportedValue("", err.clone()),
97 );
98 err
99 });
100 };
101
102 if descriptors.inherits.is_none() {
107 return Err(if let Some(err) = inherits_err {
108 err
109 } else {
110 let err = ParseError::custom(StyleParseErrorKind::PropertyInheritsField(
111 PropertyInheritsParseError::NoInherits,
112 ));
113 context.log_css_error(
114 source_location,
115 ContextualParseError::UnsupportedValue("", err.clone()),
116 );
117 err
118 });
119 };
120
121 if PropertyRegistration::validate_initial_value(
122 PropertyIdRef::from(&name.0),
123 syntax,
124 descriptors.initial_value.as_deref(),
125 )
126 .is_err()
127 {
128 return Err(ParseError::from_basic_kind(
129 BasicParseErrorKind::AtRuleBodyInvalid,
130 ));
131 }
132
133 Ok(PropertyRegistration {
134 name,
135 descriptors,
136 url_data: context.url_data.clone(),
137 source_location,
138 })
139}
140
141#[allow(missing_docs)]
143pub enum PropertyRegistrationError {
144 NoInitialValue,
145 InvalidInitialValue,
146 InitialValueNotComputationallyIndependent,
147}
148
149impl PropertyRegistration {
150 pub fn size_of(&self, _: &SharedRwLockReadGuard, ops: &mut MallocSizeOfOps) -> usize {
152 MallocSizeOf::size_of(self, ops)
153 }
154
155 pub fn compute_initial_value(
157 &self,
158 computed_context: &computed::Context,
159 ) -> Result<ComputedRegisteredValue, ()> {
160 let Some(ref initial) = self.descriptors.initial_value else {
161 return Err(());
162 };
163
164 if self.descriptors.is_universal() {
165 return Ok(ComputedRegisteredValue::universal(Arc::clone(initial)));
166 }
167
168 let mut input = Parser::new(initial.css_text());
169 input.skip_whitespace();
170
171 match SpecifiedRegisteredValue::compute(
172 &mut input,
173 &self.descriptors,
174 &self.url_data,
175 computed_context,
176 AllowComputationallyDependent::No,
177 Default::default(),
178 Some(PropertyIdRef::Custom(&self.name.0)),
179 ) {
180 Ok(computed) => Ok(computed),
181 Err(_) => Err(()),
182 }
183 }
184
185 pub fn validate_initial_value(
188 property_id: PropertyIdRef,
189 syntax: &SyntaxDescriptor,
190 initial_value: Option<&SpecifiedValue>,
191 ) -> Result<(), PropertyRegistrationError> {
192 use crate::properties::CSSWideKeyword;
193 if syntax.is_universal() && initial_value.is_none() {
197 return Ok(());
198 }
199
200 let Some(initial) = initial_value else {
205 return Err(PropertyRegistrationError::NoInitialValue);
206 };
207
208 if initial.has_references() {
211 return Err(PropertyRegistrationError::InitialValueNotComputationallyIndependent);
212 }
213
214 let mut input = Parser::new(initial.css_text());
215 input.skip_whitespace();
216
217 if input.try_parse(CSSWideKeyword::parse).is_ok() {
219 return Err(PropertyRegistrationError::InitialValueNotComputationallyIndependent);
220 }
221
222 match SpecifiedRegisteredValue::parse(
223 &mut input,
224 syntax,
225 &initial.url_data,
226 AllowComputationallyDependent::No,
227 Default::default(),
228 Some(property_id),
229 ) {
230 Ok(_) => {},
231 Err(_) => return Err(PropertyRegistrationError::InvalidInitialValue),
232 }
233
234 Ok(())
235 }
236}
237
238impl ToCssWithGuard for PropertyRegistration {
239 fn to_css(&self, _guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result {
241 dest.write_str("@property ")?;
242 self.name.to_css(&mut CssWriter::new(dest))?;
243 dest.write_str(" { ")?;
244 self.descriptors.to_css(&mut CssWriter::new(dest))?;
245 dest.write_char('}')
246 }
247}
248
249impl ToShmem for PropertyRegistration {
250 fn to_shmem(&self, _builder: &mut SharedMemoryBuilder) -> to_shmem::Result<Self> {
251 Err(String::from(
252 "ToShmem failed for PropertyRule: cannot handle @property rules",
253 ))
254 }
255}
256
257#[derive(Clone, Debug, PartialEq, MallocSizeOf)]
259pub struct PropertyRuleName(pub CustomPropertyName);
260
261impl ToCss for PropertyRuleName {
262 fn to_css<W: Write>(&self, dest: &mut CssWriter<W>) -> fmt::Result {
263 dest.write_str("--")?;
264 serialize_atom_name(&self.0, dest)
265 }
266}
267
268#[derive(Clone, Debug, MallocSizeOf, PartialEq, ToCss, ToShmem)]
270pub enum Inherits {
271 True,
273 False,
275}
276
277impl Parse for Inherits {
278 fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
279 let result: Result<Inherits, ParseError> = (|| {
282 try_match_ident_ignore_ascii_case! { input,
283 "true" => Ok(Inherits::True),
284 "false" => Ok(Inherits::False),
285 }
286 })();
287 if result.is_err() {
288 Err(ParseError::custom(
289 StyleParseErrorKind::PropertyInheritsField(
290 PropertyInheritsParseError::InvalidInherits,
291 ),
292 ))
293 } else {
294 result
295 }
296 }
297}
298
299pub type InitialValue = Arc<SpecifiedValue>;
304
305impl Parse for InitialValue {
306 fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
307 input.skip_whitespace();
308 Ok(Arc::new(SpecifiedValue::parse(context, input)?))
309 }
310}
311
312impl Descriptors {
313 #[inline]
315 pub fn unregistered() -> &'static Self {
316 static UNREGISTERED: Descriptors = Descriptors {
317 inherits: Some(Inherits::True),
318 syntax: Some(SyntaxDescriptor::universal()),
319 initial_value: None,
320 };
321 &UNREGISTERED
322 }
323
324 pub fn inherits(&self) -> bool {
326 self.inherits != Some(Inherits::False)
327 }
328
329 pub fn is_universal(&self) -> bool {
331 self.syntax.as_ref().is_none_or(|s| s.is_universal())
332 }
333}