1use 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#[derive(Copy, Clone)]
56#[allow(missing_docs)]
57pub enum FirstLineReparenting<'a> {
58 No,
59 Yes {
60 style_to_reparent: &'a ComputedValues,
64 },
65}
66
67pub 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 guards: &'a StylesheetGuards<'a>,
123 restriction: PropertyFlags,
124 current_rule_node: Option<&'a StrongRuleNode>,
126 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 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#[derive(Clone, Copy)]
240pub enum CascadeMode<'a, 'b> {
241 Unvisited {
243 visited_rules: Option<&'a StrongRuleNode>,
245 },
246 Visited {
248 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
275pub 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 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 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 using_cached_reset_properties = false;
356 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 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 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 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
457type 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 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 color
510 .to_computed_value(context)
511 .resolve_to_absolute(&AbsoluteColor::BLACK)
512 .alpha
513 }
514
515 match **declaration {
517 PropertyDeclaration::CSSWideKeyword(..) => return,
519 PropertyDeclaration::BackgroundColor(ref color) => {
520 if color.honored_in_forced_colors_mode(context, true) {
530 return;
531 }
532 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 if color
547 .0
548 .honored_in_forced_colors_mode(context, true)
549 {
550 return;
551 }
552 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 #[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 if let Some(color) = declaration.color_value()
595 && color
596 .honored_in_forced_colors_mode(context, false)
597 {
598 return;
599 }
600 },
601 }
602
603 *declaration.to_mut() =
604 PropertyDeclaration::css_wide_keyword(longhand_id, CSSWideKeyword::Revert);
605}
606
607type DeclarationIndex = u16;
609
610#[derive(Copy, Clone)]
615struct PrioritaryDeclarationPosition {
616 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#[derive(Default)]
639pub(crate) struct Declarations<'a> {
640 has_prioritary_properties: bool,
642 longhand_declarations: SmallVec<[Declaration<'a>; 64]>,
644 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 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 position.most_important = new_index;
664 } else {
665 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 longhands_set: LonghandIdSet,
692 longhands: FxHashMap<LonghandId, (CascadePriority, RevertKind)>,
693 custom: PrecomputedHashMap<Name, (CascadePriority, RevertKind)>,
694}
695
696#[derive(Default)]
697struct SeenSubstitutionFunctions<'a> {
698 var: PrecomputedHashMap<&'a Name, bool>,
701 attr: Vec<(LonghandId, Arc<UnparsedValue>)>,
703}
704
705#[derive(Default)]
706struct SeenSet<'a> {
707 longhands: LonghandIdSet,
708 custom: SeenSubstitutionFunctions<'a>,
709}
710
711fn 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 result |= ReferenceFlags::COLOR_SCHEME;
732 }
733 result
734}
735
736pub struct KeyframeCustomPropertiesBuilder<'a> {
745 cascade: Cascade<'a>,
746 decls: Declarations<'a>,
747 shorthand_cache: ShorthandsWithPropertyReferencesCache,
748}
749
750impl<'a> KeyframeCustomPropertiesBuilder<'a> {
751 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 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 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 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 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 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 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 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 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 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 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 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 (CASCADE_PROPERTY[longhand_id as usize])(declaration, context);
1174 }
1175 }
1176
1177 #[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 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 Default::default(),
1222 context.included_cascade_flags,
1223 None, &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 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 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 #[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 builder.mutate_font().mFont.family.families =
1374 FontFamily::generic(default_font_type).families.clone();
1375 }
1376
1377 #[inline]
1379 #[cfg(feature = "gecko")]
1380 fn prioritize_user_fonts_if_needed(&self, builder: &mut StyleBuilder) {
1381 use crate::gecko_bindings::bindings;
1382
1383 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 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 #[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 #[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 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 #[cfg(feature = "gecko")]
1514 fn recompute_math_font_size_if_needed(context: &mut computed::Context) {
1515 use crate::values::generics::NonNegative;
1516
1517 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 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 let scale = {
1599 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 if parent_size <= min {
1624 (parent_size, new_unconstrained_size)
1625 } else {
1626 (min.max(new_size), new_unconstrained_size)
1627 }
1628 } else {
1629 (
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 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 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 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 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 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 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 CustomDeclarationValue::Parsed(..) => false,
1782 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 substitute_references_if_needed_and_apply(
1797 name,
1798 SubstitutionFunctionKind::Var,
1799 unparsed_value,
1800 self.stylist,
1801 context,
1802 &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 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 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 CSSWideKeyword::Revert
1858 | CSSWideKeyword::RevertLayer
1859 | CSSWideKeyword::RevertRule
1860 | CSSWideKeyword::Unset => unreachable!(),
1861 },
1862 },
1863 }
1864 }
1865
1866 #[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 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 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 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 if registration.inherits() {
1949 return false;
1950 }
1951 },
1952 CustomDeclarationValue::CSSWideKeyword(CSSWideKeyword::Initial) => {
1953 if !registration.inherits() {
1956 return false;
1957 }
1958 },
1959 CustomDeclarationValue::CSSWideKeyword(CSSWideKeyword::Unset) => {
1960 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 if registration.initial_value.is_none() {
1982 return false;
1983 }
1984 }
1985 return true;
1986 };
1987 match value {
1988 CustomDeclarationValue::Unparsed(value) => {
1989 if let Some(existing_value) = existing_value.as_universal() {
1992 return existing_value != value;
1993 }
1994 },
1995 CustomDeclarationValue::Parsed(..) => {
1996 },
1999 CustomDeclarationValue::CSSWideKeyword(kw) => {
2000 match kw {
2001 CSSWideKeyword::Inherit => {
2002 debug_assert!(!registration.inherits(), "Should've been handled earlier");
2003 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 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 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 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 #[derive(Clone, Eq, PartialEq, Debug)]
2098 enum VarType {
2099 Attr(Name),
2100 Custom(Name),
2101 NonCustom(SingleNonCustomReference),
2102 }
2103
2104 #[derive(Debug)]
2106 struct VarInfo {
2107 var: Option<VarType>,
2111 lowlink: usize,
2115 }
2116
2117 #[derive(Debug, Default)]
2118 struct OrderIndexMap {
2119 var: PrecomputedHashMap<Name, usize>,
2121 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 struct Context<'a, 'b: 'a, 'c, 'd, 'e> {
2135 count: usize,
2138 index_map: OrderIndexMap,
2140 non_custom_index_map: NonCustomReferenceMap<usize>,
2142 var_info: SmallVec<[VarInfo; 5]>,
2144 stack: SmallVec<[usize; 5]>,
2147 stylist: &'a Stylist,
2150 computed_context: &'a mut computed::Context<'b>,
2153 cascade: &'a mut Cascade<'c>,
2157 decls: &'a Declarations<'d>,
2159 cache: &'a mut ShorthandsWithPropertyReferencesCache,
2161 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 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 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 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 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 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 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 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 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 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 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 None => return,
2444 };
2445 let next_info = &context.var_info[next_index];
2446 if next_index > index {
2447 *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 *lowlink = cmp::min(*lowlink, next_index);
2457 }
2458 }
2459
2460 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 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 (
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 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 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 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 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 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_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 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 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 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 return Some(index);
2668 }
2669
2670 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 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 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 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 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 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 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 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}