Skip to main content

style/
custom_properties.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! Support for [custom properties for cascading variables][custom].
6//!
7//! [custom]: https://drafts.csswg.org/css-variables/
8
9use crate::custom_properties_map::{CustomPropertiesMap, OwnMap};
10use crate::dom::AttributeTracker;
11use crate::parser::ParserContext;
12use crate::properties::{CSSWideKeyword, PrioritaryPropertyId, PropertyIdRef};
13use crate::properties_and_values::{
14    rule::Descriptors as PropertyDescriptors,
15    value::{
16        AllowComputationallyDependent, ComputedValue as ComputedRegisteredValue,
17        SpecifiedValue as SpecifiedRegisteredValue,
18    },
19};
20use crate::stylesheets::UrlExtraData;
21use crate::stylesheets::container_rule::AttrReferenceSet;
22use crate::stylist::Stylist;
23use crate::substitution::{
24    AttrTaint, ReferenceFlags, References, SubstitutionArgument, SubstitutionFunction,
25    SubstitutionFunctionKind, SubstitutionFunctionReference, SubstitutionParserContext,
26    SubstitutionReplacementContext, parse_declaration_value,
27};
28use crate::typed_om::{
29    ToTyped, TypedValue, UnparsedSegment, UnparsedValue, VariableReferenceValue,
30};
31use crate::values::computed;
32use crate::{Atom, derives::*};
33use cssparser::{CowRcStr, Delimiter, Parser, Token, TokenSerializationType};
34use servo_arc::Arc;
35use std::fmt::{self, Write};
36use std::ops::{Index, IndexMut};
37use style_traits::{CssString, CssWriter, ParseError, ToCss};
38use thin_vec::ThinVec;
39
40/// A custom property name is just an `Atom`.
41///
42/// Note that this does not include the `--` prefix
43pub type Name = Atom;
44
45/// Parse a custom property name.
46///
47/// <https://drafts.csswg.org/css-variables/#typedef-custom-property-name>
48pub fn parse_name(s: &str) -> Result<&str, ()> {
49    if s.starts_with("--") && s.len() > 2 {
50        Ok(&s[2..])
51    } else {
52        Err(())
53    }
54}
55
56/// A value for a custom property is just a set of tokens.
57///
58/// We preserve the original CSS for serialization, and also the variable
59/// references to other custom property names.
60#[derive(Clone, Debug, MallocSizeOf, ToShmem)]
61pub struct VariableValue {
62    /// The raw CSS string.
63    pub css: String,
64
65    /// The url data of the stylesheet where this value came from.
66    pub url_data: UrlExtraData,
67
68    /// The serialization type of the first token in `css`.
69    pub first_token_type: TokenSerializationType,
70    /// The serialization type of the last token in `css`.
71    pub last_token_type: TokenSerializationType,
72
73    /// var(), env(), attr() or non-custom property (e.g. through `em`) references.
74    pub references: References,
75
76    /// Was this variable value attr tainted before. Used to keep attr tainting
77    /// information when uncomputing a style that needs to be put back into the
78    /// cascade.
79    pub explicitly_attr_tainted: bool,
80}
81
82trivial_to_computed_value!(VariableValue);
83
84/// Given a potentially registered variable value turn it into a computed custom property value.
85pub(crate) fn compute_variable_value(
86    value: &Arc<VariableValue>,
87    registration: &PropertyDescriptors,
88    computed_context: &computed::Context,
89    property_id: Option<PropertyIdRef>,
90) -> Option<ComputedRegisteredValue> {
91    if registration.is_universal() {
92        return Some(ComputedRegisteredValue::universal(Arc::clone(value)));
93    }
94    compute_value(
95        &value.css,
96        &value.url_data,
97        registration,
98        computed_context,
99        AttrTaint::default(),
100        property_id,
101    )
102    .ok()
103}
104
105// For all purposes, we want values to be considered equal if their css text is equal.
106impl PartialEq for VariableValue {
107    fn eq(&self, other: &Self) -> bool {
108        self.css == other.css
109    }
110}
111
112impl Eq for VariableValue {}
113
114impl ToCss for SpecifiedValue {
115    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
116    where
117        W: Write,
118    {
119        dest.write_str(&self.css)
120    }
121}
122
123impl ToTyped for SpecifiedValue {
124    fn to_typed(&self, dest: &mut ThinVec<TypedValue>) -> Result<(), ()> {
125        let unparsed_value = reify_variable_value(self)?;
126        dest.push(TypedValue::Unparsed(unparsed_value));
127        Ok(())
128    }
129}
130
131fn reify_variable_value(value: &VariableValue) -> Result<UnparsedValue, ()> {
132    let mut reference_index = 0;
133    reify_variable_value_range(
134        &value.css,
135        &value.references.refs,
136        &mut reference_index,
137        0,
138        value.css.len(),
139    )
140}
141
142/// Reify a slice of the CSS string into UnparsedSegment entries.
143///
144/// References are stored in source order, with outer substitution functions
145/// inserted before references in their fallback. The shared `reference_index`
146/// relies on this ordering to recurse into fallbacks without reprocessing
147/// nested referecences.
148fn reify_variable_value_range(
149    css: &str,
150    references: &[SubstitutionFunctionReference],
151    reference_index: &mut usize,
152    start: usize,
153    end: usize,
154) -> Result<UnparsedValue, ()> {
155    debug_assert!(start <= end);
156    debug_assert!(end <= css.len());
157
158    let mut values = ThinVec::new();
159    let mut cur_pos = start;
160
161    while *reference_index < references.len() {
162        let reference = &references[*reference_index];
163
164        if reference.start >= end {
165            break;
166        }
167
168        debug_assert!(reference.start >= cur_pos);
169        debug_assert!(reference.start <= reference.end);
170        debug_assert!(reference.end <= css.len());
171
172        if cur_pos < reference.start {
173            values.push(UnparsedSegment::String(CssString::from(
174                &css[cur_pos..reference.start],
175            )));
176        }
177
178        *reference_index += 1;
179
180        let SubstitutionFunction::Var(var) = &reference.function else {
181            return Err(());
182        };
183        let (fallback, has_fallback) = if let Some(fallback) = var.fallback.as_ref() {
184            debug_assert!(fallback.start <= fallback.end);
185
186            (
187                reify_variable_value_range(
188                    css,
189                    references,
190                    reference_index,
191                    fallback.start.get(),
192                    fallback.end.get(),
193                )?,
194                true,
195            )
196        } else {
197            (ThinVec::new(), false)
198        };
199
200        let SubstitutionArgument::Parsed(name) = &var.name else {
201            return Err(());
202        };
203        values.push(UnparsedSegment::VariableReference(VariableReferenceValue {
204            variable: CssString::from(format!("--{}", name.0)),
205            fallback,
206            has_fallback,
207        }));
208
209        cur_pos = reference.end;
210    }
211
212    if cur_pos < end {
213        values.push(UnparsedSegment::String(CssString::from(&css[cur_pos..end])));
214    }
215
216    Ok(values)
217}
218
219/// A pair of separate CustomPropertiesMaps, split between custom properties
220/// that have the inherit flag set and those with the flag unset.
221#[repr(C)]
222#[derive(Clone, Debug, Default, PartialEq)]
223pub struct ComputedCustomProperties {
224    /// Map for custom properties with inherit flag set, including non-registered
225    /// ones.
226    pub inherited: CustomPropertiesMap,
227    /// Map for custom properties with inherit flag unset.
228    pub non_inherited: CustomPropertiesMap,
229}
230
231impl ComputedCustomProperties {
232    /// Return whether the inherited and non_inherited maps are none.
233    pub fn is_empty(&self) -> bool {
234        self.inherited.is_empty() && self.non_inherited.is_empty()
235    }
236
237    /// Return the name and value of the property at specified index, if any.
238    pub fn property_at(&self, index: usize) -> Option<(&Name, &Option<ComputedRegisteredValue>)> {
239        // Just expose the custom property items from custom_properties.inherited, followed
240        // by custom property items from custom_properties.non_inherited.
241        self.inherited
242            .get_index(index)
243            .or_else(|| self.non_inherited.get_index(index - self.inherited.len()))
244    }
245
246    /// Insert a custom property in the corresponding inherited/non_inherited
247    /// map, depending on whether the inherit flag is set or unset.
248    pub fn insert(
249        &mut self,
250        registration: &PropertyDescriptors,
251        name: &Name,
252        value: ComputedRegisteredValue,
253    ) {
254        self.map_mut(registration).insert(name, value)
255    }
256
257    /// Remove a custom property from the corresponding inherited/non_inherited
258    /// map, depending on whether the inherit flag is set or unset.
259    pub fn remove(&mut self, registration: &PropertyDescriptors, name: &Name) {
260        self.map_mut(registration).remove(name);
261    }
262
263    /// Shrink the capacity of the inherited maps as much as possible.
264    pub fn shrink_to_fit(&mut self) {
265        self.inherited.shrink_to_fit();
266        self.non_inherited.shrink_to_fit();
267    }
268
269    fn map_mut(&mut self, registration: &PropertyDescriptors) -> &mut CustomPropertiesMap {
270        if registration.inherits() {
271            &mut self.inherited
272        } else {
273            &mut self.non_inherited
274        }
275    }
276
277    /// Returns the relevant custom property value given a registration.
278    pub fn get(
279        &self,
280        registration: &PropertyDescriptors,
281        name: &Name,
282    ) -> Option<&ComputedRegisteredValue> {
283        if registration.inherits() {
284            self.inherited.get(name)
285        } else {
286            self.non_inherited.get(name)
287        }
288    }
289
290    /// Returns a property just by the name. Slightly less efficient than get(), if you already have
291    /// a custom registration handy, thus the longer name.
292    pub fn get_for_cssom(&self, name: &Name) -> Option<&ComputedRegisteredValue> {
293        self.inherited
294            .get(name)
295            .or_else(|| self.non_inherited.get(name))
296    }
297}
298
299/// Both specified and computed values are VariableValues, the difference is
300/// whether var() functions are expanded.
301pub type SpecifiedValue = VariableValue;
302/// Both specified and computed values are VariableValues, the difference is
303/// whether var() functions are expanded.
304pub type ComputedValue = VariableValue;
305
306impl ReferenceFlags {
307    /// Iterate for each non custom
308    pub fn for_each_non_custom<F>(mut self, is_root_element: bool, mut f: F)
309    where
310        F: FnMut(SingleNonCustomReference),
311    {
312        // On the root element, rem etc refer to the root's own dependencies.
313        if is_root_element {
314            if self.intersects(Self::ROOT_FONT_UNITS) {
315                self.remove(Self::ROOT_FONT_UNITS);
316                self |= Self::FONT_UNITS;
317            }
318            if self.intersects(Self::ROOT_LH_UNITS) {
319                self.remove(Self::ROOT_FONT_UNITS);
320                self |= Self::LH_UNITS;
321            }
322        }
323
324        for (_, r) in self.iter_names() {
325            let single = match r {
326                Self::FONT_UNITS => SingleNonCustomReference::FontUnits,
327                Self::LH_UNITS => SingleNonCustomReference::LhUnits,
328                Self::COLOR_SCHEME => SingleNonCustomReference::ColorScheme,
329                Self::ROOT_FONT_UNITS
330                | Self::ROOT_LH_UNITS
331                | Self::VAR
332                | Self::ENV
333                | Self::ATTR => continue,
334                _ => unreachable!("Unexpected single bit value"),
335            };
336            f(single);
337        }
338    }
339}
340
341/// A non-custom reference that participates in cycle resolution.
342/// TODO(emilio): This should probably eventually become just PrioritaryPropertyId.
343#[derive(Clone, Copy, Debug, Eq, PartialEq)]
344#[allow(missing_docs)]
345pub enum SingleNonCustomReference {
346    FontUnits = 0,
347    LhUnits,
348    ColorScheme,
349}
350
351impl SingleNonCustomReference {
352    /// Returns a prioritary id for this reference.
353    pub fn to_prioritary_id(self) -> PrioritaryPropertyId {
354        match self {
355            Self::FontUnits => PrioritaryPropertyId::FontSize,
356            Self::LhUnits => PrioritaryPropertyId::LineHeight,
357            Self::ColorScheme => PrioritaryPropertyId::ColorScheme,
358        }
359    }
360}
361
362/// A map from NonCustomReferenceMap to a T.
363pub struct NonCustomReferenceMap<T>([Option<T>; 3]);
364
365impl<T> Default for NonCustomReferenceMap<T> {
366    fn default() -> Self {
367        NonCustomReferenceMap(Default::default())
368    }
369}
370
371impl<T> Index<SingleNonCustomReference> for NonCustomReferenceMap<T> {
372    type Output = Option<T>;
373
374    fn index(&self, reference: SingleNonCustomReference) -> &Self::Output {
375        &self.0[reference as usize]
376    }
377}
378
379impl<T> IndexMut<SingleNonCustomReference> for NonCustomReferenceMap<T> {
380    fn index_mut(&mut self, reference: SingleNonCustomReference) -> &mut Self::Output {
381        &mut self.0[reference as usize]
382    }
383}
384
385/// A wrapper map that encapsulates both the custom properties and attributes
386/// for a given element.
387#[repr(C)]
388#[derive(Clone, Debug, Default, PartialEq)]
389pub struct ComputedSubstitutionFunctions {
390    /// The applicable custom properties (includes inherited and non-inherited).
391    pub custom_properties: ComputedCustomProperties,
392    /// The applicable DOM attributes.
393    pub attributes: OwnMap,
394}
395
396impl ComputedSubstitutionFunctions {
397    /// Creates a substitution function map from optional custom properties
398    /// and DOM attributes.
399    #[inline(always)]
400    pub fn new(
401        custom_properties: Option<ComputedCustomProperties>,
402        attributes: Option<OwnMap>,
403    ) -> Self {
404        Self {
405            custom_properties: custom_properties.unwrap_or_default(),
406            attributes: attributes.unwrap_or_default(),
407        }
408    }
409
410    #[inline(always)]
411    pub(crate) fn insert_var(
412        &mut self,
413        registration: &PropertyDescriptors,
414        name: &Name,
415        value: ComputedRegisteredValue,
416    ) {
417        self.custom_properties.insert(registration, name, value);
418    }
419
420    #[inline(always)]
421    pub(crate) fn insert_attr(&mut self, name: &Name, value: ComputedRegisteredValue) {
422        self.attributes.insert(name.clone(), Some(value));
423    }
424
425    #[inline(always)]
426    pub(crate) fn remove_var(&mut self, registration: &PropertyDescriptors, name: &Name) {
427        self.custom_properties.remove(registration, name);
428    }
429
430    #[inline(always)]
431    pub(crate) fn remove_attr(&mut self, name: &Name) {
432        self.attributes.insert(name.clone(), None);
433    }
434
435    #[inline(always)]
436    pub(crate) fn get_var(
437        &self,
438        registration: &PropertyDescriptors,
439        name: &Name,
440    ) -> Option<&ComputedRegisteredValue> {
441        self.custom_properties.get(registration, name)
442    }
443
444    #[inline(always)]
445    pub(crate) fn get_attr(&self, name: &Name) -> Option<&ComputedRegisteredValue> {
446        self.attributes.get(name).and_then(|p| p.as_ref())
447    }
448}
449
450impl VariableValue {
451    /// Creates an empty value.
452    pub(crate) fn empty(url_data: &UrlExtraData) -> Self {
453        Self {
454            css: String::new(),
455            last_token_type: Default::default(),
456            first_token_type: Default::default(),
457            url_data: url_data.clone(),
458            references: Default::default(),
459            explicitly_attr_tainted: false,
460        }
461    }
462
463    /// Create a new custom property without parsing if the CSS is known to be valid and contain no
464    /// references.
465    pub fn new(
466        css: String,
467        url_data: &UrlExtraData,
468        first_token_type: TokenSerializationType,
469        last_token_type: TokenSerializationType,
470    ) -> Self {
471        Self {
472            css,
473            url_data: url_data.clone(),
474            first_token_type,
475            last_token_type,
476            references: References::default(),
477            explicitly_attr_tainted: false,
478        }
479    }
480
481    /// Appends `css` to the value, inserting a comment where needed to keep tokens separate.
482    pub(crate) fn push(
483        &mut self,
484        css: &str,
485        css_first_token_type: TokenSerializationType,
486        css_last_token_type: TokenSerializationType,
487        attr_taint: Option<&mut AttrTaint>,
488    ) -> Result<(), ()> {
489        /// Prevent values from getting terribly big since you can use custom
490        /// properties exponentially.
491        ///
492        /// This number (2MB) is somewhat arbitrary, but silly enough that no
493        /// reasonable page should hit it. We could limit by number of total
494        /// substitutions, but that was very easy to work around in practice
495        /// (just choose a larger initial value and boom).
496        const MAX_VALUE_LENGTH_IN_BYTES: usize = 2 * 1024 * 1024;
497
498        if self.css.len() + css.len() > MAX_VALUE_LENGTH_IN_BYTES {
499            return Err(());
500        }
501
502        // This happens e.g. between two subsequent var() functions:
503        // `var(--a)var(--b)`.
504        //
505        // In that case, css_*_token_type is nonsensical.
506        if css.is_empty() {
507            return Ok(());
508        }
509
510        self.first_token_type.set_if_nothing(css_first_token_type);
511        // If self.first_token_type was nothing,
512        // self.last_token_type is also nothing and this will be false:
513        if self
514            .last_token_type
515            .needs_separator_when_before(css_first_token_type)
516        {
517            self.css.push_str("/**/")
518        }
519        let start = self.css.len();
520        self.css.push_str(css);
521        let end = self.css.len();
522        if let Some(taint) = attr_taint {
523            taint.push(start, end);
524        }
525        self.last_token_type = css_last_token_type;
526        Ok(())
527    }
528
529    /// Parse a custom property value.
530    pub fn parse(parser_context: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
531        let mut references = References::default();
532        let start_position = input.position();
533        let mut context = SubstitutionParserContext::new(parser_context, start_position);
534        let (first_token_type, last_token_type) =
535            parse_declaration_value(input, &mut context, &mut references, Delimiter::None)?;
536        let mut css = input
537            .slice_from(start_position)
538            .trim_ascii_start()
539            .to_owned();
540        if !context.missing_closing_characters.is_empty() {
541            // Unescaped backslash at EOF in a quoted string is ignored.
542            if css.ends_with("\\")
543                && matches!(
544                    context.missing_closing_characters.as_bytes()[0],
545                    b'"' | b'\''
546                )
547            {
548                css.pop();
549            }
550            css.push_str(&context.missing_closing_characters);
551        }
552
553        css.truncate(css.trim_ascii_end().len());
554        css.shrink_to_fit();
555        references.refs.shrink_to_fit();
556
557        Ok(Self {
558            css,
559            url_data: parser_context.url_data.clone(),
560            first_token_type,
561            last_token_type,
562            references,
563            explicitly_attr_tainted: false,
564        })
565    }
566
567    /// Returns whether this value is tainted by `attr()`.
568    pub fn is_attr_tainted(&self) -> bool {
569        self.references.flags.intersects(ReferenceFlags::ATTR) | self.explicitly_attr_tainted
570    }
571
572    /// Create VariableValue from an int.
573    pub(crate) fn integer(number: i32, url_data: &UrlExtraData) -> Self {
574        Self::from_token(
575            Token::Number {
576                has_sign: false,
577                value: number as f32,
578                int_value: Some(number),
579            },
580            url_data,
581        )
582    }
583
584    /// Create VariableValue from an int.
585    pub(crate) fn ident(ident: &'static str, url_data: &UrlExtraData) -> Self {
586        Self::from_token(Token::Ident(ident.into()), url_data)
587    }
588
589    pub(crate) fn string(s: &str, url_data: &UrlExtraData) -> Self {
590        Self::from_token(Token::QuotedString(CowRcStr::from(s)), url_data)
591    }
592
593    /// Create VariableValue from a float amount of CSS pixels.
594    pub(crate) fn pixels(number: f32, url_data: &UrlExtraData) -> Self {
595        // FIXME (https://github.com/servo/rust-cssparser/issues/266):
596        // No way to get TokenSerializationType::Dimension without creating
597        // Token object.
598        Self::from_token(
599            Token::Dimension {
600                has_sign: false,
601                value: number,
602                int_value: None,
603                unit: CowRcStr::from("px"),
604            },
605            url_data,
606        )
607    }
608
609    /// Create VariableValue from an integer amount of milliseconds.
610    pub(crate) fn int_ms(number: i32, url_data: &UrlExtraData) -> Self {
611        Self::from_token(
612            Token::Dimension {
613                has_sign: false,
614                value: number as f32,
615                int_value: Some(number),
616                unit: CowRcStr::from("ms"),
617            },
618            url_data,
619        )
620    }
621
622    /// Create VariableValue from an integer amount of CSS pixels.
623    pub(crate) fn int_pixels(number: i32, url_data: &UrlExtraData) -> Self {
624        Self::from_token(
625            Token::Dimension {
626                has_sign: false,
627                value: number as f32,
628                int_value: Some(number),
629                unit: CowRcStr::from("px"),
630            },
631            url_data,
632        )
633    }
634
635    fn from_token(token: Token, url_data: &UrlExtraData) -> Self {
636        let token_type = token.serialization_type();
637        let mut css = token.to_css_string();
638        css.shrink_to_fit();
639
640        VariableValue {
641            css,
642            url_data: url_data.clone(),
643            first_token_type: token_type,
644            last_token_type: token_type,
645            references: Default::default(),
646            explicitly_attr_tainted: false,
647        }
648    }
649
650    /// Returns the raw CSS text from this VariableValue
651    pub fn css_text(&self) -> &str {
652        &self.css
653    }
654
655    /// Returns whether this variable value has any reference to the environment or other
656    /// variables.
657    pub fn has_references(&self) -> bool {
658        self.references.has_references()
659    }
660
661    /// Returns the attribute references in this variable value, if any.
662    pub fn collect_attribute_references(&self, references: &mut AttrReferenceSet) {
663        fn collect(refs: &References, references: &mut AttrReferenceSet) {
664            for r in &refs.refs {
665                if let SubstitutionFunction::Attr(attr) = &r.function {
666                    match &attr.arg {
667                        SubstitutionArgument::Unparsed(_) => {
668                            references.is_fully_parsed = false;
669                        },
670                        SubstitutionArgument::Parsed(arg) => {
671                            // For a non-ascii-lowercase attribute, whether we match
672                            // case-sensitively depends on whether the element we're
673                            // matching against is an HTML element in an HTML document.
674                            // So to simplify invalidation we collect both potential
675                            // references here.
676                            let name = &arg.name.name;
677                            references.names.insert(name.clone().into());
678                            let lowercase = name.to_ascii_lowercase();
679                            if *lowercase != **name {
680                                references.names.insert(Atom::from(lowercase).into());
681                            }
682                        },
683                        SubstitutionArgument::Invalid => {},
684                    }
685                }
686                r.function
687                    .for_each_unparsed_value(|value| collect(&value.references, references));
688            }
689        }
690        collect(&self.references, references);
691    }
692}
693
694/// See https://drafts.csswg.org/css-variables-2/#invalid-at-computed-value-time
695pub fn handle_invalid_at_computed_value_time(
696    name: &Name,
697    registration: &PropertyDescriptors,
698    context: &mut computed::Context,
699) {
700    if !registration.is_universal() {
701        // For the root element, inherited maps are empty. We should just
702        // use the initial value if any, rather than removing the name.
703        if registration.inherits() && !context.builder.is_root_element {
704            let inherited = context.builder.inherited_style.custom_properties();
705            if let Some(value) = inherited.get(registration, name) {
706                context.builder.substitution_functions.insert_var(
707                    registration,
708                    name,
709                    value.clone(),
710                );
711                return;
712            }
713        } else if let Some(ref initial_value) = registration.initial_value
714            && let Ok(initial_value) = compute_value(
715                &initial_value.css,
716                &initial_value.url_data,
717                registration,
718                context,
719                AttrTaint::default(),
720                Some(PropertyIdRef::from(name)),
721            )
722        {
723            context
724                .builder
725                .substitution_functions
726                .insert_var(registration, name, initial_value);
727            return;
728        }
729    }
730    context
731        .builder
732        .substitution_functions
733        .remove_var(registration, name);
734}
735
736/// Replace substitution functions in a pre-existing variable value.
737pub fn substitute_references_if_needed_and_apply(
738    name: &Name,
739    kind: SubstitutionFunctionKind,
740    value: &Arc<VariableValue>,
741    stylist: &Stylist,
742    context: &mut computed::Context,
743    attribute_tracker: &mut AttributeTracker,
744) {
745    debug_assert_ne!(kind, SubstitutionFunctionKind::Env);
746    let is_var = matches!(kind, SubstitutionFunctionKind::Var);
747    let registration = stylist.get_custom_property_registration(name);
748    if is_var && !value.has_references() && registration.is_universal() {
749        // Trivial path: no references and no need to compute the value, just apply it directly.
750        let computed_value = ComputedRegisteredValue::universal(Arc::clone(value));
751        context
752            .builder
753            .substitution_functions
754            .insert_var(registration, name, computed_value);
755        return;
756    }
757
758    let url_data = &value.url_data;
759    let substitution = SubstitutionReplacementContext::new(
760        Some(PropertyIdRef::from(name)),
761        &context.builder.substitution_functions,
762        stylist,
763        context,
764        attribute_tracker,
765    )
766    .substitute_variable_value(value, None);
767
768    let Ok(substitution) = substitution else {
769        if is_var {
770            handle_invalid_at_computed_value_time(name, registration, context);
771        } else {
772            context.builder.substitution_functions.remove_attr(name);
773        }
774        return;
775    };
776
777    // If variable fallback results in a wide keyword, deal with it now.
778    let inherited = context.builder.inherited_style.custom_properties();
779    if is_var {
780        let css = &substitution.css;
781        let css_wide_kw = {
782            let mut input = Parser::new(css);
783            input.try_parse(CSSWideKeyword::parse)
784        };
785
786        if let Ok(kw) = css_wide_kw {
787            // TODO: It's unclear what this should do for revert / revert-layer, see
788            // https://github.com/w3c/csswg-drafts/issues/9131. For now treating as unset
789            // seems fine?
790            match (kw, registration.inherits(), context.is_root_element()) {
791                (CSSWideKeyword::Initial, _, _)
792                | (CSSWideKeyword::Revert, false, _)
793                | (CSSWideKeyword::RevertLayer, false, _)
794                | (CSSWideKeyword::RevertRule, false, _)
795                | (CSSWideKeyword::Unset, false, _)
796                | (CSSWideKeyword::Revert, true, true)
797                | (CSSWideKeyword::RevertLayer, true, true)
798                | (CSSWideKeyword::RevertRule, true, true)
799                | (CSSWideKeyword::Unset, true, true)
800                | (CSSWideKeyword::Inherit, _, true) => {
801                    remove_and_insert_initial_value(
802                        name,
803                        registration,
804                        &mut context.builder.substitution_functions,
805                    );
806                },
807                (CSSWideKeyword::Revert, true, false)
808                | (CSSWideKeyword::RevertLayer, true, false)
809                | (CSSWideKeyword::RevertRule, true, false)
810                | (CSSWideKeyword::Inherit, _, false)
811                | (CSSWideKeyword::Unset, true, false) => {
812                    match inherited.get(registration, name) {
813                        Some(value) => {
814                            context.builder.substitution_functions.insert_var(
815                                registration,
816                                name,
817                                value.clone(),
818                            );
819                        },
820                        None => {
821                            context
822                                .builder
823                                .substitution_functions
824                                .remove_var(registration, name);
825                        },
826                    };
827                },
828            }
829            return;
830        }
831    }
832
833    match kind {
834        SubstitutionFunctionKind::Var => {
835            let value = match substitution.into_value(
836                url_data,
837                registration,
838                context,
839                Some(PropertyIdRef::from(name)),
840            ) {
841                Ok(v) => v,
842                Err(()) => {
843                    handle_invalid_at_computed_value_time(name, registration, context);
844                    return;
845                },
846            };
847            context
848                .builder
849                .substitution_functions
850                .insert_var(registration, name, value);
851        },
852        SubstitutionFunctionKind::Attr => {
853            let mut value = ComputedRegisteredValue::universal(Arc::new(VariableValue::new(
854                substitution.css.into_owned(),
855                url_data,
856                substitution.first_token_type,
857                substitution.last_token_type,
858            )));
859            value.attr_tainted |= substitution.attr_tainted;
860            context
861                .builder
862                .substitution_functions
863                .insert_attr(name, value);
864        },
865        SubstitutionFunctionKind::Env => unreachable!("Kind cannot be env."),
866    }
867}
868
869/// Computes `css` against the registration of a custom property.
870pub fn compute_value(
871    css: &str,
872    url_data: &UrlExtraData,
873    registration: &PropertyDescriptors,
874    computed_context: &computed::Context,
875    attr_taint: AttrTaint,
876    property_id: Option<PropertyIdRef>,
877) -> Result<ComputedRegisteredValue, ()> {
878    debug_assert!(!registration.is_universal());
879
880    let mut input = Parser::new(css);
881    SpecifiedRegisteredValue::compute(
882        &mut input,
883        registration,
884        url_data,
885        computed_context,
886        AllowComputationallyDependent::Yes,
887        attr_taint,
888        property_id,
889    )
890}
891
892/// Removes the named registered custom property and inserts its uncomputed initial value.
893pub(crate) fn remove_and_insert_initial_value(
894    name: &Name,
895    registration: &PropertyDescriptors,
896    substitution_functions: &mut ComputedSubstitutionFunctions,
897) {
898    substitution_functions.remove_var(registration, name);
899    if let Some(ref initial_value) = registration.initial_value {
900        let value = ComputedRegisteredValue::universal(Arc::clone(initial_value));
901        substitution_functions.insert_var(registration, name, value);
902    }
903}