Skip to main content

style/properties/
cascade.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//! The main cascading algorithm of the style system.
6
7use crate::FxHashMap;
8use crate::applicable_declarations::{CascadePriority, RevertKind};
9use crate::color::AbsoluteColor;
10use crate::computed_value_flags::ComputedValueFlags;
11use crate::context::TreeCountingCaches;
12use crate::custom_properties::{
13    ComputedCustomProperties, ComputedSubstitutionFunctions, Name, NonCustomReferenceMap,
14    SingleNonCustomReference, VariableValue, handle_invalid_at_computed_value_time,
15    remove_and_insert_initial_value, substitute_references_if_needed_and_apply,
16};
17use crate::dom::{AttributeTracker, DummyElementContext, ElementContext, TElement};
18#[cfg(feature = "gecko")]
19use crate::font_metrics::FontMetricsOrientation;
20use crate::properties::{
21    CASCADE_PROPERTY, CSSWideKeyword, ComputedValues, DeclarationImportanceIterator, LonghandId,
22    LonghandIdSet, NonCustomPropertyId, PrioritaryPropertyId, PrioritaryPropertyIdSet,
23    PropertyDeclaration, PropertyDeclarationId, PropertyFlags, PropertyIdRef,
24    ShorthandsWithPropertyReferencesCache, StyleBuilder, property_counts,
25};
26use crate::properties::{CustomDeclaration, CustomDeclarationValue, UnparsedValue};
27use crate::properties_and_values::rule::Descriptors as PropertyDescriptors;
28use crate::properties_and_values::value::ComputedValue as ComputedRegisteredValue;
29use crate::rule_cache::{RuleCache, RuleCacheConditions};
30use crate::rule_tree::{CascadeLevel, CascadeOrigin, RuleCascadeFlags, StrongRuleNode};
31use crate::selector_map::PrecomputedHashMap;
32use crate::selector_parser::PseudoElement;
33use crate::shared_lock::StylesheetGuards;
34use crate::style_adjuster::StyleAdjuster;
35use crate::stylesheets::container_rule::ContainerSizeQuery;
36use crate::stylesheets::layer_rule::LayerOrder;
37use crate::stylist::Stylist;
38use crate::substitution::{
39    ReferenceFlags, References, SubstitutionArgument, SubstitutionFunction,
40    SubstitutionFunctionKind, SubstitutionReplacementContext,
41};
42use crate::values::computed::ToComputedValue;
43#[cfg(feature = "gecko")]
44use crate::values::specified::length::FontBaseSize;
45use crate::values::specified::position::PositionTryFallbacksTryTactic;
46use crate::values::{computed, specified};
47use hashbrown::hash_map::{Entry, EntryRef};
48use selectors::matching::ElementSelectorFlags;
49use servo_arc::Arc;
50use smallvec::SmallVec;
51use std::borrow::Cow;
52use std::cmp;
53
54/// Whether we're resolving a style with the purposes of reparenting for ::first-line.
55#[derive(Copy, Clone)]
56#[allow(missing_docs)]
57pub enum FirstLineReparenting<'a> {
58    No,
59    Yes {
60        /// The style we're re-parenting for ::first-line. ::first-line only affects inherited
61        /// properties so we use this to avoid some work and also ensure correctness by copying the
62        /// reset structs from this style.
63        style_to_reparent: &'a ComputedValues,
64    },
65}
66
67/// Performs the CSS cascade, computing new styles for an element from its parent style.
68///
69/// The arguments are:
70///
71///   * `device`: Used to get the initial viewport and other external state.
72///
73///   * `rule_node`: The rule node in the tree that represent the CSS rules that
74///   matched.
75///
76///   * `parent_style`: The parent style, if applicable; if `None`, this is the root node.
77///
78/// Returns the computed values.
79///   * `flags`: Various flags.
80///
81pub fn cascade<E>(
82    stylist: &Stylist,
83    pseudo: Option<&PseudoElement>,
84    rule_node: &StrongRuleNode,
85    guards: &StylesheetGuards,
86    parent_style: Option<&ComputedValues>,
87    layout_parent_style: Option<&ComputedValues>,
88    first_line_reparenting: FirstLineReparenting,
89    try_tactic: &PositionTryFallbacksTryTactic,
90    visited_rules: Option<&StrongRuleNode>,
91    cascade_input_flags: ComputedValueFlags,
92    included_cascade_flags: RuleCascadeFlags,
93    rule_cache: Option<&RuleCache>,
94    rule_cache_conditions: &mut RuleCacheConditions,
95    element: Option<E>,
96    tree_counting_caches: &mut TreeCountingCaches,
97) -> Arc<ComputedValues>
98where
99    E: TElement,
100{
101    cascade_rules(
102        stylist,
103        pseudo,
104        rule_node,
105        guards,
106        parent_style,
107        layout_parent_style,
108        first_line_reparenting,
109        try_tactic,
110        CascadeMode::Unvisited { visited_rules },
111        cascade_input_flags,
112        included_cascade_flags,
113        rule_cache,
114        rule_cache_conditions,
115        element,
116        tree_counting_caches,
117    )
118}
119
120struct DeclarationIterator<'a> {
121    // Global to the iteration.
122    guards: &'a StylesheetGuards<'a>,
123    restriction: PropertyFlags,
124    // The rule we're iterating over.
125    current_rule_node: Option<&'a StrongRuleNode>,
126    // Per rule state.
127    declarations: DeclarationImportanceIterator<'a>,
128    priority: CascadePriority,
129}
130
131impl<'a> DeclarationIterator<'a> {
132    #[inline]
133    fn new(
134        rule_node: &'a StrongRuleNode,
135        guards: &'a StylesheetGuards,
136        pseudo: Option<&PseudoElement>,
137    ) -> Self {
138        let restriction = pseudo.map_or(PropertyFlags::empty(), |p| p.property_restriction());
139        let mut iter = Self {
140            guards,
141            current_rule_node: Some(rule_node),
142            priority: CascadePriority::new(
143                CascadeLevel::new(CascadeOrigin::UA),
144                LayerOrder::root(),
145                RuleCascadeFlags::empty(),
146            ),
147            declarations: DeclarationImportanceIterator::default(),
148            restriction,
149        };
150        iter.update_for_node(rule_node);
151        iter
152    }
153
154    fn update_for_node(&mut self, node: &'a StrongRuleNode) {
155        self.priority = node.cascade_priority();
156        let guard = self.priority.cascade_level().origin().guard(self.guards);
157        self.declarations = match node.style_source() {
158            Some(source) => source.read(guard).declaration_importance_iter(),
159            None => DeclarationImportanceIterator::default(),
160        };
161    }
162}
163
164impl<'a> Iterator for DeclarationIterator<'a> {
165    type Item = (&'a PropertyDeclaration, CascadePriority);
166
167    #[inline]
168    fn next(&mut self) -> Option<Self::Item> {
169        loop {
170            if let Some((decl, importance)) = self.declarations.next_back() {
171                if self.priority.cascade_level().is_important() != importance.important() {
172                    continue;
173                }
174
175                if !self.restriction.is_empty() {
176                    // decl.id() is either a longhand or a custom
177                    // property.  Custom properties are always allowed, but
178                    // longhands are only allowed if they have our
179                    // restriction flag set.
180                    if let PropertyDeclarationId::Longhand(id) = decl.id()
181                        && !id.flags().contains(self.restriction)
182                        && self.priority.cascade_level().origin() != CascadeOrigin::UA
183                    {
184                        continue;
185                    }
186                }
187
188                return Some((decl, self.priority));
189            }
190
191            let next_node = self.current_rule_node.take()?.parent()?;
192            self.current_rule_node = Some(next_node);
193            self.update_for_node(next_node);
194        }
195    }
196}
197
198fn cascade_rules<E>(
199    stylist: &Stylist,
200    pseudo: Option<&PseudoElement>,
201    rule_node: &StrongRuleNode,
202    guards: &StylesheetGuards,
203    parent_style: Option<&ComputedValues>,
204    layout_parent_style: Option<&ComputedValues>,
205    first_line_reparenting: FirstLineReparenting,
206    try_tactic: &PositionTryFallbacksTryTactic,
207    cascade_mode: CascadeMode,
208    cascade_input_flags: ComputedValueFlags,
209    included_cascade_flags: RuleCascadeFlags,
210    rule_cache: Option<&RuleCache>,
211    rule_cache_conditions: &mut RuleCacheConditions,
212    element: Option<E>,
213    tree_counting_caches: &mut TreeCountingCaches,
214) -> Arc<ComputedValues>
215where
216    E: TElement,
217{
218    apply_declarations(
219        stylist,
220        pseudo,
221        rule_node,
222        guards,
223        DeclarationIterator::new(rule_node, guards, pseudo),
224        parent_style,
225        layout_parent_style,
226        first_line_reparenting,
227        try_tactic,
228        cascade_mode,
229        cascade_input_flags,
230        included_cascade_flags,
231        rule_cache,
232        rule_cache_conditions,
233        element,
234        tree_counting_caches,
235    )
236}
237
238/// Whether we're cascading for visited or unvisited styles.
239#[derive(Clone, Copy)]
240pub enum CascadeMode<'a, 'b> {
241    /// We're cascading for unvisited styles.
242    Unvisited {
243        /// The visited rules that should match the visited style.
244        visited_rules: Option<&'a StrongRuleNode>,
245    },
246    /// We're cascading for visited styles.
247    Visited {
248        /// The cascade for our unvisited style.
249        unvisited_context: &'a computed::Context<'b>,
250    },
251}
252
253fn iter_declarations<'c, 'decls: 'c>(
254    iter: impl Iterator<Item = (&'decls PropertyDeclaration, CascadePriority)>,
255    declarations: &mut Declarations<'decls>,
256    mut custom: Option<(&mut Cascade<'c>, &mut computed::Context)>,
257) {
258    for (declaration, priority) in iter {
259        if let PropertyDeclaration::Custom(ref declaration) = *declaration {
260            if let Some((ref mut cascade, ref mut context)) = custom {
261                cascade.cascade_custom_property(context, declaration, priority);
262            }
263        } else {
264            let id = declaration.id().as_longhand().unwrap();
265            declarations.note_declaration(declaration, priority, id);
266            if Cascade::might_have_non_custom_or_attr_dependency(id, declaration)
267                && let Some((ref mut cascade, ref mut context)) = custom
268            {
269                cascade.maybe_note_non_custom_dependency(context, id, declaration);
270            }
271        }
272    }
273}
274
275/// NOTE: This function expects the declaration with more priority to appear
276/// first.
277pub fn apply_declarations<'decls, E, I>(
278    stylist: &Stylist,
279    pseudo: Option<&PseudoElement>,
280    rules: &StrongRuleNode,
281    guards: &StylesheetGuards,
282    iter: I,
283    parent_style: Option<&ComputedValues>,
284    layout_parent_style: Option<&ComputedValues>,
285    first_line_reparenting: FirstLineReparenting<'_>,
286    try_tactic: &PositionTryFallbacksTryTactic,
287    cascade_mode: CascadeMode,
288    cascade_input_flags: ComputedValueFlags,
289    included_cascade_flags: RuleCascadeFlags,
290    rule_cache: Option<&RuleCache>,
291    rule_cache_conditions: &mut RuleCacheConditions,
292    element: Option<E>,
293    tree_counting_caches: &mut TreeCountingCaches,
294) -> Arc<ComputedValues>
295where
296    E: TElement,
297    I: Iterator<Item = (&'decls PropertyDeclaration, CascadePriority)>,
298{
299    debug_assert!(layout_parent_style.is_none() || parent_style.is_some());
300    let device = stylist.device();
301    let inherited_style = parent_style.unwrap_or(device.default_computed_values());
302    let is_root_element = pseudo.is_none() && element.is_some_and(|e| e.is_root());
303    let container_size_query =
304        ContainerSizeQuery::for_option_element(element, Some(inherited_style), pseudo.is_some());
305
306    let originating_element = element.map(|e| e.ultimate_originating_element());
307    let element_context = match originating_element {
308        Some(ref e) => e as &dyn ElementContext,
309        None => &DummyElementContext {},
310    };
311
312    let mut context = computed::Context::new(
313        // We'd really like to own the rules here to avoid refcount traffic, but
314        // animation's usage of `apply_declarations` make this tricky. See bug
315        // 1375525.
316        StyleBuilder::new(
317            device,
318            Some(stylist),
319            parent_style,
320            pseudo,
321            Some(rules.clone()),
322            is_root_element,
323        ),
324        stylist.quirks_mode(),
325        rule_cache_conditions,
326        container_size_query,
327        included_cascade_flags,
328        element_context,
329        tree_counting_caches,
330    );
331
332    context.style().add_flags(cascade_input_flags);
333    // Reuse flags from computing registered custom properties initial values, such as
334    // whether they depend on viewport units.
335    context
336        .style()
337        .add_flags(stylist.get_custom_property_initial_values_flags());
338
339    let using_cached_reset_properties;
340    let ignore_colors = context.builder.device.forced_colors().is_active();
341    let mut cascade = Cascade::new(first_line_reparenting, stylist, ignore_colors);
342    let mut declarations = Default::default();
343    let mut shorthand_cache = ShorthandsWithPropertyReferencesCache::default();
344    let mut attribute_tracker = AttributeTracker::new(element_context);
345
346    let properties_to_apply = match cascade_mode {
347        CascadeMode::Visited { unvisited_context } => {
348            context.builder.substitution_functions =
349                unvisited_context.builder.substitution_functions.clone();
350            context.builder.writing_mode = unvisited_context.builder.writing_mode;
351            context.builder.color_scheme = unvisited_context.builder.color_scheme;
352            // We never insert visited styles into the cache so we don't need to try looking it up.
353            // It also wouldn't be super-profitable, only a handful :visited properties are
354            // non-inherited.
355            using_cached_reset_properties = false;
356            // If we match the same rules when visited and unvisited, and we know there isn't any
357            // visited-dependent properties, we can avoid gathering the declarations, we know none
358            // would be relevant.
359            if unvisited_context.builder.rules.as_ref() != Some(rules)
360                || unvisited_context
361                    .builder
362                    .flags()
363                    .intersects(ComputedValueFlags::USES_VISITED_DEPENDENT_PROPERTIES)
364            {
365                iter_declarations(iter, &mut declarations, None);
366            }
367            LonghandIdSet::visited_dependent()
368        },
369        CascadeMode::Unvisited { .. } => {
370            cascade.init_custom_properties(&mut context);
371            iter_declarations(iter, &mut declarations, Some((&mut cascade, &mut context)));
372            // Detect cycles, remove properties participating in them, and resolve custom
373            // properties, applying prioritary properties (font-size, color-scheme, line-height)
374            // interleaved so that a custom property depending on `em`/`lh`/the used color-scheme is
375            // substituted once the prioritary property it needs has been applied.
376            cascade.apply_custom_and_prioritary_properties(
377                &mut context,
378                &declarations,
379                &mut shorthand_cache,
380                &mut attribute_tracker,
381            );
382
383            using_cached_reset_properties =
384                cascade.try_to_use_cached_reset_properties(&mut context, rule_cache, guards);
385
386            if using_cached_reset_properties {
387                LonghandIdSet::late_group_only_inherited()
388            } else {
389                LonghandIdSet::late_group()
390            }
391        },
392    };
393
394    cascade.apply_non_prioritary_properties(
395        &mut context,
396        &declarations.longhand_declarations,
397        &mut shorthand_cache,
398        properties_to_apply,
399        &mut attribute_tracker,
400    );
401
402    context.builder.attribute_references = attribute_tracker.finalize();
403
404    cascade.finished_applying_properties(&mut context.builder);
405
406    context.builder.clear_modified_reset();
407
408    if let CascadeMode::Unvisited { visited_rules } = cascade_mode {
409        // NOTE: This relies on finished_applying_properties() having already happened.
410        if let Some(visited_rules) = visited_rules {
411            cascade.compute_visited_style_if_needed(
412                &mut context,
413                element,
414                parent_style,
415                layout_parent_style,
416                try_tactic,
417                visited_rules,
418                guards,
419            );
420        }
421
422        StyleAdjuster::new(&mut context.builder).adjust(
423            layout_parent_style.unwrap_or(inherited_style),
424            element,
425            try_tactic,
426            &cascade.author_or_user_specified,
427        );
428    }
429
430    if context.builder.modified_reset() || using_cached_reset_properties {
431        // If we adjusted any reset structs, we can't cache this ComputedValues.
432        //
433        // Also, if we re-used existing reset structs, don't bother caching it back again. (Aside
434        // from being wasted effort, it will be wrong, since context.rule_cache_conditions won't be
435        // set appropriately if we didn't compute those reset properties.)
436        context.rule_cache_conditions.borrow_mut().set_uncacheable();
437    }
438
439    if context
440        .builder
441        .flags()
442        .intersects(ComputedValueFlags::tree_counting_function_flags())
443    {
444        if let Some(el) = element {
445            el.apply_selector_flags(ElementSelectorFlags::MAY_HAVE_TREE_COUNTING_FUNCTION);
446        } else {
447            debug_assert!(
448                false,
449                "Tree counting function flag applied without an element?"
450            );
451        }
452    }
453
454    context.builder.build()
455}
456
457/// For ignored colors mode, we sometimes want to do something equivalent to
458/// "revert-or-initial", where we `revert` for a given origin, but then apply a
459/// given initial value if nothing in other origins did override it.
460///
461/// This is a bit of a clunky way of achieving this.
462type DeclarationsToApplyUnlessOverriden = SmallVec<[PropertyDeclaration; 2]>;
463
464fn is_base_appearance(context: &computed::Context) -> bool {
465    use computed::Appearance;
466    let box_style = context.builder.get_box();
467    match *box_style.get_appearance() {
468        Appearance::BaseSelect => {
469            matches!(
470                box_style.get__moz_default_appearance(),
471                Appearance::Listbox | Appearance::Menulist
472            )
473        },
474        Appearance::Base => *box_style.get__moz_default_appearance() != Appearance::None,
475        _ => false,
476    }
477}
478
479fn tweak_when_ignoring_colors(
480    context: &computed::Context,
481    longhand_id: LonghandId,
482    origin: CascadeOrigin,
483    declaration: &mut Cow<PropertyDeclaration>,
484    declarations_to_apply_unless_overridden: &mut DeclarationsToApplyUnlessOverriden,
485) {
486    use crate::values::computed::ToComputedValue;
487    use crate::values::specified::Color;
488
489    if !longhand_id.ignored_when_document_colors_disabled() {
490        return;
491    }
492
493    let is_ua_or_user_rule = matches!(origin, CascadeOrigin::User | CascadeOrigin::UA);
494    if is_ua_or_user_rule {
495        return;
496    }
497
498    // Always honor colors if forced-color-adjust is set to none.
499    let forced = *context
500        .builder
501        .get_inherited_text()
502        .get_forced_color_adjust();
503    if forced == computed::ForcedColorAdjust::None {
504        return;
505    }
506
507    fn alpha_channel(color: &Color, context: &computed::Context) -> f32 {
508        // We assume here currentColor is opaque.
509        color
510            .to_computed_value(context)
511            .resolve_to_absolute(&AbsoluteColor::BLACK)
512            .alpha
513    }
514
515    // A few special-cases ahead.
516    match **declaration {
517        // Honor CSS-wide keywords like unset / revert / initial...
518        PropertyDeclaration::CSSWideKeyword(..) => return,
519        PropertyDeclaration::BackgroundColor(ref color) => {
520            // We honor system colors and transparent colors unconditionally.
521            //
522            // NOTE(emilio): We honor transparent unconditionally, like we do
523            // for color, even though it causes issues like bug 1625036. The
524            // reasoning is that the conditions that trigger that (having
525            // mismatched widget and default backgrounds) are both uncommon, and
526            // broken in other applications as well, and not honoring
527            // transparent makes stuff uglier or break unconditionally
528            // (bug 1666059, bug 1755713).
529            if color.honored_in_forced_colors_mode(context, /* allow_transparent = */ true) {
530                return;
531            }
532            // For background-color, we revert or initial-with-preserved-alpha
533            // otherwise, this is needed to preserve semi-transparent
534            // backgrounds.
535            let alpha = alpha_channel(color, context);
536            if alpha == 0.0 {
537                return;
538            }
539            let mut color = context.builder.device.default_background_color();
540            color.alpha = alpha;
541            declarations_to_apply_unless_overridden
542                .push(PropertyDeclaration::BackgroundColor(color.into()))
543        },
544        PropertyDeclaration::Color(ref color) => {
545            // We honor color: transparent and system colors.
546            if color
547                .0
548                .honored_in_forced_colors_mode(context, /* allow_transparent = */ true)
549            {
550                return;
551            }
552            // If the inherited color would be transparent, but we would
553            // override this with a non-transparent color, then override it with
554            // the default color. Otherwise just let it inherit through.
555            if context
556                .builder
557                .get_parent_inherited_text()
558                .get_color()
559                .alpha
560                == 0.0
561            {
562                let color = context.builder.device.default_color();
563                declarations_to_apply_unless_overridden.push(PropertyDeclaration::Color(
564                    specified::ColorPropertyValue(color.into()),
565                ))
566            }
567        },
568        // We honor url background-images if backplating.
569        #[cfg(feature = "gecko")]
570        PropertyDeclaration::BackgroundImage(ref bkg) => {
571            use crate::values::generics::image::Image;
572            if crate::pref!("browser.display.permit_backplate")
573                && bkg
574                    .0
575                    .iter()
576                    .all(|image| matches!(*image, Image::Url(..) | Image::None))
577            {
578                return;
579            }
580        },
581        _ => {
582            // We honor system colors more generally for all colors.
583            //
584            // We used to honor transparent but that causes accessibility
585            // regressions like bug 1740924.
586            //
587            // NOTE(emilio): This doesn't handle caret-color and accent-color
588            // because those use a slightly different syntax (<color> | auto for
589            // example).
590            //
591            // That's probably fine though, as using a system color for
592            // caret-color doesn't make sense (using currentColor is fine), and
593            // we ignore accent-color in high-contrast-mode anyways.
594            if let Some(color) = declaration.color_value()
595                && color
596                    .honored_in_forced_colors_mode(context, /* allow_transparent = */ false)
597            {
598                return;
599            }
600        },
601    }
602
603    *declaration.to_mut() =
604        PropertyDeclaration::css_wide_keyword(longhand_id, CSSWideKeyword::Revert);
605}
606
607/// We track the index only for prioritary properties. For other properties we can just iterate.
608type DeclarationIndex = u16;
609
610/// "Prioritary" properties are properties that other properties depend on in one way or another.
611///
612/// We keep track of their position in the declaration vector, in order to be able to cascade them
613/// separately in precise order.
614#[derive(Copy, Clone)]
615struct PrioritaryDeclarationPosition {
616    // DeclarationIndex::MAX signals no index.
617    most_important: DeclarationIndex,
618    least_important: DeclarationIndex,
619}
620
621impl Default for PrioritaryDeclarationPosition {
622    fn default() -> Self {
623        Self {
624            most_important: DeclarationIndex::MAX,
625            least_important: DeclarationIndex::MAX,
626        }
627    }
628}
629
630#[derive(Copy, Clone)]
631struct Declaration<'a> {
632    decl: &'a PropertyDeclaration,
633    priority: CascadePriority,
634    next_index: DeclarationIndex,
635}
636
637/// The set of property declarations from our rules.
638#[derive(Default)]
639pub(crate) struct Declarations<'a> {
640    /// Whether we have any prioritary property. This is just a minor optimization.
641    has_prioritary_properties: bool,
642    /// A list of all the applicable longhand declarations.
643    longhand_declarations: SmallVec<[Declaration<'a>; 64]>,
644    /// The prioritary property position data.
645    prioritary_positions: [PrioritaryDeclarationPosition; property_counts::PRIORITARY],
646}
647
648impl<'a> Declarations<'a> {
649    fn note_prioritary_property(&mut self, id: PrioritaryPropertyId) {
650        let new_index = self.longhand_declarations.len();
651        if new_index >= DeclarationIndex::MAX as usize {
652            // This prioritary property is past the amount of declarations we can track. Let's give
653            // up applying it to prevent getting confused.
654            return;
655        }
656
657        self.has_prioritary_properties = true;
658        let new_index = new_index as DeclarationIndex;
659        let position = &mut self.prioritary_positions[id as usize];
660        if position.most_important == DeclarationIndex::MAX {
661            // We still haven't seen this property, record the current position as the most
662            // prioritary index.
663            position.most_important = new_index;
664        } else {
665            // Let the previous item in the list know about us.
666            self.longhand_declarations[position.least_important as usize].next_index = new_index;
667        }
668        position.least_important = new_index;
669    }
670
671    fn note_declaration(
672        &mut self,
673        decl: &'a PropertyDeclaration,
674        priority: CascadePriority,
675        id: LonghandId,
676    ) {
677        if let Some(id) = PrioritaryPropertyId::from_longhand(id) {
678            self.note_prioritary_property(id);
679        }
680        self.longhand_declarations.push(Declaration {
681            decl,
682            priority,
683            next_index: 0,
684        });
685    }
686}
687
688#[derive(Default)]
689struct RevertedSet {
690    // Just to avoid the hashmap lookup in the common case.
691    longhands_set: LonghandIdSet,
692    longhands: FxHashMap<LonghandId, (CascadePriority, RevertKind)>,
693    custom: PrecomputedHashMap<Name, (CascadePriority, RevertKind)>,
694}
695
696#[derive(Default)]
697struct SeenSubstitutionFunctions<'a> {
698    /// The boolean means whether the value may have references. If false, we don't need to bother
699    /// performing lookups for cycle detection.
700    var: PrecomputedHashMap<&'a Name, bool>,
701    /// The non-custom declarations with `attr()` references.
702    attr: Vec<(LonghandId, Arc<UnparsedValue>)>,
703}
704
705#[derive(Default)]
706struct SeenSet<'a> {
707    longhands: LonghandIdSet,
708    custom: SeenSubstitutionFunctions<'a>,
709}
710
711/// Only registered (typed) properties emit a non-custom edge, from their own value.
712fn find_non_custom_references(
713    registration: &PropertyDescriptors,
714    value: &VariableValue,
715    is_root_element: bool,
716) -> ReferenceFlags {
717    use crate::properties_and_values::syntax::data_type::DependentDataTypes;
718
719    let mut result = ReferenceFlags::empty();
720    let Some(syntax) = registration.syntax.as_ref() else {
721        return result;
722    };
723    let dependent_types = syntax.dependent_types();
724    let may_reference_length = dependent_types.intersects(DependentDataTypes::LENGTH);
725    if may_reference_length {
726        result |= value.references.non_custom_references(is_root_element);
727    }
728    if dependent_types.intersects(DependentDataTypes::COLOR) {
729        // The value depends on the used color-scheme (e.g. a `<color>` property referencing
730        // `light-dark()` or a system color).
731        result |= ReferenceFlags::COLOR_SCHEME;
732    }
733    result
734}
735
736/// Resolves the custom properties for a single `@keyframes` keyframe, layered on top of the base
737/// style's already-computed custom properties.
738///
739/// `@keyframes` aren't part of the regular cascade (see bug 1883255), so this lets the caller seed
740/// the substitution map with the element's computed custom properties, cascade the keyframe's
741/// custom declarations on top, and resolve them (running cycle detection and substitution) into
742/// `context.builder.substitution_functions`, which the subsequent animation-value computation reads
743/// to substitute `var()` references.
744pub struct KeyframeCustomPropertiesBuilder<'a> {
745    cascade: Cascade<'a>,
746    decls: Declarations<'a>,
747    shorthand_cache: ShorthandsWithPropertyReferencesCache,
748}
749
750impl<'a> KeyframeCustomPropertiesBuilder<'a> {
751    /// Creates a new builder, seeding the substitution map with `base` (typically the element's
752    /// computed custom properties).
753    pub fn new(
754        stylist: &'a Stylist,
755        context: &mut computed::Context,
756        base: ComputedCustomProperties,
757    ) -> Self {
758        context.builder.substitution_functions =
759            ComputedSubstitutionFunctions::new(Some(base), None);
760        Self {
761            cascade: Cascade::new_for_custom_properties_only(stylist),
762            decls: Declarations::default(),
763            shorthand_cache: ShorthandsWithPropertyReferencesCache::default(),
764        }
765    }
766
767    /// Cascades a single custom-property declaration from the keyframe.
768    pub fn cascade(
769        &mut self,
770        context: &mut computed::Context,
771        declaration: &'a CustomDeclaration,
772        priority: CascadePriority,
773    ) {
774        self.cascade
775            .cascade_custom_property(context, declaration, priority);
776    }
777
778    /// Resolves the cascaded custom properties into `context.builder.substitution_functions`.
779    pub fn build(
780        mut self,
781        context: &mut computed::Context,
782        attribute_tracker: &mut AttributeTracker,
783    ) {
784        self.cascade.apply_custom_and_prioritary_properties(
785            context,
786            &self.decls,
787            &mut self.shorthand_cache,
788            attribute_tracker,
789        );
790    }
791}
792
793pub(crate) struct Cascade<'a> {
794    first_line_reparenting: FirstLineReparenting<'a>,
795    stylist: &'a Stylist,
796    ignore_colors: bool,
797    seen: SeenSet<'a>,
798    reverted: RevertedSet,
799    author_or_user_specified: LonghandIdSet,
800    declarations_to_apply_unless_overridden: DeclarationsToApplyUnlessOverriden,
801    may_have_custom_property_cycles: bool,
802    references_from_non_custom_properties: NonCustomReferenceMap<Vec<Arc<UnparsedValue>>>,
803    /// Set of prioritary properties that have already been applied.
804    ensured_prioritary: PrioritaryPropertyIdSet,
805}
806
807impl<'a> Cascade<'a> {
808    fn new(
809        first_line_reparenting: FirstLineReparenting<'a>,
810        stylist: &'a Stylist,
811        ignore_colors: bool,
812    ) -> Self {
813        Self {
814            first_line_reparenting,
815            stylist,
816            ignore_colors,
817            seen: Default::default(),
818            author_or_user_specified: Default::default(),
819            reverted: Default::default(),
820            declarations_to_apply_unless_overridden: Default::default(),
821            may_have_custom_property_cycles: false,
822            ensured_prioritary: PrioritaryPropertyIdSet::default(),
823            references_from_non_custom_properties: Default::default(),
824        }
825    }
826
827    /// Creates a `Cascade` for resolving custom properties outside of a full cascade (e.g. for
828    /// keyframes). The visited-style and position-try paths aren't reachable in this mode.
829    fn new_for_custom_properties_only(stylist: &'a Stylist) -> Self {
830        Self {
831            first_line_reparenting: FirstLineReparenting::No,
832            stylist,
833            ignore_colors: false,
834            seen: Default::default(),
835            author_or_user_specified: Default::default(),
836            reverted: Default::default(),
837            declarations_to_apply_unless_overridden: Default::default(),
838            may_have_custom_property_cycles: false,
839            ensured_prioritary: PrioritaryPropertyIdSet::default(),
840            references_from_non_custom_properties: Default::default(),
841        }
842    }
843
844    fn substitute_variables_if_needed<'cache, 'decl>(
845        &self,
846        context: &mut computed::Context,
847        shorthand_cache: &'cache mut ShorthandsWithPropertyReferencesCache,
848        declaration: &'decl PropertyDeclaration,
849        attribute_tracker: &mut AttributeTracker,
850    ) -> Cow<'decl, PropertyDeclaration>
851    where
852        'cache: 'decl,
853    {
854        let declaration = match *declaration {
855            PropertyDeclaration::WithVariables(ref declaration) => declaration,
856            ref d => return Cow::Borrowed(d),
857        };
858
859        if !declaration.id.inherited() {
860            context.rule_cache_conditions.borrow_mut().set_uncacheable();
861
862            // NOTE(emilio): We only really need to add the `display` /
863            // `content` flag if the CSS variable has not been specified on our
864            // declarations, but we don't have that information at this point,
865            // and it doesn't seem like an important enough optimization to
866            // warrant it.
867            if matches!(declaration.id, LonghandId::Display | LonghandId::Content) {
868                context
869                    .builder
870                    .add_flags(ComputedValueFlags::DISPLAY_OR_CONTENT_DEPEND_ON_INHERITED_STYLE);
871            }
872        }
873
874        debug_assert!(
875            context.builder.stylist.is_some(),
876            "Need a Stylist to substitute variables!"
877        );
878        declaration.value.substitute_variables(
879            declaration.id,
880            context.builder.substitution_functions(),
881            context.builder.stylist.unwrap(),
882            context,
883            shorthand_cache,
884            attribute_tracker,
885        )
886    }
887
888    fn apply_one_prioritary_property(
889        &mut self,
890        context: &mut computed::Context,
891        decls: &Declarations,
892        cache: &mut ShorthandsWithPropertyReferencesCache,
893        id: PrioritaryPropertyId,
894        attr_provider: &mut AttributeTracker,
895    ) {
896        let mut index = decls.prioritary_positions[id as usize].most_important;
897        if index == DeclarationIndex::MAX {
898            return;
899        }
900
901        let longhand_id = id.to_longhand();
902        debug_assert!(
903            !longhand_id.is_logical(),
904            "That could require more book-keeping"
905        );
906        loop {
907            let decl = decls.longhand_declarations[index as usize];
908            self.apply_one_longhand(
909                context,
910                longhand_id,
911                decl.decl,
912                decl.priority,
913                cache,
914                attr_provider,
915            );
916            if self.seen.longhands.contains(longhand_id) {
917                // Found it!
918                self.did_apply_prioritary_property(context, id);
919                return;
920            }
921            debug_assert!(
922                decl.next_index == 0 || decl.next_index > index,
923                "should make progress! {} -> {}",
924                index,
925                decl.next_index,
926            );
927            index = decl.next_index;
928            if index == 0 {
929                return;
930            }
931        }
932    }
933
934    /// Some prioritary properties need book-keeping, which this takes care of.
935    fn did_apply_prioritary_property(
936        &mut self,
937        context: &mut computed::Context,
938        id: PrioritaryPropertyId,
939    ) {
940        use crate::properties::PrioritaryPropertyId::*;
941        match id {
942            Appearance => {
943                if is_base_appearance(context) {
944                    context
945                        .style()
946                        .add_flags(ComputedValueFlags::IS_IN_APPEARANCE_BASE_SUBTREE);
947                    context
948                        .included_cascade_flags
949                        .insert(RuleCascadeFlags::APPEARANCE_BASE);
950                }
951            },
952            WritingMode | Direction | TextOrientation => {
953                context.builder.writing_mode =
954                    crate::logical_geometry::WritingMode::new(context.builder.get_inherited_box());
955            },
956            Zoom => {
957                context.builder.recompute_effective_zooms();
958                if !context.builder.effective_zoom_for_inheritance.is_one() {
959                    // NOTE(emilio): This is a bit of a hack, but matches the shipped WebKit and Blink
960                    // behavior for now. Ideally, in the future, we have a pass over all
961                    // implicitly-or-explicitly-inherited properties that can contain lengths and
962                    // re-compute them properly, see https://github.com/w3c/csswg-drafts/issues/9397.
963                    // TODO(emilio): we need to eagerly do this for line-height as well, probably.
964                    self.recompute_font_size_for_zoom_change(&mut context.builder);
965                }
966            },
967            XLang => {
968                #[cfg(feature = "gecko")]
969                self.recompute_initial_font_family_if_needed(&mut context.builder);
970                self.recompute_keyword_font_size_if_needed(context);
971            },
972            FontFamily => {
973                #[cfg(feature = "gecko")]
974                self.prioritize_user_fonts_if_needed(&mut context.builder);
975                self.recompute_keyword_font_size_if_needed(context);
976            },
977            FontSize => {
978                if self.seen.longhands.contains(LonghandId::MathDepth) {
979                    #[cfg(feature = "gecko")]
980                    Self::recompute_math_font_size_if_needed(context);
981                }
982                if self.seen.longhands.contains(LonghandId::XLang)
983                    || self.seen.longhands.contains(LonghandId::FontFamily)
984                {
985                    self.recompute_keyword_font_size_if_needed(context);
986                }
987                #[cfg(feature = "gecko")]
988                self.constrain_font_size_if_needed(&mut context.builder);
989            },
990            XTextScale => {
991                #[cfg(feature = "gecko")]
992                self.unzoom_fonts_if_needed(&mut context.builder);
993            },
994            MozMinFontSizeRatio => {
995                #[cfg(feature = "gecko")]
996                self.constrain_font_size_if_needed(&mut context.builder);
997            },
998            ColorScheme => {
999                context.builder.color_scheme =
1000                    context.builder.get_inherited_ui().color_scheme_bits();
1001            },
1002            MozDefaultAppearance | MathDepth | FontWeight | FontWidth | FontStyle
1003            | FontSizeAdjust | ForcedColorAdjust | LineHeight => {},
1004        }
1005    }
1006
1007    fn apply_non_prioritary_properties(
1008        &mut self,
1009        context: &mut computed::Context,
1010        longhand_declarations: &[Declaration],
1011        shorthand_cache: &mut ShorthandsWithPropertyReferencesCache,
1012        properties_to_apply: &LonghandIdSet,
1013        attribute_tracker: &mut AttributeTracker,
1014    ) {
1015        debug_assert!(!properties_to_apply.contains_any(LonghandIdSet::prioritary_properties()));
1016        debug_assert!(self.declarations_to_apply_unless_overridden.is_empty());
1017        for declaration in longhand_declarations {
1018            let mut longhand_id = declaration.decl.id().as_longhand().unwrap();
1019            if !properties_to_apply.contains(longhand_id) {
1020                continue;
1021            }
1022            debug_assert!(PrioritaryPropertyId::from_longhand(longhand_id).is_none());
1023            let is_logical = longhand_id.is_logical();
1024            if is_logical {
1025                let wm = context.builder.writing_mode;
1026                context
1027                    .rule_cache_conditions
1028                    .borrow_mut()
1029                    .set_writing_mode_dependency(wm);
1030                longhand_id = longhand_id.to_physical(wm);
1031            }
1032            self.apply_one_longhand(
1033                context,
1034                longhand_id,
1035                declaration.decl,
1036                declaration.priority,
1037                shorthand_cache,
1038                attribute_tracker,
1039            );
1040        }
1041        if !self.declarations_to_apply_unless_overridden.is_empty() {
1042            debug_assert!(self.ignore_colors);
1043            for declaration in std::mem::take(&mut self.declarations_to_apply_unless_overridden) {
1044                let longhand_id = declaration.id().as_longhand().unwrap();
1045                debug_assert!(!longhand_id.is_logical());
1046                if !self.seen.longhands.contains(longhand_id) {
1047                    unsafe {
1048                        self.do_apply_declaration(context, longhand_id, &declaration);
1049                    }
1050                }
1051            }
1052        }
1053
1054        if !context.builder.effective_zoom_for_inheritance.is_one() {
1055            self.recompute_zoom_dependent_inherited_lengths(context);
1056        }
1057    }
1058
1059    #[cold]
1060    fn recompute_zoom_dependent_inherited_lengths(&self, context: &mut computed::Context) {
1061        debug_assert!(self.seen.longhands.contains(LonghandId::Zoom));
1062        for prop in LonghandIdSet::zoom_dependent_inherited_properties().iter() {
1063            if self.seen.longhands.contains(prop) {
1064                continue;
1065            }
1066            let declaration = PropertyDeclaration::css_wide_keyword(prop, CSSWideKeyword::Inherit);
1067            unsafe {
1068                self.do_apply_declaration(context, prop, &declaration);
1069            }
1070        }
1071    }
1072
1073    fn apply_one_longhand(
1074        &mut self,
1075        context: &mut computed::Context,
1076        longhand_id: LonghandId,
1077        declaration: &PropertyDeclaration,
1078        priority: CascadePriority,
1079        cache: &mut ShorthandsWithPropertyReferencesCache,
1080        attribute_tracker: &mut AttributeTracker,
1081    ) {
1082        debug_assert!(!longhand_id.is_logical());
1083        if self.seen.longhands.contains(longhand_id) {
1084            return;
1085        }
1086
1087        if !(priority.flags() - context.included_cascade_flags).is_empty() {
1088            return;
1089        }
1090
1091        if self.reverted.longhands_set.contains(longhand_id)
1092            && let Some(&(reverted_priority, revert_kind)) =
1093                self.reverted.longhands.get(&longhand_id)
1094            && !reverted_priority.allows_when_reverted(&priority, revert_kind)
1095        {
1096            return;
1097        }
1098
1099        let mut declaration =
1100            self.substitute_variables_if_needed(context, cache, declaration, attribute_tracker);
1101
1102        // When document colors are disabled, do special handling of
1103        // properties that are marked as ignored in that mode.
1104        let origin = priority.cascade_level().origin();
1105        if self.ignore_colors {
1106            tweak_when_ignoring_colors(
1107                context,
1108                longhand_id,
1109                origin,
1110                &mut declaration,
1111                &mut self.declarations_to_apply_unless_overridden,
1112            );
1113        }
1114        let can_skip_apply = match declaration.get_css_wide_keyword() {
1115            Some(keyword) => {
1116                if let Some(revert_kind) = keyword.revert_kind() {
1117                    // We intentionally don't want to insert it into
1118                    // `self.seen.longhands`, `reverted` takes care of rejecting
1119                    // other declarations as needed.
1120                    self.reverted.longhands_set.insert(longhand_id);
1121                    self.reverted
1122                        .longhands
1123                        .insert(longhand_id, (priority, revert_kind));
1124                    return;
1125                }
1126
1127                let inherited = longhand_id.inherited();
1128                let zoomed = !context.builder.effective_zoom_for_inheritance.is_one()
1129                    && longhand_id.zoom_dependent();
1130                match keyword {
1131                    CSSWideKeyword::Revert
1132                    | CSSWideKeyword::RevertLayer
1133                    | CSSWideKeyword::RevertRule => unreachable!(),
1134                    CSSWideKeyword::Unset => !zoomed || !inherited,
1135                    CSSWideKeyword::Inherit => inherited && !zoomed,
1136                    CSSWideKeyword::Initial => !inherited,
1137                }
1138            },
1139            None => false,
1140        };
1141
1142        self.seen.longhands.insert(longhand_id);
1143        if origin != CascadeOrigin::UA {
1144            self.author_or_user_specified.insert(longhand_id);
1145        }
1146
1147        if !can_skip_apply {
1148            // Set context.scope to this declaration's cascade level so that
1149            // tree-scoped properties (anchor-name, position-anchor, anchor-scope)
1150            // get the correct scope when converted to computed values.
1151            let old_scope = context.scope;
1152            let cascade_level = priority.cascade_level();
1153            context.scope = cascade_level;
1154            unsafe { self.do_apply_declaration(context, longhand_id, &declaration) }
1155            context.scope = old_scope;
1156        }
1157    }
1158
1159    #[inline]
1160    unsafe fn do_apply_declaration(
1161        &self,
1162        context: &mut computed::Context,
1163        longhand_id: LonghandId,
1164        declaration: &PropertyDeclaration,
1165    ) {
1166        debug_assert!(!longhand_id.is_logical());
1167        unsafe {
1168            // We could (and used to) use a pattern match here, but that bloats this
1169            // function to over 100K of compiled code!
1170            //
1171            // To improve i-cache behavior, we outline the individual functions and
1172            // use virtual dispatch instead.
1173            (CASCADE_PROPERTY[longhand_id as usize])(declaration, context);
1174        }
1175    }
1176
1177    // `RefCell<&mut T>::borrow_mut()` needs the explicit `&mut *` to get back
1178    // to `&mut T`; clippy's needless_borrow / explicit_auto_deref both
1179    // misfire on this double indirection and suggest incorrect rewrites.
1180    #[allow(clippy::needless_borrow, clippy::explicit_auto_deref)]
1181    fn compute_visited_style_if_needed<E>(
1182        &self,
1183        context: &mut computed::Context,
1184        element: Option<E>,
1185        parent_style: Option<&ComputedValues>,
1186        layout_parent_style: Option<&ComputedValues>,
1187        try_tactic: &PositionTryFallbacksTryTactic,
1188        visited_rules: &StrongRuleNode,
1189        guards: &StylesheetGuards,
1190    ) where
1191        E: TElement,
1192    {
1193        let is_link = context.builder.pseudo.is_none() && element.unwrap().is_link();
1194
1195        macro_rules! visited_parent {
1196            ($parent:expr) => {
1197                if is_link {
1198                    $parent
1199                } else {
1200                    $parent.map(|p| p.visited_style().unwrap_or(p))
1201                }
1202            };
1203        }
1204
1205        // We could call apply_declarations directly, but that'd cause
1206        // another instantiation of this function which is not great.
1207        let style = cascade_rules(
1208            context.builder.stylist.unwrap(),
1209            context.builder.pseudo,
1210            visited_rules,
1211            guards,
1212            visited_parent!(parent_style),
1213            visited_parent!(layout_parent_style),
1214            self.first_line_reparenting,
1215            try_tactic,
1216            CascadeMode::Visited {
1217                unvisited_context: &*context,
1218            },
1219            // Cascade input flags don't matter for the visited style, they are
1220            // in the main (unvisited) style.
1221            Default::default(),
1222            context.included_cascade_flags,
1223            // The rule cache doesn't care about caching :visited
1224            // styles, we cache the unvisited style instead. We still do
1225            // need to set the caching dependencies properly if present
1226            // though, so the cache conditions need to match.
1227            None, // rule_cache
1228            &mut *context.rule_cache_conditions.borrow_mut(),
1229            element,
1230            &mut *context.tree_counting_caches.borrow_mut(),
1231        );
1232        context.builder.visited_style = Some(style);
1233    }
1234
1235    fn finished_applying_properties(&self, builder: &mut StyleBuilder) {
1236        #[cfg(feature = "gecko")]
1237        {
1238            if let Some(bg) = builder.get_background_if_mutated() {
1239                bg.fill_arrays();
1240            }
1241
1242            if let Some(svg) = builder.get_svg_if_mutated() {
1243                svg.fill_arrays();
1244            }
1245        }
1246
1247        // NOTE: This uses self.seen.longhands, not author_specified, because some UA styles do
1248        // specify visited-dependent properties.
1249        if self
1250            .seen
1251            .longhands
1252            .contains_any(LonghandIdSet::visited_dependent())
1253        {
1254            builder.add_flags(ComputedValueFlags::USES_VISITED_DEPENDENT_PROPERTIES);
1255        }
1256
1257        if self
1258            .author_or_user_specified
1259            .contains_any(LonghandIdSet::border_background_properties())
1260        {
1261            builder.add_flags(ComputedValueFlags::HAS_AUTHOR_OR_USER_SPECIFIED_BORDER_BACKGROUND);
1262        }
1263
1264        if self.author_or_user_specified.contains(LonghandId::Color) {
1265            builder.add_flags(ComputedValueFlags::HAS_AUTHOR_OR_USER_SPECIFIED_TEXT_COLOR);
1266        }
1267
1268        if self
1269            .author_or_user_specified
1270            .contains(LonghandId::TextShadow)
1271        {
1272            builder.add_flags(ComputedValueFlags::HAS_AUTHOR_OR_USER_SPECIFIED_TEXT_SHADOW);
1273        }
1274
1275        if self
1276            .author_or_user_specified
1277            .contains(LonghandId::GridAutoFlow)
1278        {
1279            builder.add_flags(ComputedValueFlags::HAS_AUTHOR_OR_USER_SPECIFIED_GRID_AUTO_FLOW);
1280        }
1281
1282        #[cfg(feature = "servo")]
1283        {
1284            if let Some(font) = builder.get_font_if_mutated() {
1285                font.compute_font_hash();
1286            }
1287        }
1288    }
1289
1290    fn try_to_use_cached_reset_properties(
1291        &self,
1292        context: &mut computed::Context<'a>,
1293        cache: Option<&'a RuleCache>,
1294        guards: &StylesheetGuards,
1295    ) -> bool {
1296        let style = match self.first_line_reparenting {
1297            FirstLineReparenting::Yes { style_to_reparent } => style_to_reparent,
1298            FirstLineReparenting::No => {
1299                let Some(cache) = cache else { return false };
1300                let Some(style) = cache.find(guards, context) else {
1301                    return false;
1302                };
1303                style
1304            },
1305        };
1306
1307        context.builder.copy_reset_from(style);
1308
1309        // We're using the same reset style as another element, and we'll skip
1310        // applying the relevant properties. So we need to do the relevant
1311        // bookkeeping here to keep these bits correct.
1312        //
1313        // Note that the border/background properties are non-inherited, so we
1314        // don't need to do anything else other than just copying the bits over.
1315        //
1316        // When using this optimization, we also need to copy whether the old
1317        // style specified viewport units / used font-relative lengths, this one
1318        // would as well.  It matches the same rules, so it is the right thing
1319        // to do anyways, even if it's only used on inherited properties.
1320        let bits_to_copy = ComputedValueFlags::HAS_AUTHOR_OR_USER_SPECIFIED_BORDER_BACKGROUND
1321            | ComputedValueFlags::HAS_AUTHOR_OR_USER_SPECIFIED_GRID_AUTO_FLOW
1322            | ComputedValueFlags::DEPENDS_ON_SELF_FONT_METRICS
1323            | ComputedValueFlags::DEPENDS_ON_INHERITED_FONT_METRICS
1324            | ComputedValueFlags::IS_IN_APPEARANCE_BASE_SUBTREE
1325            | ComputedValueFlags::USES_CONTAINER_UNITS
1326            | ComputedValueFlags::USES_VIEWPORT_UNITS
1327            | ComputedValueFlags::USES_FONT_OR_WM_RELATIVE_UNITS
1328            | ComputedValueFlags::DEPENDS_ON_CONTAINER_STYLE_QUERY
1329            | ComputedValueFlags::USES_SIBLING_COUNT
1330            | ComputedValueFlags::USES_SIBLING_INDEX
1331            | ComputedValueFlags::USES_VISITED_DEPENDENT_PROPERTIES
1332            | ComputedValueFlags::USES_ELEMENT_SCOPED_RANDOM;
1333        context.builder.add_flags(style.flags & bits_to_copy);
1334
1335        true
1336    }
1337
1338    /// The initial font depends on the current lang group so we may need to
1339    /// recompute it if the language changed.
1340    #[inline]
1341    #[cfg(feature = "gecko")]
1342    fn recompute_initial_font_family_if_needed(&self, builder: &mut StyleBuilder) {
1343        use crate::gecko_bindings::bindings;
1344        use crate::values::computed::font::FontFamily;
1345
1346        let default_font_type = {
1347            let font = builder.get_font();
1348
1349            if !font.mFont.family.is_initial {
1350                return;
1351            }
1352
1353            let default_font_type = unsafe {
1354                bindings::Gecko_nsStyleFont_ComputeFallbackFontTypeForLanguage(
1355                    builder.device.document(),
1356                    font.mLanguage.0.as_ptr(),
1357                )
1358            };
1359
1360            let initial_generic = font.mFont.family.families.single_generic();
1361            debug_assert!(
1362                initial_generic.is_some(),
1363                "Initial font should be just one generic font"
1364            );
1365            if initial_generic == Some(default_font_type) {
1366                return;
1367            }
1368
1369            default_font_type
1370        };
1371
1372        // NOTE: Leaves is_initial untouched.
1373        builder.mutate_font().mFont.family.families =
1374            FontFamily::generic(default_font_type).families.clone();
1375    }
1376
1377    /// Prioritize user fonts if needed by pref.
1378    #[inline]
1379    #[cfg(feature = "gecko")]
1380    fn prioritize_user_fonts_if_needed(&self, builder: &mut StyleBuilder) {
1381        use crate::gecko_bindings::bindings;
1382
1383        // Check the use_document_fonts setting for content, but for chrome
1384        // documents they're treated as always enabled.
1385        if crate::pref!("browser.display.use_document_fonts") != 0
1386            || builder.device.chrome_rules_enabled_for_document()
1387        {
1388            return;
1389        }
1390
1391        let default_font_type = {
1392            let font = builder.get_font();
1393
1394            if font.mFont.family.is_system_font {
1395                return;
1396            }
1397
1398            if !font.mFont.family.families.needs_user_font_prioritization() {
1399                return;
1400            }
1401
1402            unsafe {
1403                bindings::Gecko_nsStyleFont_ComputeFallbackFontTypeForLanguage(
1404                    builder.device.document(),
1405                    font.mLanguage.0.as_ptr(),
1406                )
1407            }
1408        };
1409
1410        let font = builder.mutate_font();
1411        font.mFont
1412            .family
1413            .families
1414            .prioritize_first_generic_or_prepend(default_font_type);
1415    }
1416
1417    /// Some keyword sizes depend on the font family and language.
1418    fn recompute_keyword_font_size_if_needed(&self, context: &mut computed::Context) {
1419        use crate::values::computed::ToComputedValue;
1420
1421        if !self.seen.longhands.contains(LonghandId::XLang)
1422            && !self.seen.longhands.contains(LonghandId::FontFamily)
1423        {
1424            return;
1425        }
1426
1427        let new_size = {
1428            let font = context.builder.get_font();
1429            let info = font.slow_clone_font_size().keyword_info;
1430            let new_size = match info.kw {
1431                specified::FontSizeKeyword::None => return,
1432                _ => {
1433                    context.for_non_inherited_property = false;
1434                    specified::FontSize::Keyword(info).to_computed_value(context)
1435                },
1436            };
1437
1438            #[cfg(feature = "gecko")]
1439            if font.mScriptUnconstrainedSize == new_size.computed_size {
1440                return;
1441            }
1442
1443            new_size
1444        };
1445
1446        context.builder.mutate_font().set_font_size(new_size);
1447    }
1448
1449    /// Some properties, plus setting font-size itself, may make us go out of
1450    /// our minimum font-size range.
1451    #[cfg(feature = "gecko")]
1452    fn constrain_font_size_if_needed(&self, builder: &mut StyleBuilder) {
1453        use crate::gecko_bindings::bindings;
1454        use crate::values::generics::NonNegative;
1455
1456        let min_font_size = {
1457            let font = builder.get_font();
1458            let min_font_size = unsafe {
1459                bindings::Gecko_nsStyleFont_ComputeMinSize(&**font, builder.device.document())
1460            };
1461
1462            if font.mFont.size.0 >= min_font_size {
1463                return;
1464            }
1465
1466            NonNegative(min_font_size)
1467        };
1468
1469        builder.mutate_font().mFont.size = min_font_size;
1470    }
1471
1472    /// <svg:text> is not affected by text zoom, and it uses a preshint to disable it. We fix up
1473    /// the struct when this happens by unzooming its contained font values, which will have been
1474    /// zoomed in the parent.
1475    #[cfg(feature = "gecko")]
1476    fn unzoom_fonts_if_needed(&self, builder: &mut StyleBuilder) {
1477        debug_assert!(self.seen.longhands.contains(LonghandId::XTextScale));
1478
1479        let parent_text_scale = *builder.get_parent_font().get__x_text_scale();
1480        let text_scale = *builder.get_font().get__x_text_scale();
1481        if parent_text_scale == text_scale {
1482            return;
1483        }
1484        debug_assert_ne!(
1485            parent_text_scale.text_zoom_enabled(),
1486            text_scale.text_zoom_enabled(),
1487            "There's only one value that disables it"
1488        );
1489        debug_assert!(
1490            !text_scale.text_zoom_enabled(),
1491            "We only ever disable text zoom never enable it"
1492        );
1493        let device = builder.device;
1494        builder.mutate_font().unzoom_fonts(device);
1495    }
1496
1497    fn recompute_font_size_for_zoom_change(&self, builder: &mut StyleBuilder) {
1498        debug_assert!(self.seen.longhands.contains(LonghandId::Zoom));
1499        // NOTE(emilio): Intentionally not using the effective zoom here, since all the inherited
1500        // zooms are already applied.
1501        let old_size = builder.get_font().slow_clone_font_size();
1502        let new_size = old_size.zoom(builder.effective_zoom_for_inheritance);
1503        if old_size == new_size {
1504            return;
1505        }
1506        builder.mutate_font().set_font_size(new_size);
1507    }
1508
1509    /// Special handling of font-size: math (used for MathML).
1510    /// https://w3c.github.io/mathml-core/#the-math-script-level-property
1511    /// TODO: Bug: 1548471: MathML Core also does not specify a script min size
1512    /// should we unship that feature or standardize it?
1513    #[cfg(feature = "gecko")]
1514    fn recompute_math_font_size_if_needed(context: &mut computed::Context) {
1515        use crate::values::generics::NonNegative;
1516
1517        // Do not do anything if font-size: math or math-depth is not set.
1518        if context
1519            .builder
1520            .get_font()
1521            .slow_clone_font_size()
1522            .keyword_info
1523            .kw
1524            != specified::FontSizeKeyword::Math
1525        {
1526            return;
1527        }
1528
1529        const SCALE_FACTOR_WHEN_INCREMENTING_MATH_DEPTH_BY_ONE: f32 = 0.71;
1530
1531        // Helper function that calculates the scale factor applied to font-size
1532        // when math-depth goes from parent_math_depth to computed_math_depth.
1533        // This function is essentially a modification of the MathML3's formula
1534        // 0.71^(parent_math_depth - computed_math_depth) so that a scale factor
1535        // of parent_script_percent_scale_down is applied when math-depth goes
1536        // from 0 to 1 and parent_script_script_percent_scale_down is applied
1537        // when math-depth goes from 0 to 2. This is also a straightforward
1538        // implementation of the specification's algorithm:
1539        // https://w3c.github.io/mathml-core/#the-math-script-level-property
1540        fn scale_factor_for_math_depth_change(
1541            parent_math_depth: i32,
1542            computed_math_depth: i32,
1543            parent_script_percent_scale_down: Option<f32>,
1544            parent_script_script_percent_scale_down: Option<f32>,
1545        ) -> f32 {
1546            let mut a = parent_math_depth;
1547            let mut b = computed_math_depth;
1548            let c = SCALE_FACTOR_WHEN_INCREMENTING_MATH_DEPTH_BY_ONE;
1549            let scale_between_0_and_1 = parent_script_percent_scale_down.unwrap_or(c);
1550            let scale_between_0_and_2 = parent_script_script_percent_scale_down.unwrap_or(c * c);
1551            let mut s = 1.0;
1552            let mut invert_scale_factor = false;
1553            if a == b {
1554                return s;
1555            }
1556            if b < a {
1557                std::mem::swap(&mut a, &mut b);
1558                invert_scale_factor = true;
1559            }
1560            let mut e = b - a;
1561            if a <= 0 && b >= 2 {
1562                s *= scale_between_0_and_2;
1563                e -= 2;
1564            } else if a == 1 {
1565                s *= scale_between_0_and_2 / scale_between_0_and_1;
1566                e -= 1;
1567            } else if b == 1 {
1568                s *= scale_between_0_and_1;
1569                e -= 1;
1570            }
1571            s *= c.powi(e);
1572            if invert_scale_factor {
1573                1.0 / s.max(f32::MIN_POSITIVE)
1574            } else {
1575                s
1576            }
1577        }
1578
1579        let (new_size, new_unconstrained_size) = {
1580            use crate::values::specified::font::QueryFontMetricsFlags;
1581
1582            let builder = &context.builder;
1583            let font = builder.get_font();
1584            let parent_font = builder.get_parent_font();
1585
1586            let delta = font.mMathDepth.saturating_sub(parent_font.mMathDepth);
1587
1588            if delta == 0 {
1589                return;
1590            }
1591
1592            let mut min = parent_font.mScriptMinSize;
1593            if font.mXTextScale.text_zoom_enabled() {
1594                min = builder.device.zoom_text(min);
1595            }
1596
1597            // Calculate scale factor following MathML Core's algorithm.
1598            let scale = {
1599                // Script scale factors are independent of orientation.
1600                let font_metrics = context.query_font_metrics(
1601                    FontBaseSize::InheritedStyle,
1602                    FontMetricsOrientation::Horizontal,
1603                    QueryFontMetricsFlags::NEEDS_MATH_SCALES,
1604                );
1605                scale_factor_for_math_depth_change(
1606                    parent_font.mMathDepth as i32,
1607                    font.mMathDepth as i32,
1608                    font_metrics.script_percent_scale_down,
1609                    font_metrics.script_script_percent_scale_down,
1610                )
1611            };
1612
1613            let parent_size = parent_font.mSize.0;
1614            let parent_unconstrained_size = parent_font.mScriptUnconstrainedSize.0;
1615            let new_size = parent_size.scale_by(scale);
1616            let new_unconstrained_size = parent_unconstrained_size.scale_by(scale);
1617
1618            if scale <= 1. {
1619                // The parent size can be smaller than scriptminsize, e.g. if it
1620                // was specified explicitly. Don't scale in this case, but we
1621                // don't want to set it to scriptminsize either since that will
1622                // make it larger.
1623                if parent_size <= min {
1624                    (parent_size, new_unconstrained_size)
1625                } else {
1626                    (min.max(new_size), new_unconstrained_size)
1627                }
1628            } else {
1629                // If the new unconstrained size is larger than the min size,
1630                // this means we have escaped the grasp of scriptminsize and can
1631                // revert to using the unconstrained size.
1632                // However, if the new size is even larger (perhaps due to usage
1633                // of em units), use that instead.
1634                (
1635                    new_size.min(new_unconstrained_size.max(min)),
1636                    new_unconstrained_size,
1637                )
1638            }
1639        };
1640        let font = context.builder.mutate_font();
1641        font.mFont.size = NonNegative(new_size);
1642        font.mSize = NonNegative(new_size);
1643        font.mScriptUnconstrainedSize = NonNegative(new_unconstrained_size);
1644    }
1645
1646    /// Seeds `context.builder.substitution_functions` with the inherited custom properties and the
1647    /// registered initial values, before custom-property declarations are cascaded into it.
1648    fn init_custom_properties(&mut self, context: &mut computed::Context) {
1649        let is_root_element = context.is_root_element();
1650        let initial_values = self.stylist.get_custom_property_initial_values();
1651        let inherited = if is_root_element {
1652            debug_assert!(context.inherited_custom_properties().is_empty());
1653            initial_values.inherited.clone()
1654        } else {
1655            context.inherited_custom_properties().inherited.clone()
1656        };
1657        let properties = ComputedCustomProperties {
1658            inherited,
1659            non_inherited: initial_values.non_inherited.clone(),
1660        };
1661        context.builder.substitution_functions =
1662            ComputedSubstitutionFunctions::new(Some(properties), None);
1663    }
1664
1665    /// Resolves the custom properties and applies the prioritary properties in a single
1666    /// cycle-tracked walk: as a custom property depending on `em`/`lh`/the used color-scheme
1667    /// becomes resolvable, `substitute_all` applies the prioritary property it needs (via
1668    /// `ensure_prioritary_property`) so it computes against the right value. Any prioritary
1669    /// property not triggered that way is applied at the end.
1670    fn apply_custom_and_prioritary_properties(
1671        &mut self,
1672        context: &mut computed::Context,
1673        decls: &Declarations,
1674        shorthand_cache: &mut ShorthandsWithPropertyReferencesCache,
1675        attribute_tracker: &mut AttributeTracker,
1676    ) {
1677        if self.may_have_custom_property_cycles {
1678            let stylist = self.stylist;
1679            let seen = std::mem::take(&mut self.seen.custom);
1680            let references = std::mem::take(&mut self.references_from_non_custom_properties);
1681            substitute_all(
1682                &seen,
1683                &references,
1684                stylist,
1685                context,
1686                self,
1687                decls,
1688                shorthand_cache,
1689                attribute_tracker,
1690            );
1691        }
1692        // Apply any prioritary property that wasn't applied while resolving custom properties.
1693        if decls.has_prioritary_properties {
1694            for id in PrioritaryPropertyId::each() {
1695                self.ensure_prioritary_property(
1696                    context,
1697                    decls,
1698                    shorthand_cache,
1699                    attribute_tracker,
1700                    id,
1701                );
1702            }
1703        }
1704        self.finish_cascade_custom_properties(context);
1705    }
1706
1707    /// Applies a prioritary property and the prioritary properties it depends on.
1708    fn ensure_prioritary_property(
1709        &mut self,
1710        context: &mut computed::Context,
1711        decls: &Declarations,
1712        cache: &mut ShorthandsWithPropertyReferencesCache,
1713        attribute_tracker: &mut AttributeTracker,
1714        id: PrioritaryPropertyId,
1715    ) {
1716        if self.ensured_prioritary.contains(id) {
1717            return;
1718        }
1719        self.ensured_prioritary.insert(id);
1720        let deps = id.dependencies();
1721        if !self.ensured_prioritary.contains_all(deps) {
1722            for dep in deps.iter() {
1723                self.ensure_prioritary_property(context, decls, cache, attribute_tracker, dep);
1724            }
1725        }
1726        self.apply_one_prioritary_property(context, decls, cache, id, attribute_tracker);
1727    }
1728
1729    /// Cascade a given custom property declaration.
1730    fn cascade_custom_property(
1731        &mut self,
1732        context: &mut computed::Context,
1733        declaration: &'a CustomDeclaration,
1734        priority: CascadePriority,
1735    ) {
1736        let CustomDeclaration {
1737            ref name,
1738            ref value,
1739        } = *declaration;
1740
1741        if let Some(&(reverted_priority, revert_kind)) = self.reverted.custom.get(name)
1742            && !reverted_priority.allows_when_reverted(&priority, revert_kind)
1743        {
1744            return;
1745        }
1746
1747        if !(priority.flags() - context.included_cascade_flags).is_empty() {
1748            return;
1749        }
1750
1751        let entry = match self.seen.custom.var.entry(name) {
1752            Entry::Occupied(..) => return,
1753            Entry::Vacant(v) => v,
1754        };
1755
1756        let registration = self.stylist.get_custom_property_registration(name);
1757        let initial_values = self.stylist.get_custom_property_initial_values();
1758        if !Self::value_may_affect_style(context, name, registration, initial_values, value) {
1759            entry.insert(false);
1760            return;
1761        }
1762
1763        let has_references = match value {
1764            CustomDeclarationValue::Unparsed(unparsed_value) => {
1765                // Non-custom dependency is really relevant for registered custom properties
1766                // that require computed value of such dependencies.
1767                unparsed_value
1768                    .references
1769                    .flags
1770                    .intersects(ReferenceFlags::ATTR | ReferenceFlags::VAR)
1771                    || !find_non_custom_references(
1772                        registration,
1773                        unparsed_value,
1774                        context.is_root_element(),
1775                    )
1776                    .is_empty()
1777            },
1778            // XXX This matches the previous behavior but I don't think it's fully sound. Parsed
1779            // values may have non-custom references, can't they? But also how do we get a parsed
1780            // value at all here?
1781            CustomDeclarationValue::Parsed(..) => false,
1782            // If we're a wide keyword we either get an initial value or an inherited one (no
1783            // references). Revert might have references, but we remove the `seen` entry, so it
1784            // doesn't matter.
1785            CustomDeclarationValue::CSSWideKeyword(..) => false,
1786        };
1787        self.may_have_custom_property_cycles |= has_references;
1788        entry.insert(has_references);
1789
1790        match value {
1791            CustomDeclarationValue::Unparsed(unparsed_value) => {
1792                if !has_references {
1793                    // If the variable value has no references to other properties, perform
1794                    // substitution here instead of forcing a full traversal in `substitute_all`
1795                    // afterwards.
1796                    substitute_references_if_needed_and_apply(
1797                        name,
1798                        SubstitutionFunctionKind::Var,
1799                        unparsed_value,
1800                        self.stylist,
1801                        context,
1802                        // We just checked there are no attr dependencies.
1803                        &mut AttributeTracker::new_dummy(),
1804                    );
1805                    return;
1806                }
1807                let value = ComputedRegisteredValue::universal(Arc::clone(unparsed_value));
1808                context
1809                    .builder
1810                    .substitution_functions
1811                    .insert_var(registration, name, value);
1812            },
1813            CustomDeclarationValue::Parsed(parsed_value) => {
1814                let value = parsed_value.to_computed_value(context);
1815                context
1816                    .builder
1817                    .substitution_functions
1818                    .insert_var(registration, name, value);
1819            },
1820            CustomDeclarationValue::CSSWideKeyword(keyword) => match keyword.revert_kind() {
1821                Some(revert_kind) => {
1822                    self.seen.custom.var.remove(name);
1823                    self.reverted
1824                        .custom
1825                        .insert(name.clone(), (priority, revert_kind));
1826                },
1827                None => match keyword {
1828                    CSSWideKeyword::Initial => {
1829                        // For non-inherited custom properties, 'initial' was handled in value_may_affect_style.
1830                        debug_assert!(registration.inherits(), "Should've been handled earlier");
1831                        remove_and_insert_initial_value(
1832                            name,
1833                            registration,
1834                            &mut context.builder.substitution_functions,
1835                        );
1836                    },
1837                    CSSWideKeyword::Inherit => {
1838                        // For inherited custom properties, 'inherit' was handled in value_may_affect_style.
1839                        debug_assert!(!registration.inherits(), "Should've been handled earlier");
1840                        context
1841                            .style()
1842                            .add_flags(ComputedValueFlags::INHERITS_RESET_STYLE);
1843                        let inherited_value = context
1844                            .inherited_custom_properties()
1845                            .non_inherited
1846                            .get(name)
1847                            .cloned();
1848                        if let Some(inherited_value) = inherited_value {
1849                            context.builder.substitution_functions.insert_var(
1850                                registration,
1851                                name,
1852                                inherited_value,
1853                            );
1854                        }
1855                    },
1856                    // handled in value_may_affect_style or in the revert_kind branch above.
1857                    CSSWideKeyword::Revert
1858                    | CSSWideKeyword::RevertLayer
1859                    | CSSWideKeyword::RevertRule
1860                    | CSSWideKeyword::Unset => unreachable!(),
1861                },
1862            },
1863        }
1864    }
1865
1866    /// Fast check to avoid calling maybe_note_non_custom_dependency in ~all cases.
1867    #[inline]
1868    pub fn might_have_non_custom_or_attr_dependency(
1869        id: LonghandId,
1870        decl: &PropertyDeclaration,
1871    ) -> bool {
1872        if let PropertyDeclaration::WithVariables(v) = decl {
1873            return matches!(id, LonghandId::LineHeight | LonghandId::FontSize)
1874                || v.value
1875                    .variable_value
1876                    .references
1877                    .flags
1878                    .intersects(ReferenceFlags::ATTR);
1879        }
1880        false
1881    }
1882
1883    /// Note a non-custom property with variable reference that may in turn depend on that property.
1884    /// e.g. `font-size` depending on a custom property that may be a registered property using `em`.
1885    pub fn maybe_note_non_custom_dependency(
1886        &mut self,
1887        context: &mut computed::Context,
1888        id: LonghandId,
1889        decl: &'a PropertyDeclaration,
1890    ) {
1891        debug_assert!(Self::might_have_non_custom_or_attr_dependency(id, decl));
1892        let PropertyDeclaration::WithVariables(v) = decl else {
1893            return;
1894        };
1895        let value = &v.value.variable_value;
1896        let refs = &value.references;
1897
1898        if !refs
1899            .flags
1900            .intersects(ReferenceFlags::VAR | ReferenceFlags::ATTR)
1901        {
1902            return;
1903        }
1904
1905        // Attributes in non-custom properties may reference `var()` or `attr()` in their
1906        // values, which we need to track to support chained references and detect cycles.
1907        if refs.flags.intersects(ReferenceFlags::ATTR) {
1908            self.may_have_custom_property_cycles = true;
1909            self.seen.custom.attr.push((id, v.value.clone()));
1910        }
1911
1912        // The non-custom node(s) this property feeds. We don't try to figure out here which
1913        // referenced custom properties can actually cycle back to it: instead we record the whole
1914        // declaration value, and let `substitute_all` traverse its references (following fallbacks
1915        // only when the primary is invalid). This way, references that only appear in an unused
1916        // fallback (e.g. `var(--exists, var(--font-size-em))`) don't create a spurious cycle, while
1917        // references in a used fallback (e.g. `var(--noexist, var(--font-size-em))`) do.
1918        //
1919        // With unit algebra in `calc()`, references aren't limited to `font-size`. For example,
1920        // `--foo: 100ex; font-weight: calc(var(--foo) / 1ex);`, or
1921        // `--foo: 1em; zoom: calc(var(--foo) * 30px / 2em);`
1922        let references = match id {
1923            LonghandId::FontSize => ReferenceFlags::FONT_UNITS,
1924            LonghandId::LineHeight => ReferenceFlags::LH_UNITS | ReferenceFlags::FONT_UNITS,
1925            LonghandId::ColorScheme => ReferenceFlags::COLOR_SCHEME,
1926            _ => return,
1927        };
1928
1929        references.for_each_non_custom(context.is_root_element(), |idx| {
1930            self.references_from_non_custom_properties[idx]
1931                .get_or_insert_with(Vec::new)
1932                .push(v.value.clone());
1933        });
1934    }
1935
1936    fn value_may_affect_style(
1937        context: &computed::Context,
1938        name: &Name,
1939        registration: &PropertyDescriptors,
1940        initial_values: &ComputedCustomProperties,
1941        value: &CustomDeclarationValue,
1942    ) -> bool {
1943        match *value {
1944            CustomDeclarationValue::CSSWideKeyword(CSSWideKeyword::Inherit) => {
1945                // For inherited custom properties, explicit 'inherit' means we
1946                // can just use any existing value in the inherited
1947                // CustomPropertiesMap.
1948                if registration.inherits() {
1949                    return false;
1950                }
1951            },
1952            CustomDeclarationValue::CSSWideKeyword(CSSWideKeyword::Initial) => {
1953                // For non-inherited custom properties, explicit 'initial' means
1954                // we can just use any initial value in the registration.
1955                if !registration.inherits() {
1956                    return false;
1957                }
1958            },
1959            CustomDeclarationValue::CSSWideKeyword(CSSWideKeyword::Unset) => {
1960                // Explicit 'unset' means we can either just use any existing
1961                // value in the inherited CustomPropertiesMap or the initial
1962                // value in the registration.
1963                return false;
1964            },
1965            _ => {},
1966        }
1967
1968        let existing_value = context
1969            .builder
1970            .substitution_functions
1971            .get_var(registration, name);
1972        let Some(existing_value) = existing_value else {
1973            if matches!(
1974                value,
1975                CustomDeclarationValue::CSSWideKeyword(CSSWideKeyword::Initial)
1976            ) {
1977                debug_assert!(registration.inherits(), "Should've been handled earlier");
1978                // The initial value of a custom property without a
1979                // guaranteed-invalid initial value is the same as it
1980                // not existing in the map.
1981                if registration.initial_value.is_none() {
1982                    return false;
1983                }
1984            }
1985            return true;
1986        };
1987        match value {
1988            CustomDeclarationValue::Unparsed(value) => {
1989                // Don't bother overwriting an existing value with the same
1990                // specified value.
1991                if let Some(existing_value) = existing_value.as_universal() {
1992                    return existing_value != value;
1993                }
1994            },
1995            CustomDeclarationValue::Parsed(..) => {
1996                // If the value has dependencies, context might not yield the same
1997                // result as the eventual value.
1998            },
1999            CustomDeclarationValue::CSSWideKeyword(kw) => {
2000                match kw {
2001                    CSSWideKeyword::Inherit => {
2002                        debug_assert!(!registration.inherits(), "Should've been handled earlier");
2003                        // existing_value is the registered initial value.
2004                        // Don't bother adding it to self.custom_properties.non_inherited
2005                        // if the key is also absent from self.inherited.non_inherited.
2006                        if context
2007                            .inherited_custom_properties()
2008                            .non_inherited
2009                            .get(name)
2010                            .is_none()
2011                        {
2012                            return false;
2013                        }
2014                    },
2015                    CSSWideKeyword::Initial => {
2016                        debug_assert!(registration.inherits(), "Should've been handled earlier");
2017                        // Don't bother overwriting an existing value with the initial value
2018                        // specified in the registration.
2019                        if let Some(initial_value) = initial_values.get(registration, name) {
2020                            return existing_value.attr_tainted || existing_value != initial_value;
2021                        }
2022                    },
2023                    CSSWideKeyword::Unset => {
2024                        debug_assert!(false, "Should've been handled earlier");
2025                    },
2026                    CSSWideKeyword::Revert
2027                    | CSSWideKeyword::RevertLayer
2028                    | CSSWideKeyword::RevertRule => {},
2029                }
2030            },
2031        };
2032
2033        true
2034    }
2035
2036    /// Computes the map of applicable custom properties, saving the result into the computed
2037    /// context, and applies the prioritary properties interleaved with custom-property resolution.
2038    pub fn finish_cascade_custom_properties(&mut self, context: &mut computed::Context) {
2039        context
2040            .builder
2041            .substitution_functions
2042            .custom_properties
2043            .shrink_to_fit();
2044
2045        // Some pages apply a lot of redundant custom properties, see e.g.
2046        // bug 1758974 comment 5. Try to detect the case where the values
2047        // haven't really changed, and save some memory by reusing the inherited
2048        // map in that case.
2049        let initial_values = self.stylist.get_custom_property_initial_values();
2050        let reuse_inherited = context.inherited_custom_properties().inherited
2051            == context
2052                .builder
2053                .substitution_functions
2054                .custom_properties
2055                .inherited;
2056        if reuse_inherited {
2057            let inherited = context.inherited_custom_properties().inherited.clone();
2058            context
2059                .builder
2060                .substitution_functions
2061                .custom_properties
2062                .inherited = inherited;
2063        }
2064        if initial_values.non_inherited
2065            == context
2066                .builder
2067                .substitution_functions
2068                .custom_properties
2069                .non_inherited
2070        {
2071            let non_inherited = initial_values.non_inherited.clone();
2072            context
2073                .builder
2074                .substitution_functions
2075                .custom_properties
2076                .non_inherited = non_inherited;
2077        }
2078    }
2079}
2080
2081fn substitute_all(
2082    seen: &SeenSubstitutionFunctions,
2083    references_from_non_custom_properties: &NonCustomReferenceMap<Vec<Arc<UnparsedValue>>>,
2084    stylist: &Stylist,
2085    computed_context: &mut computed::Context,
2086    cascade: &mut Cascade,
2087    decls: &Declarations,
2088    shorthand_cache: &mut ShorthandsWithPropertyReferencesCache,
2089    attr_tracker: &mut AttributeTracker,
2090) {
2091    // The cycle dependencies removal in this function is a variant
2092    // of Tarjan's algorithm. It is mostly based on the pseudo-code
2093    // listed in
2094    // https://en.wikipedia.org/w/index.php?
2095    // title=Tarjan%27s_strongly_connected_components_algorithm&oldid=801728495
2096
2097    #[derive(Clone, Eq, PartialEq, Debug)]
2098    enum VarType {
2099        Attr(Name),
2100        Custom(Name),
2101        NonCustom(SingleNonCustomReference),
2102    }
2103
2104    /// Struct recording necessary information for each variable.
2105    #[derive(Debug)]
2106    struct VarInfo {
2107        /// The name of the variable. It will be taken when the corresponding variable is popped
2108        /// from the stack, which serves as a mark for whether the variable is currently in the
2109        /// stack below.
2110        var: Option<VarType>,
2111        /// If the variable is in a dependency cycle, lowlink represents a smaller index which
2112        /// corresponds to a variable in the same strong connected component, which is known to be
2113        /// accessible from this variable. It is not necessarily the root, though.
2114        lowlink: usize,
2115    }
2116
2117    #[derive(Debug, Default)]
2118    struct OrderIndexMap {
2119        /// The map from the custom property name to its order index.
2120        var: PrecomputedHashMap<Name, usize>,
2121        /// The map from the attribute name to its order index.
2122        attr: PrecomputedHashMap<Name, usize>,
2123    }
2124
2125    impl OrderIndexMap {
2126        fn clear(&mut self) {
2127            self.var.clear();
2128            self.attr.clear();
2129        }
2130    }
2131
2132    /// Context struct for traversing the variable graph, so that we can
2133    /// avoid referencing all the fields multiple times.
2134    struct Context<'a, 'b: 'a, 'c, 'd, 'e> {
2135        /// Number of variables visited. This is used as the order index
2136        /// when we visit a new unresolved variable.
2137        count: usize,
2138        /// The map from a substitution function name to its order index.
2139        index_map: OrderIndexMap,
2140        /// Mapping from a non-custom dependency to its order index.
2141        non_custom_index_map: NonCustomReferenceMap<usize>,
2142        /// Information of each variable indexed by the order index.
2143        var_info: SmallVec<[VarInfo; 5]>,
2144        /// The stack of order index of visited variables. It contains
2145        /// all unfinished strong connected components.
2146        stack: SmallVec<[usize; 5]>,
2147        /// The stylist is used to get registered properties, and to resolve the environment to
2148        /// substitute `env()` variables.
2149        stylist: &'a Stylist,
2150        /// The computed context is used to get inherited custom properties, compute registered
2151        /// custom properties, and apply prioritary properties.
2152        computed_context: &'a mut computed::Context<'b>,
2153        /// The cascade owns prioritary-property application; when a `NonCustom` node (or a
2154        /// color-scheme-dependent custom property) becomes resolvable, we apply the corresponding
2155        /// prioritary property directly through it.
2156        cascade: &'a mut Cascade<'c>,
2157        /// The declarations, needed to apply prioritary properties.
2158        decls: &'a Declarations<'d>,
2159        /// Shorthand cache, needed to apply prioritary properties.
2160        cache: &'a mut ShorthandsWithPropertyReferencesCache,
2161        /// Tracks and resolves attributes queried by `attr()`.
2162        attribute_tracker: &'a mut AttributeTracker<'e>,
2163    }
2164
2165    impl<'a, 'b: 'a, 'c, 'd, 'e> Context<'a, 'b, 'c, 'd, 'e> {
2166        fn reset(&mut self) {
2167            self.count = 0;
2168            self.index_map.clear();
2169            self.non_custom_index_map = Default::default();
2170            self.var_info.clear();
2171            self.stack.clear();
2172        }
2173
2174        fn map(&self) -> &ComputedSubstitutionFunctions {
2175            &self.computed_context.builder.substitution_functions
2176        }
2177
2178        fn map_mut(&mut self) -> &mut ComputedSubstitutionFunctions {
2179            &mut self.computed_context.builder.substitution_functions
2180        }
2181
2182        /// Marks a given `name` as being in a loop.
2183        fn handle_loop(&mut self, name: &VarType) {
2184            match name {
2185                VarType::Attr(name) => {
2186                    self.computed_context
2187                        .builder
2188                        .substitution_functions
2189                        .remove_attr(name);
2190                },
2191                VarType::Custom(name) => {
2192                    // This variable is in a loop. Resolve to invalid.
2193                    handle_invalid_at_computed_value_time(
2194                        name,
2195                        self.stylist.get_custom_property_registration(name),
2196                        self.computed_context,
2197                    );
2198                },
2199                VarType::NonCustom(non_custom) => {
2200                    self.computed_context
2201                        .builder
2202                        .invalid_non_custom_properties
2203                        .insert(non_custom.to_prioritary_id().to_longhand());
2204                },
2205            }
2206        }
2207
2208        /// Applies a prioritary property (and its dependencies) while resolving custom properties.
2209        ///
2210        /// The in-progress map lives outside `computed_context` during traversal; we move it into
2211        /// `computed_context.builder.substitution_functions` so the prioritary declaration's `var()`
2212        /// references resolve against the custom properties resolved so far, then take it back out.
2213        fn apply_prioritary_property(&mut self, id: PrioritaryPropertyId) {
2214            self.cascade.ensure_prioritary_property(
2215                self.computed_context,
2216                self.decls,
2217                self.cache,
2218                self.attribute_tracker,
2219                id,
2220            );
2221        }
2222
2223        fn replacement_context<'s>(
2224            &'s mut self,
2225            property_id: PropertyIdRef<'s>,
2226        ) -> SubstitutionReplacementContext<'s, 's, 'b, 'e> {
2227            SubstitutionReplacementContext::new(
2228                Some(property_id),
2229                &self.computed_context.builder.substitution_functions,
2230                self.stylist,
2231                self.computed_context,
2232                self.attribute_tracker,
2233            )
2234        }
2235    }
2236
2237    /// Traverse the references in `root` creating graph edges to the referenced substitution
2238    /// functions and updating `lowlink`/`self_ref` accordingly.
2239    ///
2240    /// We follow var()/attr()/env() fallbacks only when the primary substitution function is
2241    /// guaranteed-invalid (i.e. when the fallback is actually used). This matches the substitution
2242    /// order and the resolution of https://github.com/w3c/csswg-drafts/issues/11500: cycles (or
2243    /// dependencies) that only exist through an unused fallback don't count.
2244    ///
2245    /// We need to bubble up non custom references from unregistered properties.
2246    fn visit_value_references<'a, 'b, 'c, 'd, 'e>(
2247        var: Option<&VarType>,
2248        root: &References,
2249        source: &VariableValue,
2250        index: usize,
2251        property_id: PropertyIdRef,
2252        references_from_non_custom_properties: &NonCustomReferenceMap<Vec<Arc<UnparsedValue>>>,
2253        context: &mut Context<'a, 'b, 'c, 'd, 'e>,
2254        lowlink: &mut usize,
2255        self_ref: &mut bool,
2256        non_custom_references: &mut ReferenceFlags,
2257    ) {
2258        macro_rules! check_declaration_value_cycle {
2259            ($arg:expr) => {{
2260                let mut arg_lowlink = usize::MAX;
2261                let mut arg_self_ref = false;
2262                visit_value_references(
2263                    var,
2264                    &$arg.references,
2265                    source,
2266                    index,
2267                    property_id,
2268                    references_from_non_custom_properties,
2269                    context,
2270                    &mut arg_lowlink,
2271                    &mut arg_self_ref,
2272                    non_custom_references,
2273                );
2274                *lowlink = cmp::min(*lowlink, arg_lowlink);
2275                *self_ref |= arg_self_ref;
2276                arg_lowlink != usize::MAX || arg_self_ref
2277            }};
2278        }
2279
2280        // FIXME: Maybe avoid visiting the same var twice if not needed?
2281        let mut refs_stack = SmallVec::<[&References; 5]>::new();
2282        refs_stack.push(root);
2283        while let Some(refs) = refs_stack.pop() {
2284            *non_custom_references |= refs.flags;
2285            for next in &refs.refs {
2286                let (next_var, fallback) = match next.function {
2287                    SubstitutionFunction::Env(ref env_fn) => {
2288                        let name = match &env_fn.name {
2289                            SubstitutionArgument::Unparsed(arg) => {
2290                                if check_declaration_value_cycle!(arg) {
2291                                    continue;
2292                                }
2293                                let mut replacement_context =
2294                                    context.replacement_context(property_id);
2295                                env_fn
2296                                    .replace_name(source, &mut replacement_context)
2297                                    .value
2298                                    .map(|name| Cow::Owned(name.into_owned()))
2299                            },
2300                            SubstitutionArgument::Parsed(name) => Some(Cow::Borrowed(name)),
2301                            SubstitutionArgument::Invalid => None,
2302                        };
2303
2304                        let device = context.stylist.device();
2305                        let replacement_context = context.replacement_context(property_id);
2306                        let present = name
2307                            .and_then(|name| {
2308                                device.environment().get(
2309                                    &name.0,
2310                                    device,
2311                                    &replacement_context.parser_context(&source.url_data),
2312                                )
2313                            })
2314                            .is_some();
2315                        if !present && let Some(ref fallback) = env_fn.fallback {
2316                            refs_stack.push(&fallback.references);
2317                        }
2318                        continue;
2319                    },
2320                    SubstitutionFunction::Attr(ref attr_fn) => {
2321                        let arg = match &attr_fn.arg {
2322                            SubstitutionArgument::Unparsed(arg) => {
2323                                if check_declaration_value_cycle!(arg) {
2324                                    continue;
2325                                }
2326                                attr_fn
2327                                    .replace_arg(
2328                                        source,
2329                                        &mut context.replacement_context(property_id),
2330                                    )
2331                                    .value
2332                                    .map(|arg| Cow::Owned(arg.into_owned()))
2333                            },
2334                            SubstitutionArgument::Parsed(arg) => Some(Cow::Borrowed(arg)),
2335                            SubstitutionArgument::Invalid => None,
2336                        };
2337                        let Some(arg) = arg else {
2338                            if let Some(ref fallback) = attr_fn.fallback {
2339                                refs_stack.push(&fallback.references);
2340                            }
2341                            continue;
2342                        };
2343                        // An type()-less attr() within attr(... type()) can still have nested
2344                        // references.
2345                        let can_chain = arg.has_type() || matches!(var, Some(VarType::Attr(..)));
2346                        if !can_chain {
2347                            continue;
2348                        }
2349                        if context.map().get_attr(&arg.name.name).is_none()
2350                            && let Ok(val) = arg.name.value_for_cycle_resolution(
2351                                &mut context.replacement_context(property_id),
2352                                &source.url_data,
2353                            )
2354                        {
2355                            context.map_mut().insert_attr(&arg.name.name, val);
2356                        }
2357                        (
2358                            VarType::Attr(arg.name.name.clone()),
2359                            attr_fn.fallback.as_ref(),
2360                        )
2361                    },
2362                    SubstitutionFunction::Var(ref var_fn) => {
2363                        let name = match &var_fn.name {
2364                            SubstitutionArgument::Unparsed(arg) => {
2365                                if check_declaration_value_cycle!(arg) {
2366                                    continue;
2367                                }
2368                                let mut replacement_context =
2369                                    context.replacement_context(property_id);
2370                                var_fn
2371                                    .replace_name(source, &mut replacement_context)
2372                                    .value
2373                                    .map(|name| Cow::Owned(name.into_owned()))
2374                            },
2375                            SubstitutionArgument::Parsed(name) => Some(Cow::Borrowed(name)),
2376                            SubstitutionArgument::Invalid => None,
2377                        };
2378                        let Some(name) = name else {
2379                            if let Some(ref fallback) = var_fn.fallback {
2380                                refs_stack.push(&fallback.references);
2381                            }
2382                            continue;
2383                        };
2384                        (VarType::Custom(name.0.clone()), var_fn.fallback.as_ref())
2385                    },
2386                };
2387
2388                visit_link(
2389                    next_var.clone(),
2390                    index,
2391                    references_from_non_custom_properties,
2392                    context,
2393                    lowlink,
2394                    self_ref,
2395                );
2396
2397                // Now that the primary reference has been resolved, classify it to
2398                // decide whether its fallback is used.
2399                let resolved = match next_var {
2400                    VarType::Custom(ref name) => {
2401                        let registration = context.stylist.get_custom_property_registration(name);
2402                        context.map().get_var(registration, name)
2403                    },
2404                    VarType::Attr(ref name) => context.map().get_attr(name),
2405                    VarType::NonCustom(..) => {
2406                        unreachable!("Handled above")
2407                    },
2408                };
2409                // The primary is guaranteed-invalid if it's absent from the map, or still
2410                // present but unresolved (i.e. part of a cycle currently being resolved).
2411                let mut primary_valid = false;
2412                if let Some(resolved) = resolved {
2413                    if let Some(v) = resolved.as_universal() {
2414                        primary_valid = !v.has_references();
2415                        *non_custom_references |= v.references.flags;
2416                    } else {
2417                        // Resolved and computed value, no other custom references left.
2418                        primary_valid = true;
2419                    }
2420                }
2421
2422                if !primary_valid && let Some(fallback) = fallback {
2423                    refs_stack.push(&fallback.references);
2424                }
2425            }
2426        }
2427    }
2428
2429    /// Traverse a single dependency `var` of the variable at order index `index`, updating its
2430    /// `lowlink`/`self_ref` from the result.
2431    fn visit_link<'a, 'b, 'c, 'd, 'e>(
2432        var: VarType,
2433        index: usize,
2434        non_custom_references: &NonCustomReferenceMap<Vec<Arc<UnparsedValue>>>,
2435        context: &mut Context<'a, 'b, 'c, 'd, 'e>,
2436        lowlink: &mut usize,
2437        self_ref: &mut bool,
2438    ) {
2439        let next_index = match traverse(var, non_custom_references, context) {
2440            Some(index) => index,
2441            // There is nothing to do if the next variable has been
2442            // fully resolved at this point.
2443            None => return,
2444        };
2445        let next_info = &context.var_info[next_index];
2446        if next_index > index {
2447            // The next variable has a larger index than us, so it
2448            // must be inserted in the recursive call above. We want
2449            // to get its lowlink.
2450            *lowlink = cmp::min(*lowlink, next_info.lowlink);
2451        } else if next_index == index {
2452            *self_ref = true;
2453        } else if next_info.var.is_some() {
2454            // The next variable has a smaller order index and it is
2455            // in the stack, so we are at the same component.
2456            *lowlink = cmp::min(*lowlink, next_index);
2457        }
2458    }
2459
2460    /// This function combines the traversal for cycle removal and value
2461    /// substitution. It returns either a signal None if this variable
2462    /// has been fully resolved (to either having no reference or being
2463    /// marked invalid), or the order index for the given name.
2464    ///
2465    /// When it returns, the variable corresponds to the name would be
2466    /// in one of the following states:
2467    /// * It is still in context.stack, which means it is part of an
2468    ///   potentially incomplete dependency circle.
2469    /// * It has been removed from the map.  It can be either that the
2470    ///   substitution failed, or it is inside a dependency circle.
2471    ///   When this function removes a variable from the map because
2472    ///   of dependency circle, it would put all variables in the same
2473    ///   strong connected component to the set together.
2474    /// * It doesn't have any reference, because either this variable
2475    ///   doesn't have reference at all in specified value, or it has
2476    ///   been completely resolved.
2477    /// * There is no such variable at all.
2478    fn traverse<'a, 'b, 'c, 'd, 'e>(
2479        var: VarType,
2480        references_from_non_custom_properties: &NonCustomReferenceMap<Vec<Arc<UnparsedValue>>>,
2481        context: &mut Context<'a, 'b, 'c, 'd, 'e>,
2482    ) -> Option<usize> {
2483        // Some shortcut checks.
2484        // The non-custom (font/line-height/color-scheme) dependencies of this value, carried out
2485        // of the match so we can create the corresponding nodes once we've pushed this variable.
2486        let mut value_non_custom_refs = ReferenceFlags::empty();
2487        let mut registered = false;
2488        let value = match var {
2489            VarType::Custom(ref name) | VarType::Attr(ref name) => {
2490                let map = &context.computed_context.builder.substitution_functions;
2491                let (registration, value, kind) = if matches!(var, VarType::Custom(..)) {
2492                    let registration = context.stylist.get_custom_property_registration(name);
2493                    (
2494                        registration,
2495                        map.get_var(registration, name)?.as_universal()?,
2496                        SubstitutionFunctionKind::Var,
2497                    )
2498                } else {
2499                    // `attr()` is always treated as unregistered.
2500                    (
2501                        PropertyDescriptors::unregistered(),
2502                        map.get_attr(name)?.as_universal()?,
2503                        SubstitutionFunctionKind::Attr,
2504                    )
2505                };
2506                let is_root = context.computed_context.is_root_element();
2507                value_non_custom_refs = find_non_custom_references(registration, value, is_root);
2508                registered = !registration.is_universal();
2509                let has_dependency = value
2510                    .references
2511                    .flags
2512                    .intersects(ReferenceFlags::ATTR | ReferenceFlags::VAR)
2513                    || !value_non_custom_refs.is_empty();
2514                // Nothing to resolve.
2515                if !has_dependency {
2516                    debug_assert!(
2517                        !value.references.flags.intersects(ReferenceFlags::ENV),
2518                        "Should've been handled earlier"
2519                    );
2520                    if kind == SubstitutionFunctionKind::Attr || registered {
2521                        // We might still need to compute the value if this is not an universal
2522                        // registration but we thought it had a dependency during the cascade and it
2523                        // turned out not to. Note that if this was already computed we would've
2524                        // bailed out in the as_universal() check.
2525                        let value = value.clone();
2526                        substitute_references_if_needed_and_apply(
2527                            name,
2528                            kind,
2529                            &value,
2530                            context.stylist,
2531                            context.computed_context,
2532                            context.attribute_tracker,
2533                        );
2534                    }
2535                    return None;
2536                }
2537
2538                // Has this variable been visited?
2539                let index_map = if kind == SubstitutionFunctionKind::Var {
2540                    &mut context.index_map.var
2541                } else {
2542                    &mut context.index_map.attr
2543                };
2544                match index_map.entry_ref(name) {
2545                    EntryRef::Occupied(entry) => {
2546                        return Some(*entry.get());
2547                    },
2548                    EntryRef::Vacant(entry) => {
2549                        entry.insert(context.count);
2550                    },
2551                }
2552                // Hold a strong reference to the value so that we don't
2553                // need to keep reference to context.map.
2554                Some((name, value.clone()))
2555            },
2556            VarType::NonCustom(ref non_custom) => {
2557                let entry = &mut context.non_custom_index_map[*non_custom];
2558                if let Some(v) = entry {
2559                    return Some(*v);
2560                }
2561                *entry = Some(context.count);
2562                None
2563            },
2564        };
2565
2566        // Add new entry to the information table.
2567        let index = context.count;
2568        context.count += 1;
2569        debug_assert_eq!(index, context.var_info.len());
2570        context.var_info.push(VarInfo {
2571            var: Some(var.clone()),
2572            lowlink: index,
2573        });
2574        context.stack.push(index);
2575
2576        let mut self_ref = false;
2577        let mut lowlink = index;
2578        if let Some((name, v)) = value.as_ref() {
2579            // Visit the references in this value...
2580            visit_value_references(
2581                Some(&var),
2582                &v.references,
2583                v,
2584                index,
2585                PropertyIdRef::from(*name),
2586                references_from_non_custom_properties,
2587                context,
2588                &mut lowlink,
2589                &mut self_ref,
2590                &mut value_non_custom_refs,
2591            );
2592
2593            // ... Then the non-custom properties this value depends on (font-size, line-height,
2594            // color-scheme), as computed by `find_non_custom_references` above.
2595            let is_root = context.computed_context.is_root_element();
2596            if registered && !value_non_custom_refs.is_empty() {
2597                value_non_custom_refs.for_each_non_custom(is_root, |r| {
2598                    visit_link(
2599                        VarType::NonCustom(r),
2600                        index,
2601                        references_from_non_custom_properties,
2602                        context,
2603                        &mut lowlink,
2604                        &mut self_ref,
2605                    );
2606                });
2607            }
2608        } else if let VarType::NonCustom(non_custom) = var {
2609            // line-height's resolution depends on font-size's, so its node has a graph edge to the
2610            // font-size node. This is needed for cycle detection (not just application order, which
2611            // `prioritary_property_dependencies(LineHeight)` handles): it puts the line-height node
2612            // in the same strongly-connected component as a font-size<->custom cycle, so the node
2613            // doesn't apply line-height (and, transitively, font-size) before that cycle is
2614            // removed.
2615            //
2616            // TODO(emilio): I think the right fix for this is
2617            // s/SingleNonCustomReference/PrioritaryPropertyId in VarType::NonCustom.
2618            if non_custom == SingleNonCustomReference::LhUnits {
2619                visit_link(
2620                    VarType::NonCustom(SingleNonCustomReference::FontUnits),
2621                    index,
2622                    references_from_non_custom_properties,
2623                    context,
2624                    &mut lowlink,
2625                    &mut self_ref,
2626                );
2627            }
2628            let entry = &references_from_non_custom_properties[non_custom];
2629            if let Some(values) = entry.as_ref() {
2630                for value in values {
2631                    // Traverse the non-custom property's declaration value(s), creating edges to
2632                    // the custom properties they reference (directly or through a used fallback)
2633                    // that might cycle back to this node. Note we traverse unregistered/universal
2634                    // references too: while their own font-relative units are textual (resolved
2635                    // against the parent, see `find_non_custom_references`), they may chain to a
2636                    // registered property that does cycle back.
2637                    let property_id = PropertyIdRef::from(match value.from_shorthand {
2638                        Some(shorthand_id) => NonCustomPropertyId::from(shorthand_id),
2639                        None => {
2640                            NonCustomPropertyId::from(non_custom.to_prioritary_id().to_longhand())
2641                        },
2642                    });
2643                    let value = &value.variable_value;
2644                    visit_value_references(
2645                        Some(&var),
2646                        &value.references,
2647                        value,
2648                        index,
2649                        property_id,
2650                        references_from_non_custom_properties,
2651                        context,
2652                        &mut lowlink,
2653                        &mut self_ref,
2654                        &mut Default::default(),
2655                    );
2656                }
2657            }
2658        }
2659
2660        context.var_info[index].lowlink = lowlink;
2661        if lowlink != index {
2662            // This variable is in a loop, but it is not the root of this strong connected
2663            // component. We simply return for now, and the root would remove it from the map.
2664            //
2665            // This cannot be removed from the map here, because otherwise the shortcut check at the
2666            // beginning of this function would return the wrong value.
2667            return Some(index);
2668        }
2669
2670        // This is the root of a strong-connected component.
2671        let mut in_loop = self_ref;
2672        loop {
2673            let var_index = context
2674                .stack
2675                .pop()
2676                .expect("The current variable should still be in stack");
2677            let var_info = &mut context.var_info[var_index];
2678            // We should never visit the variable again, so it's safe to take the name away.
2679            let var_name = var_info
2680                .var
2681                .take()
2682                .expect("Variable should not be popped from stack twice");
2683            if var_index != index {
2684                // Anything here is in a loop which can traverse to the node we are handling, so
2685                // it's invalid at computed-value time.
2686                in_loop = true;
2687            }
2688            if in_loop {
2689                context.handle_loop(&var_name);
2690            }
2691            if var_index == index {
2692                debug_assert_eq!(var_name, var);
2693                break;
2694            }
2695        }
2696
2697        if in_loop {
2698            return None;
2699        }
2700
2701        // Not in a loop, apply the value.
2702        match var {
2703            VarType::Custom(ref name) | VarType::Attr(ref name) => {
2704                if let Some((_, ref v)) = value {
2705                    let kind = if matches!(var, VarType::Custom(..)) {
2706                        SubstitutionFunctionKind::Var
2707                    } else {
2708                        SubstitutionFunctionKind::Attr
2709                    };
2710                    // We know we're not in a loop now, perform substitution.
2711                    // TODO(emilio): Merge with the cycle detection loop instead?
2712                    substitute_references_if_needed_and_apply(
2713                        name,
2714                        kind,
2715                        v,
2716                        context.stylist,
2717                        context.computed_context,
2718                        context.attribute_tracker,
2719                    );
2720                }
2721            },
2722            VarType::NonCustom(non_custom) => {
2723                context.apply_prioritary_property(non_custom.to_prioritary_id());
2724            },
2725        }
2726        // All resolved, so return the signal value.
2727        None
2728    }
2729
2730    let mut context = Context {
2731        count: 0,
2732        index_map: OrderIndexMap::default(),
2733        non_custom_index_map: NonCustomReferenceMap::default(),
2734        stack: SmallVec::new(),
2735        var_info: SmallVec::new(),
2736        stylist,
2737        computed_context: &mut *computed_context,
2738        cascade: &mut *cascade,
2739        decls,
2740        cache: &mut *shorthand_cache,
2741        attribute_tracker: attr_tracker,
2742    };
2743    let mut first = true;
2744    let mut reset = |context: &mut Context| {
2745        if !first {
2746            context.reset();
2747        }
2748        first = false;
2749    };
2750    // Note that `seen` doesn't contain names inherited from our parent, but
2751    // those can't have variable references (since we inherit the computed
2752    // variables) so we don't want to spend cycles traversing them anyway.
2753    for (var, has_refs) in &seen.var {
2754        if !has_refs {
2755            continue;
2756        }
2757        reset(&mut context);
2758        traverse(
2759            VarType::Custom((*var).clone()),
2760            references_from_non_custom_properties,
2761            &mut context,
2762        );
2763    }
2764    // Traverse non-custom properties that reference `attr()`.
2765    for (longhand_id, unparsed_value) in &seen.attr {
2766        reset(&mut context);
2767        let property_id = PropertyIdRef::from(match unparsed_value.from_shorthand {
2768            Some(shorthand_id) => NonCustomPropertyId::from(shorthand_id),
2769            None => NonCustomPropertyId::from(*longhand_id),
2770        });
2771        let value = &unparsed_value.variable_value;
2772        let mut lowlink = usize::MAX;
2773        let mut self_ref = false;
2774        visit_value_references(
2775            None,
2776            &value.references,
2777            value,
2778            usize::MAX,
2779            property_id,
2780            references_from_non_custom_properties,
2781            &mut context,
2782            &mut lowlink,
2783            &mut self_ref,
2784            &mut Default::default(),
2785        );
2786    }
2787}