1use super::{
8 rule::Descriptors as PropertyDescriptors,
9 syntax::{
10 Component as SyntaxComponent, ComponentName, Descriptor, Multiplier, data_type::DataType,
11 },
12};
13use crate::custom_properties::ComputedValue as ComputedPropertyValue;
14use crate::derives::*;
15use crate::parser::{Parse, ParserContext};
16use crate::properties;
17use crate::properties::{CSSWideKeyword, CustomDeclarationValue, PropertyIdRef};
18use crate::stylesheets::{CssRuleType, Origin, UrlExtraData};
19use crate::substitution::AttrTaint;
20use crate::values::{
21 CustomIdent,
22 animated::{self, Animate, Procedure},
23 computed::{self, ToComputedValue},
24 specified,
25};
26use cssparser::{BasicParseErrorKind, ParseErrorKind, Parser as CSSParser, TokenSerializationType};
27use selectors::matching::QuirksMode;
28use servo_arc::Arc;
29use smallvec::SmallVec;
30use std::fmt::{self, Write};
31use style_traits::{
32 CssWriter, ParseError as StyleParseError, ParsingMode, PropertySyntaxParseError,
33 StyleParseErrorKind, ToCss, owned_str::OwnedStr,
34};
35
36pub type ComputedValueComponent = GenericValueComponent<
38 computed::Length,
39 computed::Number,
40 computed::Percentage,
41 computed::LengthPercentage,
42 computed::Color,
43 computed::Image,
44 computed::url::ComputedUrl,
45 computed::Integer,
46 computed::Angle,
47 computed::Time,
48 computed::Resolution,
49 computed::Transform,
50>;
51
52pub type SpecifiedValueComponent = GenericValueComponent<
54 specified::Length,
55 specified::Number,
56 specified::Percentage,
57 specified::LengthPercentage,
58 specified::Color,
59 specified::Image,
60 specified::url::SpecifiedUrl,
61 specified::Integer,
62 specified::Angle,
63 specified::Time,
64 specified::Resolution,
65 specified::Transform,
66>;
67
68impl<L, N, P, LP, C, Image, U, Integer, A, T, R, Transform>
69 GenericValueComponent<L, N, P, LP, C, Image, U, Integer, A, T, R, Transform>
70{
71 fn serialization_types(&self) -> (TokenSerializationType, TokenSerializationType) {
72 let first_token_type = match self {
73 Self::Length(_) | Self::Angle(_) | Self::Time(_) | Self::Resolution(_) => {
74 TokenSerializationType::Dimension
75 },
76 Self::Number(_) | Self::Integer(_) => TokenSerializationType::Number,
77 Self::Percentage(_) | Self::LengthPercentage(_) => TokenSerializationType::Percentage,
78 Self::Color(_)
79 | Self::Image(_)
80 | Self::Url(_)
81 | Self::TransformFunction(_)
82 | Self::TransformList(_) => TokenSerializationType::Function,
83 Self::CustomIdent(_) => TokenSerializationType::Ident,
84 Self::String(_) => TokenSerializationType::Other,
85 };
86 let last_token_type = if first_token_type == TokenSerializationType::Function {
87 TokenSerializationType::Other
88 } else {
89 first_token_type
90 };
91 (first_token_type, last_token_type)
92 }
93}
94
95#[derive(
97 Animate, Clone, ToCss, ToComputedValue, ToResolvedValue, Debug, MallocSizeOf, PartialEq, ToShmem,
98)]
99#[animation(no_bound(Image, Url))]
100pub enum GenericValueComponent<
101 Length,
102 Number,
103 Percentage,
104 LengthPercentage,
105 Color,
106 Image,
107 Url,
108 Integer,
109 Angle,
110 Time,
111 Resolution,
112 TransformFunction,
113> {
114 Length(Length),
116 Number(Number),
118 Percentage(Percentage),
120 LengthPercentage(LengthPercentage),
122 Color(Color),
124 #[animation(error)]
126 Image(Image),
127 #[animation(error)]
129 Url(Url),
130 Integer(Integer),
132 Angle(Angle),
134 Time(Time),
136 Resolution(Resolution),
138 TransformFunction(TransformFunction),
141 #[animation(error)]
143 CustomIdent(CustomIdent),
144 TransformList(ComponentList<Self>),
147 #[animation(error)]
149 String(OwnedStr),
150}
151
152#[derive(Clone, ToComputedValue, ToResolvedValue, Debug, MallocSizeOf, PartialEq, ToShmem)]
154pub struct ComponentList<Component> {
155 pub multiplier: Multiplier,
157 pub components: crate::OwnedSlice<Component>,
159}
160
161impl<Component: Animate> Animate for ComponentList<Component> {
162 fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> {
163 if self.multiplier != other.multiplier {
164 return Err(());
165 }
166 let components = animated::lists::by_computed_value::animate(
167 &self.components,
168 &other.components,
169 procedure,
170 )?;
171 Ok(Self {
172 multiplier: self.multiplier,
173 components,
174 })
175 }
176}
177
178impl<Component: ToCss> ToCss for ComponentList<Component> {
179 fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
180 where
181 W: Write,
182 {
183 let mut iter = self.components.iter();
184 let Some(first) = iter.next() else {
185 return Ok(());
186 };
187 first.to_css(dest)?;
188
189 let separator = match self.multiplier {
191 Multiplier::Space => " ",
193 Multiplier::Comma => ", ",
195 };
196 for component in iter {
197 dest.write_str(separator)?;
198 component.to_css(dest)?;
199 }
200 Ok(())
201 }
202}
203
204#[derive(Clone, Debug, MallocSizeOf, ToCss, ToComputedValue, ToResolvedValue, ToShmem, ToTyped)]
207#[typed(todo_derive_fields)]
208pub struct Value<Component> {
209 pub(crate) v: ValueInner<Component>,
211 #[css(skip)]
214 url_data: UrlExtraData,
215 #[css(skip)]
217 pub attr_tainted: bool,
218}
219
220impl<Component: PartialEq> PartialEq for Value<Component> {
221 fn eq(&self, other: &Self) -> bool {
223 self.v == other.v
224 }
225}
226
227impl<Component: Animate> Animate for Value<Component> {
228 fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> {
229 let v = self.v.animate(&other.v, procedure)?;
230 Ok(Value {
231 v,
232 url_data: self.url_data.clone(),
233 attr_tainted: self.attr_tainted,
234 })
235 }
236}
237
238impl<Component> Value<Component> {
239 pub fn new(v: ValueInner<Component>, url_data: UrlExtraData) -> Self {
241 Self {
242 v,
243 url_data,
244 attr_tainted: Default::default(),
245 }
246 }
247
248 pub fn universal(var: Arc<ComputedPropertyValue>) -> Self {
250 let attr_tainted = var.is_attr_tainted();
251 let url_data = var.url_data.clone();
252 let v = ValueInner::Universal(var);
253 Self {
254 v,
255 url_data,
256 attr_tainted,
257 }
258 }
259}
260
261impl<L, N, P, LP, C, Image, U, Integer, A, T, R, Transform>
262 Value<GenericValueComponent<L, N, P, LP, C, Image, U, Integer, A, T, R, Transform>>
263where
264 Self: ToCss,
265{
266 fn serialization_types(&self) -> (TokenSerializationType, TokenSerializationType) {
267 match &self.v {
268 ValueInner::Component(component) => component.serialization_types(),
269 ValueInner::Universal(_) => unreachable!(),
270 ValueInner::List(list) => list
271 .components
272 .first()
273 .map_or(Default::default(), |f| f.serialization_types()),
274 }
275 }
276
277 pub fn to_variable_value(&self) -> ComputedPropertyValue {
279 if let ValueInner::Universal(ref value) = self.v {
280 return (**value).clone();
281 }
282 let serialization_types = self.serialization_types();
283 ComputedPropertyValue::new(
284 self.to_css_string(),
285 &self.url_data,
286 serialization_types.0,
287 serialization_types.1,
288 )
289 }
290}
291
292#[derive(
294 Animate, ToComputedValue, ToResolvedValue, ToCss, Clone, Debug, MallocSizeOf, PartialEq, ToShmem,
295)]
296pub enum ValueInner<Component> {
297 Component(Component),
300 #[animation(error)]
302 Universal(#[ignore_malloc_size_of = "Arc"] Arc<ComputedPropertyValue>),
303 List(#[animation(field_bound)] ComponentList<Component>),
305}
306
307pub type SpecifiedValue = Value<SpecifiedValueComponent>;
309
310pub type ComputedValue = Value<ComputedValueComponent>;
312
313impl SpecifiedValue {
314 pub fn compute(
317 input: &mut CSSParser,
318 registration: &PropertyDescriptors,
319 url_data: &UrlExtraData,
320 context: &computed::Context,
321 allow_computationally_dependent: AllowComputationallyDependent,
322 attr_taint: AttrTaint,
323 property_id: Option<PropertyIdRef>,
324 ) -> Result<ComputedValue, ()> {
325 debug_assert!(!registration.is_universal(), "Shouldn't be needed");
326 let Some(ref syntax) = registration.syntax else {
327 return Err(());
328 };
329 let Ok(value) = Self::parse(
330 input,
331 syntax,
332 url_data,
333 allow_computationally_dependent,
334 attr_taint,
335 property_id,
336 ) else {
337 return Err(());
338 };
339
340 Ok(value.to_computed_value(context))
341 }
342
343 pub fn parse(
346 input: &mut CSSParser,
347 syntax: &Descriptor,
348 url_data: &UrlExtraData,
349 allow_computationally_dependent: AllowComputationallyDependent,
350 attr_taint: AttrTaint,
351 property_id: Option<PropertyIdRef>,
352 ) -> Result<Self, StyleParseError> {
353 let parsing_mode = match allow_computationally_dependent {
354 AllowComputationallyDependent::No => ParsingMode::DISALLOW_COMPUTATIONALLY_DEPENDENT,
355 AllowComputationallyDependent::Yes => ParsingMode::DEFAULT,
356 };
357 let context = ParserContext::new_with_property_id(
358 Origin::Author,
359 url_data,
360 Some(CssRuleType::Style),
361 parsing_mode,
362 QuirksMode::NoQuirks,
363 Default::default(),
364 None,
365 None,
366 attr_taint,
367 property_id,
368 );
369
370 if syntax.is_universal() {
371 let parsed = ComputedPropertyValue::parse(&context, input)?;
372 return Ok(Self::new(
373 ValueInner::Universal(Arc::new(parsed)),
374 url_data.clone(),
375 ));
376 }
377
378 let mut values = SmallComponentVec::new();
379 let mut multiplier = None;
380 {
381 let mut parser = Parser::new(syntax, &mut values, &mut multiplier);
382 parser.parse(&context, input)?;
383 }
384 let v = if let Some(multiplier) = multiplier {
385 ValueInner::List(ComponentList {
386 multiplier,
387 components: values.to_vec().into(),
388 })
389 } else {
390 ValueInner::Component(values[0].clone())
391 };
392 Ok(Self::new(v, url_data.clone()))
393 }
394}
395
396impl ComputedValue {
397 pub fn to_declared_value(&self) -> properties::CustomDeclarationValue {
399 if let ValueInner::Universal(ref var) = self.v {
400 if self.attr_tainted && !var.is_attr_tainted() {
408 let mut tainted = (**var).clone();
409 tainted.explicitly_attr_tainted = true;
410 return properties::CustomDeclarationValue::Unparsed(Arc::new(tainted));
411 }
412 return properties::CustomDeclarationValue::Unparsed(Arc::clone(var));
413 }
414 properties::CustomDeclarationValue::Parsed(Arc::new(ToComputedValue::from_computed_value(
415 self,
416 )))
417 }
418
419 pub fn as_universal(&self) -> Option<&Arc<ComputedPropertyValue>> {
421 if let ValueInner::Universal(ref var) = self.v {
422 Some(var)
423 } else {
424 None
425 }
426 }
427}
428
429pub enum AllowComputationallyDependent {
434 No,
436 Yes,
438}
439
440type SmallComponentVec = SmallVec<[SpecifiedValueComponent; 1]>;
441
442struct Parser<'a> {
443 syntax: &'a Descriptor,
444 output: &'a mut SmallComponentVec,
445 output_multiplier: &'a mut Option<Multiplier>,
446}
447
448impl<'a> Parser<'a> {
449 fn new(
450 syntax: &'a Descriptor,
451 output: &'a mut SmallComponentVec,
452 output_multiplier: &'a mut Option<Multiplier>,
453 ) -> Self {
454 Self {
455 syntax,
456 output,
457 output_multiplier,
458 }
459 }
460
461 fn parse(
462 &mut self,
463 context: &ParserContext,
464 input: &mut CSSParser,
465 ) -> Result<(), StyleParseError> {
466 for component in self.syntax.components.iter() {
467 let result = input.try_parse(|input| {
468 input.parse_entirely(|input| {
469 Self::parse_value(context, input, &component.unpremultiplied())
470 })
471 });
472 let Ok(values) = result else { continue };
473 self.output.extend(values);
474 *self.output_multiplier = component.multiplier();
475 break;
476 }
477 if self.output.is_empty() {
478 return Err(StyleParseError::from_basic_kind(
479 BasicParseErrorKind::EndOfInput,
480 ));
481 }
482 Ok(())
483 }
484
485 fn parse_value(
486 context: &ParserContext,
487 input: &mut CSSParser,
488 component: &SyntaxComponent,
489 ) -> Result<SmallComponentVec, StyleParseError> {
490 let mut values = SmallComponentVec::new();
491 values.push(Self::parse_component_without_multiplier(
492 context, input, component,
493 )?);
494
495 if let Some(multiplier) = component.multiplier() {
496 loop {
497 let result = Self::expect_multiplier(input, &multiplier);
498 if Self::expect_multiplier_yielded_eof_error(&result) {
499 break;
500 }
501 result?;
502 values.push(Self::parse_component_without_multiplier(
503 context, input, component,
504 )?);
505 }
506 }
507 Ok(values)
508 }
509
510 fn parse_component_without_multiplier(
511 context: &ParserContext,
512 input: &mut CSSParser,
513 component: &SyntaxComponent,
514 ) -> Result<SpecifiedValueComponent, StyleParseError> {
515 let data_type = match component.name() {
516 ComponentName::DataType(ty) => ty,
517 ComponentName::Ident(name) => {
518 let ident = CustomIdent::parse(input, &[])?;
519 if ident != *name {
520 return Err(StyleParseError::custom(
521 StyleParseErrorKind::UnspecifiedError,
522 ));
523 }
524 return Ok(SpecifiedValueComponent::CustomIdent(ident));
525 },
526 };
527
528 let value = match data_type {
529 DataType::Length => {
530 SpecifiedValueComponent::Length(specified::Length::parse(context, input)?)
531 },
532 DataType::Number => {
533 SpecifiedValueComponent::Number(specified::Number::parse(context, input)?)
534 },
535 DataType::Percentage => {
536 SpecifiedValueComponent::Percentage(specified::Percentage::parse(context, input)?)
537 },
538 DataType::LengthPercentage => SpecifiedValueComponent::LengthPercentage(
539 specified::LengthPercentage::parse(context, input)?,
540 ),
541 DataType::Color => {
542 SpecifiedValueComponent::Color(specified::Color::parse(context, input)?)
543 },
544 DataType::Image => {
545 SpecifiedValueComponent::Image(specified::Image::parse_forbid_none(context, input)?)
546 },
547 DataType::Url => {
548 SpecifiedValueComponent::Url(specified::url::SpecifiedUrl::parse(context, input)?)
549 },
550 DataType::Integer => {
551 SpecifiedValueComponent::Integer(specified::Integer::parse(context, input)?)
552 },
553 DataType::Angle => {
554 SpecifiedValueComponent::Angle(specified::Angle::parse(context, input)?)
555 },
556 DataType::Time => {
557 SpecifiedValueComponent::Time(specified::Time::parse(context, input)?)
558 },
559 DataType::Resolution => {
560 SpecifiedValueComponent::Resolution(specified::Resolution::parse(context, input)?)
561 },
562 DataType::TransformFunction => SpecifiedValueComponent::TransformFunction(
563 specified::Transform::parse(context, input)?,
564 ),
565 DataType::CustomIdent => {
566 let name = CustomIdent::parse(input, &[])?;
567 SpecifiedValueComponent::CustomIdent(name)
568 },
569 DataType::TransformList => {
570 let mut values = vec![];
571 let Some(multiplier) = component.unpremultiplied().multiplier() else {
572 debug_assert!(false, "Unpremultiplied <transform-list> had no multiplier?");
573 return Err(StyleParseError::custom(
574 StyleParseErrorKind::PropertySyntaxField(
575 PropertySyntaxParseError::UnexpectedEOF,
576 ),
577 ));
578 };
579 debug_assert_eq!(multiplier, Multiplier::Space);
580 loop {
581 values.push(SpecifiedValueComponent::TransformFunction(
582 specified::Transform::parse(context, input)?,
583 ));
584 let result = Self::expect_multiplier(input, &multiplier);
585 if Self::expect_multiplier_yielded_eof_error(&result) {
586 break;
587 }
588 result?;
589 }
590 let list = ComponentList {
591 multiplier,
592 components: values.into(),
593 };
594 SpecifiedValueComponent::TransformList(list)
595 },
596 DataType::String => {
597 let string = input.expect_string()?;
598 SpecifiedValueComponent::String(string.as_ref().to_owned().into())
599 },
600 };
601 Ok(value)
602 }
603
604 fn expect_multiplier_yielded_eof_error(result: &Result<(), StyleParseError>) -> bool {
605 matches!(
606 result,
607 Err(StyleParseError {
608 kind: ParseErrorKind::Basic(BasicParseErrorKind::EndOfInput),
609 ..
610 })
611 )
612 }
613
614 fn expect_multiplier(
615 input: &mut CSSParser,
616 multiplier: &Multiplier,
617 ) -> Result<(), StyleParseError> {
618 match multiplier {
619 Multiplier::Space => {
620 input.expect_whitespace()?;
621 if input.is_exhausted() {
622 return Err(StyleParseError::from_basic_kind(
624 BasicParseErrorKind::EndOfInput,
625 ));
626 }
627 Ok(())
628 },
629 Multiplier::Comma => Ok(input.expect_comma()?),
630 }
631 }
632}
633
634#[derive(Clone, Debug, MallocSizeOf, PartialEq)]
636pub struct CustomAnimatedValue {
637 pub(crate) name: crate::custom_properties::Name,
639 pub(crate) value: Option<ComputedValue>,
642}
643
644impl Animate for CustomAnimatedValue {
645 fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> {
646 if self.name != other.name {
647 return Err(());
648 }
649 let value = self.value.animate(&other.value, procedure)?;
650 Ok(Self {
651 name: self.name.clone(),
652 value,
653 })
654 }
655}
656
657impl CustomAnimatedValue {
658 pub(crate) fn from_computed(
659 name: &crate::custom_properties::Name,
660 value: Option<&ComputedValue>,
661 ) -> Self {
662 Self {
663 name: name.clone(),
664 value: value.cloned(),
665 }
666 }
667
668 pub(crate) fn from_declaration(
669 declaration: &properties::CustomDeclaration,
670 context: &mut computed::Context,
671 ) -> Option<Self> {
672 let computed_value = match declaration.value {
673 properties::CustomDeclarationValue::Unparsed(ref value) => Some({
674 debug_assert!(
675 context.builder.stylist.is_some(),
676 "Need a Stylist to get property registration!"
677 );
678 let registration = context
679 .builder
680 .stylist
681 .unwrap()
682 .get_custom_property_registration(&declaration.name);
683 if registration.is_universal() {
684 ComputedValue::universal(Arc::clone(value))
686 } else {
687 let mut input = CSSParser::new(&value.css);
688 SpecifiedValue::compute(
689 &mut input,
690 registration,
691 &value.url_data,
692 context,
693 AllowComputationallyDependent::Yes,
694 Default::default(),
695 Some(PropertyIdRef::from(&declaration.name)),
696 )
697 .unwrap_or_else(|_| ComputedValue::universal(Arc::clone(value)))
698 }
699 }),
700 properties::CustomDeclarationValue::Parsed(ref v) => Some(v.to_computed_value(context)),
701 properties::CustomDeclarationValue::CSSWideKeyword(keyword) => {
702 let stylist = context.builder.stylist.unwrap();
703 let registration = stylist.get_custom_property_registration(&declaration.name);
704 match keyword {
705 CSSWideKeyword::Initial => stylist
706 .get_custom_property_initial_values()
707 .get(registration, &declaration.name),
708 CSSWideKeyword::Inherit => context
709 .builder
710 .inherited_custom_properties()
711 .get(registration, &declaration.name),
712 CSSWideKeyword::Unset => {
713 if registration.inherits() {
714 context
715 .builder
716 .inherited_custom_properties()
717 .get(registration, &declaration.name)
718 } else {
719 stylist
720 .get_custom_property_initial_values()
721 .get(registration, &declaration.name)
722 }
723 },
724 CSSWideKeyword::Revert
734 | CSSWideKeyword::RevertRule
735 | CSSWideKeyword::RevertLayer => return None,
736 }
737 .cloned()
738 },
739 };
740 Some(Self {
741 name: declaration.name.clone(),
742 value: computed_value,
743 })
744 }
745
746 pub(crate) fn to_declaration(&self) -> properties::PropertyDeclaration {
747 properties::PropertyDeclaration::Custom(properties::CustomDeclaration {
748 name: self.name.clone(),
749 value: match &self.value {
750 Some(value) => value.to_declared_value(),
751 None => CustomDeclarationValue::CSSWideKeyword(CSSWideKeyword::Initial),
752 },
753 })
754 }
755}