Skip to content

Truly independent web browser

LibWeb: Style a document in breadth-first passes over a thread pool

Andreas Klingbf682f61681a
diff --git a/Cargo.lock b/Cargo.lock
index eed5ecf40eb..a6f92121ce5 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -291,6 +291,31 @@ dependencies = [
"libm",
]
+[[package]]
+name = "crossbeam-deque"
+version = "0.8.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"
+dependencies = [
+ "crossbeam-epoch",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-epoch"
+version = "0.9.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-utils"
+version = "0.8.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
+
[[package]]
name = "displaydoc"
version = "0.2.5"
@@ -966,6 +991,7 @@ dependencies = [
"libgfx_rust",
"liburl_rust",
"libweb_html_tokenizer",
+ "rayon",
"rustc-demangle",
"serde_json",
"smallvec",
@@ -1135,6 +1161,26 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+[[package]]
+name = "rayon"
+version = "1.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
+dependencies = [
+ "either",
+ "rayon-core",
+]
+
+[[package]]
+name = "rayon-core"
+version = "1.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
+dependencies = [
+ "crossbeam-deque",
+ "crossbeam-utils",
+]
+
[[package]]
name = "regex"
version = "1.12.3"
diff --git a/Libraries/LibWeb/CSS/ComputedStyleWorkingSet.cpp b/Libraries/LibWeb/CSS/ComputedStyleWorkingSet.cpp
index 36cac2969c0..b09dc4e8438 100644
--- a/Libraries/LibWeb/CSS/ComputedStyleWorkingSet.cpp
+++ b/Libraries/LibWeb/CSS/ComputedStyleWorkingSet.cpp
@@ -43,58 +43,26 @@ AnimatedProperties::~AnimatedProperties()
static_assert(to_underlying(PseudoElement::KnownPseudoElementCount) <= sizeof(u64) * 8);
-ComputedStyleWorkingSet::ComputedStyleWorkingSet()
- : m_computed_longhand_table(ComputedValuesFFI::rust_computed_longhand_table_create())
+ComputedStyleWorkingSet::ComputedStyleWorkingSet(StyleRecordRef record)
+ : m_record(move(record))
+ , m_metadata(ComputedValuesFFI::rust_style_record_metadata(m_record.get()))
{
}
-ComputedStyleWorkingSet::ComputedStyleWorkingSet(ComputedValuesFFI::ComputedLonghandTable* longhand_table)
- : m_computed_longhand_table(longhand_table)
-{
-}
-
-ComputedStyleWorkingSet::~ComputedStyleWorkingSet()
-{
- ComputedValuesFFI::rust_computed_longhand_table_release(m_computed_longhand_table);
-}
-
-NonnullRefPtr<ComputedStyleWorkingSet> ComputedStyleWorkingSet::create()
-{
- return adopt_ref(*new ComputedStyleWorkingSet);
-}
+ComputedStyleWorkingSet::~ComputedStyleWorkingSet() = default;
-NonnullRefPtr<ComputedStyleWorkingSet> ComputedStyleWorkingSet::create_with_longhand_table(ComputedValuesFFI::ComputedLonghandTable* longhand_table)
+NonnullRefPtr<ComputedStyleWorkingSet> ComputedStyleWorkingSet::create_over_record(StyleRecordRef record)
{
- VERIFY(longhand_table);
- return adopt_ref(*new ComputedStyleWorkingSet(longhand_table));
+ VERIFY(record.get());
+ return adopt_ref(*new ComputedStyleWorkingSet(move(record)));
}
NonnullRefPtr<ComputedStyleWorkingSet> ComputedStyleWorkingSet::create_with_base_values_from(ComputedValues const& style)
{
- auto working_set = create();
auto const& base = style.base_values();
- // Seed the table with the previous drive's computed values so unevaluated longhands read
- // and publish without reverse-materialization; the funnel overwrites what this drive
- // evaluates. A borrowed record view seeds from its interned value span. The base always
- // carries a table: property() has no other source for an unevaluated longhand's value.
- if (auto const* table = base.computed_longhand_table()) {
- ComputedValuesFFI::rust_computed_longhand_table_copy_from(working_set->m_computed_longhand_table, static_cast<ComputedValuesFFI::ComputedLonghandTable const*>(table));
- } else {
- auto longhand_values = base.computed_longhand_values();
- VERIFY(!longhand_values.is_empty());
- ComputedValuesFFI::rust_computed_longhand_table_copy_from_values(working_set->m_computed_longhand_table, longhand_values.data(), longhand_values.size());
- }
- // A fresh drive starts with nothing evaluated and re-records its own inheritance-dependent
- // specified values; the flag bitmaps seed from the base style's published bitmaps, which a
- // borrowed record view carries even though it owns no table.
- ComputedValuesFFI::rust_computed_longhand_table_clear_seeded_state(working_set->m_computed_longhand_table);
- auto importance = base.property_importance_bitmap();
- auto inheritance = base.property_inheritance_bitmap();
- ComputedValuesFFI::rust_computed_longhand_table_load_flag_bitmaps(working_set->m_computed_longhand_table, importance, inheritance);
- for (auto const& entry : base.inheritance_dependent_specified_values())
- ComputedValuesFFI::rust_computed_longhand_table_add_inheritance_dependent_value(working_set->m_computed_longhand_table, entry.property, entry.value);
+ // The base style's record holds every longhand's value, so an unevaluated longhand reads it in place.
+ auto working_set = create_over_record(base.record());
working_set->set_display_before_box_type_transformation(base.display_before_box_type_transformation());
- working_set->set_has_pseudo_element_styles(base.pseudo_element_style_mask());
if (base.depends_on_viewport_metrics())
working_set->set_depends_on_viewport_metrics();
if (base.font_metrics_depend_on_viewport_metrics())
@@ -104,12 +72,9 @@ NonnullRefPtr<ComputedStyleWorkingSet> ComputedStyleWorkingSet::create_with_base
return working_set;
}
-NonnullRefPtr<ComputedStyleWorkingSet> ComputedStyleWorkingSet::create_for_animation_update(ComputedValuesFFI::ComputedLonghandTable const* table, ComputedValuesFFI::AnimatedOverlay const* overlay)
+NonnullRefPtr<ComputedStyleWorkingSet> ComputedStyleWorkingSet::create_for_animation_update(void const* record, ComputedValuesFFI::AnimatedOverlay const* overlay)
{
- VERIFY(table);
- auto* retained_table = const_cast<ComputedValuesFFI::ComputedLonghandTable*>(ComputedValuesFFI::rust_computed_longhand_table_retain(table));
- auto working_set = create_with_longhand_table(retained_table);
- working_set->m_computed_longhand_table_is_shared = true;
+ auto working_set = create_over_record(StyleRecordRef { record });
if (overlay) {
working_set->m_had_animated_post_compute_adjustment_property = ComputedValuesFFI::rust_animated_overlay_contains(overlay, to_underlying(PropertyID::Display))
|| ComputedValuesFFI::rust_animated_overlay_contains(overlay, to_underlying(PropertyID::Position))
@@ -124,22 +89,6 @@ NonnullRefPtr<ComputedStyleWorkingSet> ComputedStyleWorkingSet::create_for_anima
return working_set;
}
-void ComputedStyleWorkingSet::ensure_mutable_computed_longhand_table()
-{
- if (!m_computed_longhand_table_is_shared)
- return;
- auto* table = ComputedValuesFFI::rust_computed_longhand_table_create();
- ComputedValuesFFI::rust_computed_longhand_table_copy_from(table, m_computed_longhand_table);
- ComputedValuesFFI::rust_computed_longhand_table_release(m_computed_longhand_table);
- m_computed_longhand_table = table;
- m_computed_longhand_table_is_shared = false;
-}
-
-void ComputedStyleWorkingSet::freeze_computed_longhand_table()
-{
- ComputedValuesFFI::rust_computed_longhand_table_freeze(m_computed_longhand_table);
-}
-
AnimatedProperties::AnimatedProperties()
: m_identity(s_next_animated_properties_identity.fetch_add(1, AK::MemoryOrder::memory_order_relaxed))
, m_overlay(ComputedValuesFFI::rust_animated_overlay_create())
@@ -236,16 +185,6 @@ void AnimatedProperties::set_property(PropertyID id, NonnullRefPtr<StyleValue co
m_wrapper_cache.set(id, move(value));
}
-ReadonlyBytes ComputedStyleWorkingSet::property_importance_bitmap() const
-{
- return { ComputedValuesFFI::rust_computed_longhand_table_importance_bits(m_computed_longhand_table), (number_of_longhand_properties + 7) / 8 };
-}
-
-ReadonlyBytes ComputedStyleWorkingSet::property_inheritance_bitmap() const
-{
- return { ComputedValuesFFI::rust_computed_longhand_table_inheritance_bits(m_computed_longhand_table), (number_of_longhand_properties + 7) / 8 };
-}
-
RefPtr<AnimatedProperties const> ComputedStyleWorkingSet::animated_properties_snapshot() const
{
return m_animated_properties;
@@ -261,20 +200,6 @@ bool ComputedStyleWorkingSet::has_animated_property(PropertyID property_id) cons
return animated_properties().has_property(property_id);
}
-bool ComputedStyleWorkingSet::has_pseudo_element_style(PseudoElement pseudo_element) const
-{
- VERIFY(to_underlying(pseudo_element) < to_underlying(PseudoElement::KnownPseudoElementCount));
- return metadata().pseudo_element_styles & (1ull << to_underlying(pseudo_element));
-}
-
-void ComputedStyleWorkingSet::set_has_pseudo_element_styles(u64 pseudo_element_styles)
-{
- constexpr auto known_pseudo_element_count = to_underlying(PseudoElement::KnownPseudoElementCount);
- if constexpr (known_pseudo_element_count < sizeof(u64) * 8)
- VERIFY((pseudo_element_styles >> known_pseudo_element_count) == 0);
- metadata().pseudo_element_styles |= pseudo_element_styles;
-}
-
void ComputedStyleWorkingSet::set_depends_on_viewport_metrics()
{
metadata().dependency_flags |= to_underlying(StyleRecordDependencyFlag::DependsOnViewportMetrics);
@@ -333,11 +258,6 @@ bool ComputedStyleWorkingSet::requires_animated_post_compute_adjustments() const
|| has_animated_property(PropertyID::TextAlign);
}
-void ComputedStyleWorkingSet::prepare_for_animated_post_compute_adjustments(Badge<StyleComputer>)
-{
- ensure_mutable_computed_longhand_table();
-}
-
void ComputedStyleWorkingSet::set_animated_custom_property(Badge<StyleComputer>, Utf16FlyString name, NonnullRefPtr<StyleValue const> value)
{
m_animated_custom_properties.set(move(name), move(value));
@@ -374,15 +294,14 @@ StyleValue const& ComputedStyleWorkingSet::property(PropertyID property_id, With
VERIFY(property_id >= first_longhand_property_id && property_id <= last_longhand_property_id);
auto& cache = m_minted_wrappers;
- // Without an animated overlay, a cached wrapper is always the effective value: the store
- // funnels replace or invalidate the entry on every table write, and the recorded specified
- // values invalidate it when they change.
+ // Without an animated overlay, a cached wrapper is always the effective value: the record
+ // the values are read from never changes.
if (!m_animated_properties) {
if (auto it = cache.find(property_id); it != cache.end())
return *it->value;
}
- auto effective = ComputedValuesFFI::rust_computed_longhand_table_effective_value(
- m_computed_longhand_table,
+ auto effective = ComputedValuesFFI::rust_style_record_effective_value(
+ m_record.get(),
m_animated_properties ? m_animated_properties->overlay() : nullptr,
to_underlying(property_id),
return_animated_value == WithAnimationsApplied::Yes);
@@ -406,8 +325,8 @@ StyleValue const& ComputedStyleWorkingSet::property(PropertyID property_id, With
StyleValueFFI::StyleValueData const* ComputedStyleWorkingSet::effective_property_data(PropertyID property_id, WithAnimationsApplied return_animated_value) const
{
VERIFY(property_id >= first_longhand_property_id && property_id <= last_longhand_property_id);
- auto effective = ComputedValuesFFI::rust_computed_longhand_table_effective_value(
- m_computed_longhand_table,
+ auto effective = ComputedValuesFFI::rust_style_record_effective_value(
+ m_record.get(),
m_animated_properties ? m_animated_properties->overlay() : nullptr,
to_underlying(property_id),
return_animated_value == WithAnimationsApplied::Yes);
diff --git a/Libraries/LibWeb/CSS/ComputedStyleWorkingSet.h b/Libraries/LibWeb/CSS/ComputedStyleWorkingSet.h
index 17fd9f47837..bcc75cbf355 100644
--- a/Libraries/LibWeb/CSS/ComputedStyleWorkingSet.h
+++ b/Libraries/LibWeb/CSS/ComputedStyleWorkingSet.h
@@ -38,12 +38,11 @@ enum class AnimatedPropertyResultOfTransition : u8 {
Yes
};
-// The style computation drive's working state: the Rust computed longhand table the drive
-// stores into, plus the genuinely-C++ residue no record can carry - the GC style sheet
-// sidecar for on-demand wrapper stamping, the sparse wrapper mint cache, the computed font
-// list cache, and the AnimatedProperties overlay association. Post-drive readers consume the
-// published ComputedValues / style record instead; this object only survives the drive for
-// the animation refresh paths that re-sample the overlay against the frozen table.
+// What the host computes an element's style update in on the main thread, as an animation or
+// transition update or the document's own style does: the style record whose longhands it reads,
+// what it settles beside them, plus the genuinely-C++ residue no record can carry - the sparse
+// wrapper mint cache, the computed font list cache, and the AnimatedProperties overlay
+// association.
class ComputedStyleWorkingSet final : public RefCounted<ComputedStyleWorkingSet> {
public:
enum class WithAnimationsApplied {
@@ -56,25 +55,17 @@ public:
Yes
};
- static NonnullRefPtr<ComputedStyleWorkingSet> create();
- static NonnullRefPtr<ComputedStyleWorkingSet> create_with_longhand_table(ComputedValuesFFI::ComputedLonghandTable*);
+ static NonnullRefPtr<ComputedStyleWorkingSet> create_over_record(StyleRecordRef);
static NonnullRefPtr<ComputedStyleWorkingSet> create_with_base_values_from(ComputedValues const&);
- static NonnullRefPtr<ComputedStyleWorkingSet> create_for_animation_update(ComputedValuesFFI::ComputedLonghandTable const*, ComputedValuesFFI::AnimatedOverlay const*);
+ static NonnullRefPtr<ComputedStyleWorkingSet> create_for_animation_update(void const* record, ComputedValuesFFI::AnimatedOverlay const*);
~ComputedStyleWorkingSet();
- // Freezes the computed longhand table once the drive has stored every longhand. The
- // animated overlay and the dependency flags stay mutable for the refresh paths.
- void freeze_computed_longhand_table();
-
- void set_has_pseudo_element_styles(u64);
void set_depends_on_viewport_metrics();
void set_font_metrics_depend_on_viewport_metrics();
- // The wrapper-carrying store funnel: dual-writes the Rust table and the wrapper cache.
void set_display_before_box_type_transformation(Display);
bool has_effective_color_scheme() const { return metadata().effective_color_scheme >= 0; }
- void set_effective_color_scheme(PreferredColorScheme color_scheme) { metadata().effective_color_scheme = to_underlying(color_scheme); }
RefPtr<AnimatedProperties const> animated_properties_snapshot() const;
ComputedValuesFFI::AnimatedOverlay const* animated_overlay() const;
@@ -83,7 +74,6 @@ public:
bool font_metrics_depend_on_viewport_metrics() const { return metadata().dependency_flags & to_underlying(StyleRecordDependencyFlag::FontMetricsDependOnViewportMetrics); }
// Whether the element this style was computed for has computed display none, or is a descendant of one that does.
bool in_display_none_subtree() const { return metadata().in_display_none_subtree; }
- bool has_pseudo_element_style(PseudoElement) const;
ComputedValuesFFI::AnimatedOverlay* prepare_animated_overlay_for_rust_mutation(Badge<StyleComputer>);
ComputedValuesFFI::AnimatedOverlay* prepare_animated_overlay_for_rust_finalization(Badge<StyleComputer>);
ComputedValuesFFI::AnimatedOverlay const* animated_overlay(Badge<StyleComputer>) const;
@@ -91,7 +81,6 @@ public:
// Hold every value of `overlay` as the working set's animated values, as the computation that sampled them did.
void install_animated_overlay(Badge<StyleComputer>, ComputedValuesFFI::AnimatedOverlay const*);
bool requires_animated_post_compute_adjustments() const;
- void prepare_for_animated_post_compute_adjustments(Badge<StyleComputer>);
void set_animated_custom_property(Badge<StyleComputer>, Utf16FlyString name, NonnullRefPtr<StyleValue const> value);
void clear_animated_properties(Badge<StyleComputer>);
OrderedHashMap<Utf16FlyString, NonnullRefPtr<StyleValue const>> const& animated_custom_properties() const { return m_animated_custom_properties; }
@@ -116,19 +105,11 @@ public:
Vector<ComputedFontFamily> computed_font_families() const;
FontOpticalSizing font_optical_sizing() const;
- // Whole-bitmap views over the table's importance and inheritance flags, in FixedBitmap
- // byte layout; valid while the table is.
- ReadonlyBytes property_importance_bitmap() const;
- ReadonlyBytes property_inheritance_bitmap() const;
-
- // The drive's computed longhand table, for transfer onto the ComputedValues built from
- // this working set.
- ComputedValuesFFI::ComputedLonghandTable* mutable_computed_longhand_table() { return m_computed_longhand_table; }
- ComputedValuesFFI::ComputedLonghandTable const* computed_longhand_table() const { return m_computed_longhand_table; }
+ // The style record whose longhands this working set reads.
+ void const* record() const { return m_record.get(); }
private:
- ComputedStyleWorkingSet();
- explicit ComputedStyleWorkingSet(ComputedValuesFFI::ComputedLonghandTable*);
+ explicit ComputedStyleWorkingSet(StyleRecordRef);
AnimatedProperties const& animated_properties() const;
AnimatedProperties& mutable_animated_properties();
@@ -138,28 +119,23 @@ private:
double font_weight() const;
Percentage font_width() const;
int font_slope() const;
- ComputedValuesFFI::FfiComputedStyleMetadata& metadata()
- {
- ensure_mutable_computed_longhand_table();
- return *ComputedValuesFFI::rust_computed_longhand_table_metadata(m_computed_longhand_table);
- }
- ComputedValuesFFI::FfiComputedStyleMetadata const& metadata() const { return *ComputedValuesFFI::rust_computed_longhand_table_metadata(m_computed_longhand_table); }
- void ensure_mutable_computed_longhand_table();
+ ComputedValuesFFI::FfiComputedStyleMetadata& metadata() { return m_metadata; }
+ ComputedValuesFFI::FfiComputedStyleMetadata const& metadata() const { return m_metadata; }
void clear_computed_font_list_cache()
{
m_cached_computed_font_list = nullptr;
m_cached_first_available_computed_font = nullptr;
}
- // The source of truth for computed longhand values and their importance, inheritance
- // and evaluation flags plus the recorded inheritance-dependent specified values,
- // written by the store funnels and the flag setters and frozen when the drive completes.
- ComputedValuesFFI::ComputedLonghandTable* m_computed_longhand_table { nullptr };
- bool m_computed_longhand_table_is_shared { false };
+ // The source of truth for computed longhand values and their importance and inheritance
+ // flags, with the recorded inheritance-dependent specified values.
+ StyleRecordRef m_record;
+ // What the host settles beside the record's values, starting from what the record's
+ // computation settled.
+ ComputedValuesFFI::FfiComputedStyleMetadata m_metadata;
// The sparse per-longhand mint cache over the effective values: an entry holds the
- // wrapper a store funnel carried or the one property() minted on demand, and is replaced
- // or invalidated when the drive stores new table data for the longhand. Overlay values
- // are never cached here; their wrappers live on AnimatedProperties.
+ // wrapper property() minted on demand. Overlay values are never cached here; their
+ // wrappers live on AnimatedProperties.
mutable HashMap<PropertyID, NonnullRefPtr<StyleValue const>> m_minted_wrappers;
RefPtr<AnimatedProperties> m_animated_properties;
bool m_had_animated_post_compute_adjustment_property { false };
diff --git a/Libraries/LibWeb/CSS/StyleComputer.cpp b/Libraries/LibWeb/CSS/StyleComputer.cpp
index 7932c0e8d54..48471bc14e5 100644
--- a/Libraries/LibWeb/CSS/StyleComputer.cpp
+++ b/Libraries/LibWeb/CSS/StyleComputer.cpp
@@ -110,26 +110,6 @@
namespace Web::CSS {
-static Utf16View utf16_view(ComputedValuesFFI::FfiUtf16View view)
-{
- if (view.length == 0)
- return {};
- VERIFY((view.latin1 == nullptr) != (view.utf16 == nullptr));
- if (view.latin1)
- return Utf16View::from_latin1({ view.latin1, view.length }, false);
- return { reinterpret_cast<char16_t const*>(view.utf16), view.length };
-}
-
-// The custom properties the style queries of a substitution read are the element's style query
-// references, as a style query in a container condition records them.
-static void record_style_query_dependencies(DOM::AbstractElement element, void* dependencies)
-{
- ComputedValuesFFI::rust_style_query_dependencies_take(dependencies, &element, [](void* context, ComputedValuesFFI::FfiUtf16View name) {
- auto& element = *static_cast<DOM::AbstractElement*>(context);
- element.element().record_style_query_custom_property_reference(element.pseudo_element(), Utf16FlyString::from_utf16(utf16_view(name)));
- });
-}
-
class Fnv1a64 {
public:
void add(u64 value)
@@ -146,16 +126,6 @@ private:
GC_DEFINE_ALLOCATOR(StyleComputer);
-// What a rule contributes, for the two rule types that carry a declaration block.
-static RustDeclarationBlock const& declaration_of_rule(CSSRule const& rule)
-{
- if (rule.type() == CSSRule::Type::Style)
- return static_cast<CSSStyleRule const&>(rule).declaration();
- if (rule.type() == CSSRule::Type::NestedDeclarations)
- return static_cast<CSSNestedDeclarations const&>(rule).declaration();
- VERIFY_NOT_REACHED();
-}
-
StyleComputer::StyleComputer(DOM::Document& document)
: m_document(document)
, m_default_font_metrics(16, Platform::FontPlugin::the().default_font(16)->pixel_metrics(), normal_line_height(Platform::FontPlugin::the().default_font(16)->pixel_metrics()))
@@ -199,41 +169,47 @@ Parser::ValueParserFFI::FfiMediaEnvironment const* StyleComputer::ensure_media_e
return &*m_style_update_ffi_media_environment;
}
-ComputedStyleRecordView StyleComputer::computed_style_record_view(Layout::BegunRead const& read, StyleRecordID style_record_identity) const
-{
- return computed_style_record_view(install_style(read, style_record_identity));
-}
-
ComputedStyleRecordView StyleComputer::computed_style_record_view(InstalledStyle const& style) const
{
if (!style)
return {};
- // A view held across a later install keeps the record it borrows from live.
- bool owns_style_record_pin = m_style_record_view_epoch_depth == 0 || style.view().animation_overlay_identity != 0;
- if (owns_style_record_pin) {
- pin_style_record(style.record());
- ++m_computed_style_record_view_pin_count;
- }
- return ComputedStyleRecordView { style.view(), *this, style.record(), owns_style_record_pin };
+ // NB: The view holds the style it reads, so it reads it however long it lives.
+ return ComputedStyleRecordView { style };
}
InstalledStyle StyleComputer::install_style(Layout::BegunRead const& read, StyleRecordID style_record) const
{
if (!style_record)
return {};
- return { style_record, m_style_engine.style_record_view(read, style_record) };
+ return InstalledStyle { m_style_engine.host_record(read, style_record) };
+}
+
+void StyleComputer::begin_style_installation()
+{
+ if (m_style_installation_depth++ == 0)
+ m_installation_subtree_style_generation = ++m_subtree_style_generation;
+}
+
+void StyleComputer::end_style_installation()
+{
+ VERIFY(m_style_installation_depth > 0);
+ if (--m_style_installation_depth == 0)
+ m_custom_property_environments_noted_during_installation.clear();
}
-void StyleComputer::pin_style_record(StyleRecordID style_record_identity) const
+u64 StyleComputer::subtree_style_generation_for_move()
{
- VERIFY(style_record_identity);
- StyleEngineFFI::style_engine_pin_style_record(m_style_engine.host(), style_record_identity.value());
+ if (m_style_installation_depth > 0)
+ return m_installation_subtree_style_generation;
+ return ++m_subtree_style_generation;
}
-void StyleComputer::unpin_style_record(StyleRecordID style_record_identity) const
+bool StyleComputer::custom_property_environment_needs_note(CustomPropertyData const& environment) const
{
- VERIFY(style_record_identity);
- StyleEngineFFI::style_engine_unpin_style_record(m_style_engine.host(), style_record_identity.value());
+ if (m_style_installation_depth == 0)
+ return true;
+ // NB: The table holds what it names, so no other environment can take an identity it remembers.
+ return m_custom_property_environments_noted_during_installation.set(environment.identity(), environment) == HashSetResult::InsertedNewEntry;
}
void StyleComputer::begin_style_record_view_epoch() const
@@ -259,6 +235,9 @@ void StyleComputer::register_style_node(StyleNodeID style_node_id, DOM::Node& no
return;
}
m_element_style_nodes[style_node_index(style_node_id)] = node;
+ // NB: An HTML element is neither of the kinds below, which most elements are spared asking.
+ if (node.is_html_element())
+ return;
// Registration is where an element's publications keyed by its style node begin: an attribute written before it
// had one published nothing.
if (auto* svg_element = as_if<SVG::SVGElement>(node))
@@ -299,7 +278,6 @@ void StyleComputer::unregister_style_node(StyleNodeID style_node_id)
m_element_style_nodes[index] = nullptr;
m_style_nodes_retired_beside_lanes.set(style_node_id);
StyleEngineFFI::style_engine_consume_element_style_input(m_style_engine.host(), style_node_id);
- m_style_engine.note_style_node_arrived_or_retired(style_node_id);
}
}
@@ -364,14 +342,6 @@ void StyleComputer::prepare_elements_for_style_computation()
}
}
-void StyleComputer::for_each_style_node(Function<void(DOM::Element&)> callback) const
-{
- for (auto node : m_element_style_nodes) {
- if (auto* element = as_if<DOM::Element>(node.ptr()))
- callback(*element);
- }
-}
-
void StyleComputer::visit_edges(Visitor& visitor)
{
Base::visit_edges(visitor);
@@ -404,24 +374,24 @@ void StyleComputer::begin_transition_stabilization_epoch()
VERIFY(m_provisional_transition_state_indices_by_target.is_empty());
}
-void StyleComputer::record_transition_stabilization_baseline(DOM::AbstractElement abstract_element, StyleRecordID before_change_style_record) const
+void StyleComputer::record_transition_stabilization_baseline(DOM::AbstractElement abstract_element, InstalledStyle const& before_change_style) const
{
auto style_node_id = abstract_element.element().style_node_id();
if (style_node_id == 0)
return;
// Few epochs record a baseline, so only one that does asks for or releases them.
m_transition_baselines_recorded = true;
- StyleEngineFFI::style_engine_record_transition_baseline(m_style_engine.host(), style_node_id, pseudo_element_to_ffi(abstract_element.pseudo_element()), before_change_style_record.value());
+ StyleEngineFFI::style_engine_record_transition_baseline(m_style_engine.host(), style_node_id, pseudo_element_to_ffi(abstract_element.pseudo_element()), before_change_style.record_pointer());
}
// https://drafts.csswg.org/css-transitions-2/#defining-before-change-style
// A later pass of this stabilization epoch can give the element a transition it does not declare yet, which is decided
// against the style the element moved away from in this one. Size container queries and the feedback epoch run such
// passes.
-void StyleComputer::record_transition_baseline_for_later_passes(DOM::AbstractElement abstract_element, StyleRecordID before_change_style_record) const
+void StyleComputer::record_transition_baseline_for_later_passes(DOM::AbstractElement abstract_element, InstalledStyle const& before_change_style) const
{
if (abstract_element.style_scope().rule_cache().has_size_container_queries || document().is_in_style_stabilization_feedback_epoch())
- record_transition_stabilization_baseline(abstract_element, before_change_style_record);
+ record_transition_stabilization_baseline(abstract_element, before_change_style);
}
// A provisionally started transition already contributed to the style published by the pass that
@@ -553,8 +523,8 @@ static RefPtr<CustomPropertyData const> inheritable_custom_property_data(Layout:
struct StyleComputer::AnimationSample {
AK_ALLOC_WITH_KMALLOC;
- AnimationSample(GC::Ref<StyleComputer const> style_computer, DOM::AbstractElement abstract_element, ComputedStyleWorkingSet& computed_properties, Layout::BegunRead const& read)
- : context { style_computer, abstract_element, computed_properties, read }
+ AnimationSample(GC::Ref<StyleComputer const> style_computer, DOM::AbstractElement abstract_element, ComputedStyleWorkingSet& computed_properties)
+ : context { style_computer, abstract_element, computed_properties }
{
}
@@ -562,7 +532,6 @@ struct StyleComputer::AnimationSample {
GC::Ref<StyleComputer const> style_computer;
DOM::AbstractElement abstract_element;
ComputedStyleWorkingSet& computed_properties;
- Layout::BegunRead const& read;
} context;
Vector<ComputedValuesFFI::FfiSampledAnimationEffect, 1> sampled_effects;
Vector<Vector<Compositing::RustFFI::FfiLinearEasingPoint>, 1> easing_points;
@@ -577,9 +546,8 @@ struct StyleComputer::AnimationSample {
void StyleComputer::collect_animations_into(Layout::BegunRead const& read, DOM::AbstractElement abstract_element, ReadonlySpan<GC::Ref<Animations::KeyframeEffect>> effects, ComputedStyleWorkingSet& computed_properties) const
{
- m_keyframes_inherited_non_inherited_style_groups = 0;
// A refresh samples over the record the element holds, which the working set was reconstructed from.
- collect_animation_effects_into(read, abstract_element, effects, computed_properties, abstract_element.style_record_identity());
+ collect_animation_effects_into(read, abstract_element, effects, computed_properties);
finish_animation_refresh(read, abstract_element, computed_properties);
}
@@ -593,7 +561,7 @@ void StyleComputer::refresh_animations_into_each(Layout::BegunRead const& read,
samples.ensure_capacity(requests.size());
inputs.ensure_capacity(requests.size());
for (auto const& request : requests) {
- samples.unchecked_append(begin_animation_sample(read, request.abstract_element, request.effects, request.computed_properties, request.abstract_element.style_record_identity()));
+ samples.unchecked_append(begin_animation_sample(read, request.abstract_element, request.effects, request.computed_properties));
inputs.unchecked_append(samples.last()->input);
}
Vector<ComputedValuesFFI::FfiHostAnimationSampleResult> results;
@@ -601,7 +569,6 @@ void StyleComputer::refresh_animations_into_each(Layout::BegunRead const& read,
ComputedValuesFFI::rust_sample_animation_effects_each(inputs.data(), inputs.size(), &read, results.data());
for (size_t index = 0; index < requests.size(); ++index) {
auto const& request = requests[index];
- m_keyframes_inherited_non_inherited_style_groups = 0;
finish_animation_sample(*samples[index], results[index]);
finish_animation_refresh(read, request.abstract_element, request.computed_properties);
}
@@ -609,19 +576,9 @@ void StyleComputer::refresh_animations_into_each(Layout::BegunRead const& read,
void StyleComputer::finish_animation_refresh(Layout::BegunRead const& read, DOM::AbstractElement abstract_element, ComputedStyleWorkingSet& computed_properties) const
{
- publish_animated_custom_properties(read, computed_properties, abstract_element);
- // An animation-only overlay update resolves keyframe values just like a full style computation does, so a
- // keyframe-borne `inherit` on a non-inherited property discovered here must leave the same invalidation
- // mark behind, or a later change to the parent's value never reaches this element's animated style.
- if (m_keyframes_inherited_non_inherited_style_groups != 0) {
- if (auto* parent = abstract_element.element().parent())
- parent->add_children_explicitly_inherited_non_inherited_style_groups(m_keyframes_inherited_non_inherited_style_groups);
- m_keyframes_inherited_non_inherited_style_groups = 0;
- }
- if (computed_properties.requires_animated_post_compute_adjustments()) {
- computed_properties.prepare_for_animated_post_compute_adjustments(Badge<StyleComputer> {});
+ publish_animated_custom_properties(computed_properties, abstract_element);
+ if (computed_properties.requires_animated_post_compute_adjustments())
finalize_animated_box_type(read, computed_properties, abstract_element);
- }
}
// The engine decides the timing only where every time is in one unit: a duration, or a percentage of a scroll
@@ -682,16 +639,16 @@ ComputedValuesFFI::FfiEffectTiming style_engine_effect_timing(Animations::Keyfra
return timing;
}
-void StyleComputer::collect_animation_effects_into(Layout::BegunRead const& read, DOM::AbstractElement abstract_element, ReadonlySpan<GC::Ref<Animations::KeyframeEffect>> effects, ComputedStyleWorkingSet& computed_properties, StyleRecordID sampled_style_record) const
+void StyleComputer::collect_animation_effects_into(Layout::BegunRead const& read, DOM::AbstractElement abstract_element, ReadonlySpan<GC::Ref<Animations::KeyframeEffect>> effects, ComputedStyleWorkingSet& computed_properties) const
{
- auto sample = begin_animation_sample(read, abstract_element, effects, computed_properties, sampled_style_record);
+ auto sample = begin_animation_sample(read, abstract_element, effects, computed_properties);
auto result = ComputedValuesFFI::rust_sample_animation_effects(&sample->input, &read);
finish_animation_sample(*sample, result);
}
-NonnullOwnPtr<StyleComputer::AnimationSample> StyleComputer::begin_animation_sample(Layout::BegunRead const& read, DOM::AbstractElement abstract_element, ReadonlySpan<GC::Ref<Animations::KeyframeEffect>> effects, ComputedStyleWorkingSet& computed_properties, StyleRecordID sampled_style_record) const
+NonnullOwnPtr<StyleComputer::AnimationSample> StyleComputer::begin_animation_sample(Layout::BegunRead const& read, DOM::AbstractElement abstract_element, ReadonlySpan<GC::Ref<Animations::KeyframeEffect>> effects, ComputedStyleWorkingSet& computed_properties) const
{
- auto sample = make<AnimationSample>(*this, abstract_element, computed_properties, read);
+ auto sample = make<AnimationSample>(*this, abstract_element, computed_properties);
// The style engine samples each effect from the description it holds of it, kept current here, right before
// the element is sampled.
auto const animation_slot = abstract_element.pseudo_element().map([](auto pseudo_element) { return static_cast<u8>(to_underlying(pseudo_element) + 1); }).value_or(0);
@@ -731,7 +688,7 @@ NonnullOwnPtr<StyleComputer::AnimationSample> StyleComputer::begin_animation_sam
auto& inheritance_custom_property_data = sample->inheritance_custom_property_data;
custom_property_data = abstract_element.custom_property_data();
base_custom_property_data = custom_property_data;
- if (base_custom_property_data && base_custom_property_data->is_animation_overlay_for(abstract_element))
+ if (base_custom_property_data && abstract_element.custom_property_data_is_animation_overlay())
base_custom_property_data = base_custom_property_data->parent();
auto inheritance_parent = abstract_element.element_to_inherit_style_from();
inheritance_custom_property_data = inheritance_parent.has_value() ? inheritance_parent->custom_property_data() : nullptr;
@@ -779,9 +736,9 @@ NonnullOwnPtr<StyleComputer::AnimationSample> StyleComputer::begin_animation_sam
.pseudo_kind = abstract_element.pseudo_element().map([](auto pseudo_element) { return static_cast<u8>(to_underlying(pseudo_element)); }).value_or(NumericLimits<u8>::max()),
.effects = sampled_effects.data(),
.effect_count = sampled_effects.size(),
- .longhand_table = computed_properties.computed_longhand_table(),
+ .record = computed_properties.record(),
.animated_overlay = computed_properties.animated_overlay(Badge<StyleComputer> {}),
- .style_record = sampled_style_record.value(),
+ .style_record = abstract_element.installed_style().record_pointer(),
.custom_property_store = custom_property_data ? custom_property_data->rust_store() : nullptr,
.base_custom_property_store = base_custom_property_data ? base_custom_property_data->rust_store() : nullptr,
.inheritance_custom_property_store = inheritance_custom_property_data ? inheritance_custom_property_data->rust_store() : nullptr,
@@ -791,7 +748,7 @@ NonnullOwnPtr<StyleComputer::AnimationSample> StyleComputer::begin_animation_sam
inheritance_custom_property_data ? inheritance_custom_property_data->identity() : 0,
},
.custom_property_registration_generation = document().custom_property_registration_generation(),
- .inheritance_parent_style_record = inheritance_parent.has_value() ? inheritance_parent->style_record_identity().value() : 0,
+ .inheritance_parent_record = inheritance_parent.has_value() ? inheritance_parent->installed_style().record_pointer() : nullptr,
.environment = &sample->environment,
.element_box_slot = Layout::Node::slot_id(abstract_element.element().unsafe_layout_node(read)).index,
.callback_context = &sample->context,
@@ -804,7 +761,7 @@ NonnullOwnPtr<StyleComputer::AnimationSample> StyleComputer::begin_animation_sam
// Each context is the sampled element's own, built afresh: a batch builds several elements' contexts in one call.
auto length_context_for = [&](PropertyID property_id) {
return to_ffi_length_resolution_context_with_container_bases(
- sample.style_computer->make_computation_context_for_property(sample.read, property_id, sample.computed_properties, sample.abstract_element).length_resolution_context,
+ sample.style_computer->make_computation_context_for_property(property_id, sample.computed_properties, sample.abstract_element).length_resolution_context,
container_relative_length_unit_mask);
};
contexts->font = length_context_for(PropertyID::FontFamily);
@@ -821,18 +778,12 @@ void StyleComputer::finish_animation_sample(AnimationSample& sample, ComputedVal
// What the substituted values read is what the element's style now depends on, as for a value its cascade
// substituted.
auto& element = abstract_element.element();
- if (result.substitution_marks & ComputedValuesFFI::SUBSTITUTION_MARK_VAR)
- element.set_style_uses_var_css_function();
if (result.substitution_marks & ComputedValuesFFI::SUBSTITUTION_MARK_ATTR)
element.set_style_uses_attr_css_function();
if (result.substitution_marks & ComputedValuesFFI::SUBSTITUTION_MARK_IF)
element.set_style_uses_if_css_function();
- if (result.substitution_marks & ComputedValuesFFI::SUBSTITUTION_MARK_INHERIT)
- element.set_style_uses_inherit_css_function();
if (result.substitution_marks & ComputedValuesFFI::SUBSTITUTION_MARK_CUSTOM_FUNCTION)
element.set_style_uses_custom_function();
- if (result.style_query_dependencies)
- record_style_query_dependencies(abstract_element, result.style_query_dependencies);
switch (result.outcome) {
case ComputedValuesFFI::FfiHostAnimationSampleOutcome::Unchanged:
@@ -844,7 +795,6 @@ void StyleComputer::finish_animation_sample(AnimationSample& sample, ComputedVal
break;
}
computed_properties.set_animated_custom_properties_trigger_restyle(Badge<StyleComputer> {}, result.custom_properties_trigger_restyle);
- m_keyframes_inherited_non_inherited_style_groups |= result.keyframes_inherited_non_inherited_style_groups;
if (result.depends_on_viewport_metrics)
computed_properties.set_depends_on_viewport_metrics();
if (result.font_metrics_depend_on_viewport_metrics)
@@ -859,27 +809,56 @@ void StyleComputer::finish_animation_sample(AnimationSample& sample, ComputedVal
computed_properties.finish_animated_overlay_rust_mutation(Badge<StyleComputer> {});
}
-void StyleComputer::publish_animated_custom_properties(Layout::BegunRead const& read, ComputedStyleWorkingSet& computed_properties, DOM::AbstractElement abstract_element) const
+// NB: A dependency cycle among animated values and what the element declares is invalid, which the sample answers. One
+// it cannot name, through a custom function or attr(), or an animation that its own values start and end, would
+// feed each pass into the next with no end. In an acyclic chain an element's values move only as what they read
+// does, at most once per value animated on it and above it, so values still moving after that stop where they are.
+bool StyleComputer::animated_custom_properties_may_move(DOM::AbstractElement abstract_element, size_t animated_value_count) const
+{
+ auto& document = abstract_element.document();
+ if (!document.is_in_style_stabilization_epoch())
+ return true;
+ constexpr u64 ordinary_change_limit = 8;
+ auto const changes = document.note_animated_custom_properties_moved_in_stabilization_epoch(abstract_element.element().style_node_id());
+ if (changes <= ordinary_change_limit)
+ return true;
+ u64 animated_above = animated_value_count;
+ for (auto ancestor = abstract_element.element_to_inherit_style_from(); ancestor.has_value(); ancestor = ancestor->element_to_inherit_style_from()) {
+ if (auto ancestor_data = ancestor->custom_property_data(); ancestor_data && ancestor->custom_property_data_is_animation_overlay())
+ animated_above += ancestor_data->declared_count();
+ }
+ return changes <= ordinary_change_limit + animated_above;
+}
+
+void StyleComputer::stop_publishing_animated_custom_properties(DOM::AbstractElement abstract_element) const
{
auto data = abstract_element.custom_property_data();
+ if (!data || !abstract_element.custom_property_data_is_animation_overlay())
+ return;
+ if (!animated_custom_properties_may_move(abstract_element, data->declared_count()))
+ return;
+ abstract_element.replace_custom_property_data(Badge<StyleComputer> {}, data->parent(), IsAnimationOverlay::No);
+ invalidate_animated_custom_property_readers(abstract_element, true);
+}
+
+void StyleComputer::publish_animated_custom_properties(ComputedStyleWorkingSet& computed_properties, DOM::AbstractElement abstract_element) const
+{
+ auto data = abstract_element.custom_property_data();
+ bool const holds_animation_overlay = data && abstract_element.custom_property_data_is_animation_overlay();
RefPtr<CustomPropertyData const> base = data;
- if (data && data->is_animation_overlay_for(abstract_element))
+ if (holds_animation_overlay)
base = data->parent();
auto const& animated_values = computed_properties.animated_custom_properties();
if (animated_values.is_empty()) {
- if (base.ptr() != data.ptr()) {
- abstract_element.replace_custom_property_data(Badge<StyleComputer> {}, base);
- invalidate_animated_custom_property_readers(read, abstract_element, animated_values, move(data), true);
- }
+ stop_publishing_animated_custom_properties(abstract_element);
return;
}
- if (data && data->is_animation_overlay_for(abstract_element) && data->own_values().size() == animated_values.size()) {
+ if (holds_animation_overlay && data->declared_count() == animated_values.size()) {
bool values_unchanged = true;
for (auto const& [name, value] : animated_values) {
- auto existing = data->own_values().find(name);
- if (existing == data->own_values().end() || !existing->value.value->equals(*value)) {
+ if (!data->declares_value(name, *value)) {
values_unchanged = false;
break;
}
@@ -888,6 +867,9 @@ void StyleComputer::publish_animated_custom_properties(Layout::BegunRead const&
return;
}
+ if (!animated_custom_properties_may_move(abstract_element, animated_values.size()))
+ return;
+
OrderedHashMap<Utf16FlyString, StyleProperty> overlay_values;
for (auto const& [name, value] : animated_values) {
overlay_values.set(name,
@@ -897,11 +879,11 @@ void StyleComputer::publish_animated_custom_properties(Layout::BegunRead const&
.value = value,
});
}
- abstract_element.replace_custom_property_data(Badge<StyleComputer> {}, CustomPropertyData::create_animation_overlay(move(overlay_values), move(base), abstract_element));
- invalidate_animated_custom_property_readers(read, abstract_element, animated_values, move(data), computed_properties.animated_custom_properties_trigger_restyle());
+ abstract_element.replace_custom_property_data(Badge<StyleComputer> {}, CustomPropertyData::create_animation_overlay(move(overlay_values), move(base)), IsAnimationOverlay::Yes);
+ invalidate_animated_custom_property_readers(abstract_element, computed_properties.animated_custom_properties_trigger_restyle());
}
-void StyleComputer::invalidate_animated_custom_property_readers(Layout::BegunRead const& read, DOM::AbstractElement abstract_element, OrderedHashMap<Utf16FlyString, NonnullRefPtr<StyleValue const>> const& animated_values, RefPtr<CustomPropertyData const> old_data, bool recompute_style) const
+void StyleComputer::invalidate_animated_custom_property_readers(DOM::AbstractElement abstract_element, bool recompute_style) const
{
auto& element = abstract_element.element();
auto& style_engine = element.document().style_computer().style_engine();
@@ -911,26 +893,8 @@ void StyleComputer::invalidate_animated_custom_property_readers(Layout::BegunRea
// Style container queries can read animated values even when those values do not inherit.
element.invalidate_descendant_styles_depending_on_style_container_query();
}
-
- if (abstract_element.pseudo_element().has_value())
- return;
-
- auto any_custom_property_inherits = [&](auto const& values) {
- for (auto const& [name, value] : values) {
- auto registration = m_document->get_registered_custom_property(name);
- if (!registration.has_value() || registration->inherit)
- return true;
- }
- return false;
- };
- // What the element hands down moved too. Its descendants take the moved environment as they take one a style
- // reaction moved: only those that read a name whose value moved compute again. Include names from the previous
- // animation overlay, since an inheriting property may have stopped animating while non-inheriting ones remain.
- bool const new_values_inherit = any_custom_property_inherits(animated_values);
- bool const old_values_inherit = old_data && old_data->is_animation_overlay_for(abstract_element)
- && any_custom_property_inherits(old_data->own_values());
- if (new_values_inherit || old_values_inherit)
- move_custom_property_environment_below_animated_element(read, element, move(old_data));
+ // NB: The style engine restyles the children of an element whose animations sampled other custom properties
+ // itself, as the engine learns of the element's new environment.
}
// The host's form of one animation definition a style computation decided.
@@ -1068,31 +1032,31 @@ void StyleComputer::apply_settled_animation_plan(Layout::BegunRead const& read,
} context { *this, abstract_element };
auto const* animations = abstract_element.css_defined_animations();
bool has_animations = animations && !animations->is_empty();
- ComputedValuesFFI::rust_settled_animation_plan(m_style_engine.host(), &read, abstract_element.element().style_node_id().value(), pseudo_element_to_ffi(abstract_element.pseudo_element()), abstract_element.style_record_identity().value(), has_animations, &context, [](void* context_pointer, ComputedValuesFFI::FfiComputedAnimation const* definitions, size_t count, bool in_display_none_subtree) {
+ ComputedValuesFFI::rust_settled_animation_plan(m_style_engine.host(), &read, abstract_element.element().style_node_id().value(), pseudo_element_to_ffi(abstract_element.pseudo_element()), abstract_element.installed_style().record_pointer(), has_animations, &context, [](void* context_pointer, ComputedValuesFFI::FfiComputedAnimation const* definitions, size_t count, bool in_display_none_subtree) {
auto& context = *static_cast<Context*>(context_pointer);
context.style_computer->apply_animation_definitions(context.abstract_element, { definitions, count }, in_display_none_subtree);
});
}
-// A C++ computation applies the animation plan it decides beside the record it computes, and collects the animations of
-// the element or pseudo-element, those the plan starts among them, into that record. For a record the engine settled,
-// the host applies the plan once the record is installed and samples the animations over it, as an animation update
-// samples them over the record an element holds, and publishes what they compose.
+// The host applies the animation plan of a record the engine settled once the record is installed and samples the
+// animations over it, as an animation update samples them over the record an element holds, and publishes what they
+// compose.
// https://drafts.csswg.org/css-transitions-2/#defining-before-change-style
// Sampling the installed record can keep the epoch's before-change style, and the record held by then is the
// after-change one, so a record that owes the transition step keeps the record it moved away from first.
-void StyleComputer::compose_installed_engine_record(Layout::BegunRead const& read, DOM::AbstractElement abstract_element, StyleRecordID before_change_style_record) const
+void StyleComputer::compose_installed_engine_record(Layout::BegunRead const& read, DOM::AbstractElement abstract_element, InstalledStyle const& before_change_style) const
{
apply_settled_animation_plan(read, abstract_element);
- if (!!before_change_style_record && document().is_in_style_stabilization_epoch())
- record_transition_stabilization_baseline(abstract_element, before_change_style_record);
- auto& element = abstract_element.element();
- if (!element.has_relevant_animations() && !element.has_associated_animations())
+ if (before_change_style && document().is_in_style_stabilization_epoch())
+ record_transition_stabilization_baseline(abstract_element, before_change_style);
+ if (!has_animations_to_compose(abstract_element)) {
+ stop_publishing_animated_custom_properties(abstract_element);
return;
- auto style_record = abstract_element.style_record_identity();
- if (!style_record)
+ }
+ auto const& style = abstract_element.installed_style();
+ if (!style)
return;
- Animations::AnimationUpdateContext::ElementData element_data { style_record, reconstruct_computed_properties_for_animation(read, style_record) };
+ Animations::AnimationUpdateContext::ElementData element_data { style, reconstruct_computed_properties_for_animation(style) };
element_data.base_is_current = true;
Animations::AnimationUpdateContext context;
context.elements.set(abstract_element, move(element_data));
@@ -1142,20 +1106,20 @@ static void collect_aspect_ratio_from_dimension_values(Vector<StyleProperty>& pr
// The whole transition step for an element's record, run once the record is installed.
//
// The step needs two styles: the one the element moved away from, which the caller names, and the one it moved to,
-// which is the record just installed. Both are records, and the step reads the before-change half only through
-// `decide_transitions`' baseline. A transition the step starts layers its current values into the after-change style to
+// which is the record just installed. Both are records, and the step reads the before-change half only through the
+// transition baseline. A transition the step starts layers its current values into the after-change style to
// keep the frame from jumping; publishing that is the same animation overlay publication an animation sample performs,
// on the same element, over the same base, and the step samples the transitions over the installed record as such a
// sample does: the box-type transformation of the values they take adjusts the composition, and the base stays current.
-RequiredInvalidationAfterStyleChange StyleComputer::run_transition_step_for_installed_record(Layout::BegunRead const& read, DOM::AbstractElement abstract_element, StyleRecordID before_change_style_record) const
+RequiredInvalidationAfterStyleChange StyleComputer::run_transition_step_for_installed_record(Layout::BegunRead const& read, DOM::AbstractElement abstract_element, InstalledStyle const& before_change_style) const
{
- auto installed_style_record = abstract_element.style_record_identity();
- if (!installed_style_record || !before_change_style_record)
+ auto const installed_style = abstract_element.installed_style();
+ if (!installed_style || !before_change_style)
return {};
auto& element = abstract_element.element();
auto pseudo_element = abstract_element.pseudo_element();
- record_transition_baseline_for_later_passes(abstract_element, before_change_style_record);
+ record_transition_baseline_for_later_passes(abstract_element, before_change_style);
// OPTIMIZATION: The transition entries and existing transitions `start_needed_transitions` decides over, plus this
// element's own provisional states. With none of them there is nothing to decide, and the
@@ -1168,11 +1132,9 @@ RequiredInvalidationAfterStyleChange StyleComputer::run_transition_step_for_inst
// A transition starts from the before-change style the epoch keeps, if any, and never from a style under
// display: none. The installed record may itself be display: none; checking it would skip the discrete transition
// into that state.
- if (m_transition_baselines_recorded) {
- if (auto baseline = StyleEngineFFI::style_engine_transition_baseline(m_style_engine.host(), element.style_node_id().value(), pseudo_element_to_ffi(pseudo_element)); baseline != 0)
- before_change_style_record = StyleRecordID { baseline };
- }
- if (has_flag(m_style_engine.style_record_dependency_flags(read, before_change_style_record), StyleRecordDependencyFlag::InDisplayNoneSubtree))
+ InstalledStyle const baseline { m_transition_baselines_recorded ? StyleEngineFFI::style_engine_transition_baseline(m_style_engine.host(), element.style_node_id().value(), pseudo_element_to_ffi(pseudo_element)) : nullptr };
+ auto const& before_change = baseline ? baseline : before_change_style;
+ if (has_flag(before_change.dependency_flags(), StyleRecordDependencyFlag::InDisplayNoneSubtree))
return {};
if (auto parent = abstract_element.element_to_inherit_style_from(); parent.has_value()) {
if (auto parent_style = parent->computed_style(); parent_style && parent_style->in_display_none_subtree())
@@ -1181,10 +1143,10 @@ RequiredInvalidationAfterStyleChange StyleComputer::run_transition_step_for_inst
begin_style_update();
ScopeGuard end_style_update = [&] { this->end_style_update(); };
- auto new_style = start_needed_transitions(read, abstract_element, before_change_style_record);
+ auto new_style = start_needed_transitions(read, abstract_element, before_change);
if (!new_style)
return {};
- auto const* installed_overlay = static_cast<ComputedValuesFFI::AnimatedOverlay const*>(m_style_engine.style_record_view(read, installed_style_record).animated_overlay);
+ auto const* installed_overlay = static_cast<ComputedValuesFFI::AnimatedOverlay const*>(installed_style.view().animated_overlay);
// A step that starts, ends or replaces nothing leaves the installed record as it stands.
if (installed_overlay) {
@@ -1196,7 +1158,7 @@ RequiredInvalidationAfterStyleChange StyleComputer::run_transition_step_for_inst
SampledAnimationOverlay const overlay { abstract_element, *new_style };
StyleEngineFFI::FfiAnimationOverlayPublication publication;
publish_sampled_animation_overlays(read, { &overlay, 1 }, { &publication, 1 });
- element.refresh_computed_style(pseudo_element, StyleRecordID { publication.publication.new_style_record });
+ element.refresh_computed_style(read, pseudo_element, InstalledStyle::adopt(publication.record));
if (auto* svg_element = as_if<SVG::SVGElement>(element); svg_element && !pseudo_element.has_value())
svg_element->note_svg_paint_resource_description_may_have_changed();
return decode_style_invalidation(publication.invalidation.invalidation);
@@ -1211,7 +1173,7 @@ static u64 transition_target_key(DOM::AbstractElement abstract_element)
}
// https://drafts.csswg.org/css-transitions/#starting
-RefPtr<ComputedStyleWorkingSet> StyleComputer::start_needed_transitions(Layout::BegunRead const& read, DOM::AbstractElement abstract_element, StyleRecordID before_change_style_record) const
+RefPtr<ComputedStyleWorkingSet> StyleComputer::start_needed_transitions(Layout::BegunRead const& read, DOM::AbstractElement abstract_element, InstalledStyle const& before_change_style) const
{
auto had_pending_animated_style_update = m_document->needs_animated_style_update();
@@ -1310,7 +1272,7 @@ RefPtr<ComputedStyleWorkingSet> StyleComputer::start_needed_transitions(Layout::
.target_pseudo_kind = pseudo_element_to_ffi(pseudo_element),
.element_box_slot = Layout::Node::slot_id(element.unsafe_layout_node(read)).index,
};
- StyleEngineFFI::style_engine_decide_transitions(m_style_engine.host(), &read, before_change_style_record.value(), abstract_element.style_record_identity().value(), &input, [](void* context, StyleValueFFI::FfiTransitionAction const* actions, size_t count) { (*static_cast<decltype(on_actions)*>(context))({ actions, count }); }, &on_actions);
+ StyleEngineFFI::style_engine_decide_transitions(m_style_engine.host(), &read, before_change_style.record_pointer(), abstract_element.installed_style().record_pointer(), &input, [](void* context, StyleValueFFI::FfiTransitionAction const* actions, size_t count) { (*static_cast<decltype(on_actions)*>(context))({ actions, count }); }, &on_actions);
// A transition action is provisional until the stabilization epoch commits, but the style
// published by this pass must already reflect that decision. Rebuild the effect stack without
@@ -1320,7 +1282,7 @@ RefPtr<ComputedStyleWorkingSet> StyleComputer::start_needed_transitions(Layout::
// OPTIMIZATION: Transition decisions read the installed records directly. Reconstruct a working style only when
// changes to the effect stack require rebuilding the overlay.
- auto new_style = reconstruct_computed_properties_for_animation(read, abstract_element.style_record_identity());
+ auto new_style = reconstruct_computed_properties_for_animation(abstract_element.installed_style());
new_style->clear_animated_properties(Badge<StyleComputer> {});
auto animations = abstract_element.element().get_animations_internal(
Animations::Animatable::GetAnimationsSorted::Yes,
@@ -1364,6 +1326,14 @@ bool StyleComputer::has_provisional_transition_states(DOM::AbstractElement abstr
return m_provisional_transition_state_indices_by_target.contains(transition_target_key(abstract_element));
}
+// What composes over the record an element or pseudo-element holds: the animations associated with the element, and the
+// transitions this stabilization epoch started for it, which are associated with it only once the epoch commits.
+bool StyleComputer::has_animations_to_compose(DOM::AbstractElement abstract_element) const
+{
+ auto const& element = abstract_element.element();
+ return element.has_relevant_animations() || element.has_associated_animations() || has_provisional_transition_states(abstract_element);
+}
+
void StyleComputer::register_style_engine_sheet_source(StyleSheetState const& sheet)
{
auto identity = Parser::ValueParserFFI::rust_style_sheet_identity(sheet.native_sheet().handle());
@@ -1375,7 +1345,7 @@ Optional<StyleEngineRuleTarget> StyleComputer::style_engine_rule_target(Layout::
StyleEngineFFI::FfiNativeRuleTarget target {};
if (!StyleEngineFFI::style_engine_native_rule_target(m_style_engine.host(), &read, rule_id.value(), &target))
return {};
- RustDeclarationBlockSnapshot declaration { static_cast<Parser::ValueParserFFI::DeclarationBlockData const*>(target.declarations) };
+ RustDeclarationBlockSnapshot declaration { static_cast<Parser::ValueParserFFI::DeclarationBlockHeader const*>(target.declarations) };
auto source = m_style_engine_sheet_sources.get(target.source_identity);
if (!source.has_value())
return {};
@@ -1414,419 +1384,6 @@ void StyleComputer::set_style_engine_sheet_id_for(StyleSheetState& sheet, SheetI
sheet.set_style_engine_sheet_id(sheet_id);
}
-static bool custom_property_inherits(DOM::Document const& document, Utf16FlyString const& name)
-{
- // A custom property inherits unless it has been registered with an explicit `inherits: false`.
- auto registration = document.get_registered_custom_property(name);
- return !registration.has_value() || registration->inherit;
-}
-
-enum class IsCustomProperty : u8 {
- No,
- Yes,
-};
-
-enum class Inherits : u8 {
- No,
- Yes,
-};
-
-enum class NameIsValid : u8 {
- No,
- Yes,
-};
-
-enum class IsValid : u8 {
- No,
- Yes,
-};
-
-static JsonObject serialize_devtools_style_declaration(
- String name,
- String value,
- Important important,
- IsCustomProperty is_custom_property,
- Inherits inherits,
- NameIsValid is_name_valid,
- IsValid is_valid)
-{
- JsonObject serialized_property;
- serialized_property.set("name"sv, move(name));
- serialized_property.set("value"sv, move(value));
- serialized_property.set("priority"sv, important == Important::Yes ? "important"sv : ""sv);
- serialized_property.set("isCustomProperty"sv, is_custom_property == IsCustomProperty::Yes);
- serialized_property.set("inherits"sv, inherits == Inherits::Yes);
- serialized_property.set("isNameValid"sv, is_name_valid == NameIsValid::Yes);
- serialized_property.set("isValid"sv, is_valid == IsValid::Yes);
- return serialized_property;
-}
-
-static JsonArray serialize_devtools_style_declarations(DOM::Document const& document, RustDeclarationBlock const& declaration)
-{
- JsonArray declarations;
-
- auto serialize_property = [&](Utf16FlyString const& name, StyleProperty const& property, IsCustomProperty is_custom_property, Inherits inherits) {
- declarations.must_append(serialize_devtools_style_declaration(
- name.to_utf16_string().to_utf8_but_should_be_ported_to_utf16(),
- property.value->to_string(SerializationMode::Normal),
- property.important,
- is_custom_property,
- inherits,
- NameIsValid::Yes,
- IsValid::Yes));
- };
-
- for (auto const& property : declaration.properties()) {
- serialize_property(
- string_from_property_id(property.property_id),
- property,
- IsCustomProperty::No,
- is_inherited_property(property.property_id) ? Inherits::Yes : Inherits::No);
- }
-
- for (auto const& custom_property : declaration.custom_properties())
- serialize_property(
- custom_property.key,
- custom_property.value,
- IsCustomProperty::Yes,
- custom_property_inherits(document, custom_property.key) ? Inherits::Yes : Inherits::No);
-
- return declarations;
-}
-
-static JsonArray serialize_devtools_style_declarations(DOM::Document const& document, Vector<Parser::DevToolsStyleDeclaration> const& declarations)
-{
- JsonArray serialized_declarations;
-
- for (auto const& declaration : declarations) {
- bool inherits = declaration.is_custom_property
- ? custom_property_inherits(document, declaration.name)
- : PropertyNameAndID::from_name(declaration.name)
- .map([](auto const& property) { return !property.is_custom_property() && is_inherited_property(property.id()); })
- .value_or(false);
-
- serialized_declarations.must_append(serialize_devtools_style_declaration(
- MUST(declaration.name.view().to_utf8()),
- declaration.value.to_utf8(),
- declaration.important,
- declaration.is_custom_property ? IsCustomProperty::Yes : IsCustomProperty::No,
- inherits ? Inherits::Yes : Inherits::No,
- declaration.is_name_valid ? NameIsValid::Yes : NameIsValid::No,
- declaration.is_valid ? IsValid::Yes : IsValid::No));
- }
-
- return serialized_declarations;
-}
-
-static Vector<Parser::DevToolsStyleDeclaration> parse_devtools_style_declarations(DOM::Document const& document, StringView declaration_block)
-{
- return Parser::parse_css_declaration_block_for_devtools(Parser::ParsingParams(document), declaration_block);
-}
-
-static Vector<Parser::DevToolsStyleDeclaration> parse_devtools_style_declarations(DOM::Document const& document, Utf16View declaration_block)
-{
- return Parser::parse_css_declaration_block_for_devtools(Parser::ParsingParams(document), declaration_block);
-}
-
-static Optional<size_t> source_offset_for_line_and_column(StringView source, SourcePosition const& position)
-{
- size_t line = 0;
- size_t column = 0;
-
- Utf8View source_code_points { source };
- for (auto it = source_code_points.begin(); it != source_code_points.end();) {
- auto offset = source_code_points.byte_offset_of(it);
- if (line == position.line && column == position.column)
- return offset;
-
- auto code_point = *it;
- ++it;
-
- if (code_point == '\r') {
- if (offset + 1 < source.length() && source[offset + 1] == '\n')
- ++it;
- ++line;
- column = 0;
- } else if (code_point == '\n' || code_point == '\f') {
- ++line;
- column = 0;
- } else {
- ++column;
- }
- }
-
- if (line == position.line && column == position.column)
- return source.length();
-
- return {};
-}
-
-static Optional<String> extract_css_declaration_block_from_source(CSSRule const& rule)
-{
- if (rule.type() != CSSRule::Type::Style)
- return {};
-
- auto const* style_sheet = rule.parent_style_sheet();
- if (!style_sheet)
- return {};
-
- auto const source_text = style_sheet->source_text();
- if (!source_text.has_value())
- return {};
-
- auto source = source_text->to_utf8();
- auto source_view = source.bytes_as_string_view();
- auto const& source_location = rule.source_location();
- if (!source_location.has_value())
- return {};
-
- auto maybe_offset = source_offset_for_line_and_column(source_view, *source_location);
- if (!maybe_offset.has_value())
- return {};
-
- Optional<u8> string_quote;
- bool in_comment = false;
- bool escaped = false;
- Optional<size_t> block_start;
- size_t block_depth = 0;
-
- for (size_t offset = *maybe_offset; offset < source_view.length(); ++offset) {
- auto ch = source_view[offset];
- auto next_ch = offset + 1 < source_view.length() ? source_view[offset + 1] : '\0';
-
- if (in_comment) {
- if (ch == '*' && next_ch == '/') {
- in_comment = false;
- ++offset;
- }
- continue;
- }
-
- if (string_quote.has_value()) {
- if (escaped) {
- escaped = false;
- continue;
- }
- if (ch == '\\') {
- escaped = true;
- continue;
- }
- if (ch == *string_quote)
- string_quote = {};
- continue;
- }
-
- if (ch == '/' && next_ch == '*') {
- in_comment = true;
- ++offset;
- continue;
- }
-
- if (ch == '"' || ch == '\'') {
- string_quote = ch;
- continue;
- }
-
- if (ch == '{') {
- if (!block_start.has_value())
- block_start = offset + 1;
- ++block_depth;
- continue;
- }
-
- if (ch == '}' && block_start.has_value()) {
- VERIFY(block_depth > 0);
- --block_depth;
- if (block_depth == 0)
- return MUST(String::from_utf8(source_view.substring_view(*block_start, offset - *block_start)));
- }
- }
-
- return {};
-}
-
-static bool has_inherited_declaration(DOM::Document const& document, ReadonlySpan<StyleProperty> properties, OrderedHashMap<Utf16FlyString, StyleProperty> const& custom_properties)
-{
- if (any_of(properties, [](auto const& property) {
- return CSS::is_inherited_property(property.property_id);
- })) {
- return true;
- }
-
- return any_of(custom_properties, [&](auto const& custom_property) {
- return custom_property_inherits(document, custom_property.key);
- });
-}
-
-static JsonObject serialize_devtools_style_sheet_identifier(StyleSheetIdentifier const& identifier)
-{
- JsonObject serialized_identifier;
- serialized_identifier.set("type"sv, style_sheet_identifier_type_to_string(identifier.type));
- if (identifier.dom_element_unique_id.has_value())
- serialized_identifier.set("domElementUniqueId"sv, identifier.dom_element_unique_id->value());
- if (identifier.url.has_value())
- serialized_identifier.set("url"sv, identifier.url->to_utf8());
- serialized_identifier.set("ruleCount"sv, identifier.rule_count);
- return serialized_identifier;
-}
-
-// What DevTools shows for one rule the engine says decides for this element. Which of the rule's
-// selectors matched is asked with a selector query, because the engine reports the rule rather than
-// the entry, and a panel can afford to match each selector again.
-static JsonObject serialize_devtools_applied_rule(DOM::Document& document, CSSRule const& rule, DOM::AbstractElement const& element)
-{
- auto const& declaration = declaration_of_rule(rule);
- auto authored_text = extract_css_declaration_block_from_source(rule);
- SelectorList const* selector_list = nullptr;
- if (auto const* style_rule = as_if<CSSStyleRule>(rule))
- selector_list = &style_rule->absolutized_selectors();
- else if (auto const* nested = as_if<CSSNestedDeclarations>(rule))
- selector_list = &nested->absolutized_selectors();
- SelectorList const empty_selectors;
- auto const& selectors = selector_list ? *selector_list : empty_selectors;
-
- JsonArray serialized_selectors;
- JsonArray specificities;
- JsonArray matched_selector_indexes;
- for (size_t index = 0; index < selectors.size(); ++index) {
- auto const& selector = selectors[index];
- serialized_selectors.must_append(selector->serialize().to_utf8());
- specificities.must_append(selector->specificity());
- SelectorList selector_query_list;
- selector_query_list.append(selector);
- auto selector_query = DOM::SelectorQuery::create(move(selector_query_list));
- if (selector_query->matches(element.element(), document))
- matched_selector_indexes.must_append(index);
- }
-
- JsonObject serialized_rule;
- serialized_rule.set("type"sv, to_underlying(rule.type()));
- serialized_rule.set("className"sv, rule.type() == CSSRule::Type::Style ? "CSSStyleRule"sv : "CSSNestedDeclarations"sv);
- serialized_rule.set("selectors"sv, move(serialized_selectors));
- serialized_rule.set("selectorsSpecificity"sv, move(specificities));
- serialized_rule.set("matchedSelectorIndexes"sv, move(matched_selector_indexes));
- serialized_rule.set("cssText"sv, rule.serialized().to_utf8());
- if (authored_text.has_value()) {
- serialized_rule.set("authoredText"sv, *authored_text);
- serialized_rule.set("declarations"sv, serialize_devtools_style_declarations(document, parse_devtools_style_declarations(document, authored_text->bytes_as_string_view())));
- } else {
- auto style = rule.type() == CSSRule::Type::Style
- ? static_cast<CSSStyleRule const&>(rule).style()
- : static_cast<CSSNestedDeclarations const&>(rule).style();
- serialized_rule.set("authoredText"sv, style->serialized().to_utf8());
- serialized_rule.set("declarations"sv, serialize_devtools_style_declarations(document, declaration));
- }
- if (auto* sheet = rule.parent_style_sheet()) {
- if (auto identifier = style_sheet_identifier_for(*sheet); identifier.has_value())
- serialized_rule.set("ruleId"sv, serialize_devtools_style_sheet_identifier(*identifier));
- }
- return serialized_rule;
-}
-
-static JsonObject serialize_devtools_inline_style(DOM::Document const& document, DOM::AbstractElement abstract_element, CSSStyleProperties const& declaration)
-{
- auto authored_text = abstract_element.element().get_attribute(HTML::AttributeNames::style);
-
- JsonObject serialized_rule;
- serialized_rule.set("type"sv, 100);
- serialized_rule.set("className"sv, 100);
- serialized_rule.set("cssText"sv, declaration.serialized().to_utf8());
- if (authored_text.has_value()) {
- auto authored_text_utf8 = authored_text->to_utf8();
- serialized_rule.set("authoredText"sv, authored_text_utf8);
- serialized_rule.set("declarations"sv, serialize_devtools_style_declarations(document, parse_devtools_style_declarations(document, authored_text->utf16_view())));
- } else {
- serialized_rule.set("authoredText"sv, declaration.serialized().to_utf8());
- serialized_rule.set("declarations"sv, serialize_devtools_style_declarations(document, declaration.declaration_block()));
- }
- serialized_rule.set("isSystem"sv, false);
- serialized_rule.set("nodeId"sv, abstract_element.element().unique_id().value());
- return serialized_rule;
-}
-
-static void append_devtools_applied_style_entry(JsonArray& entries, JsonObject rule, Optional<UniqueNodeID> inherited_node_id = {})
-{
- JsonObject entry;
-
- JsonValue matched_selector_indexes { JsonArray {} };
- if (auto value = rule.get("matchedSelectorIndexes"sv); value.has_value())
- matched_selector_indexes = *value;
- rule.remove("matchedSelectorIndexes"sv);
- auto is_system = rule.get_bool("isSystem"sv).value_or(false);
-
- entry.set("rule"sv, move(rule));
- entry.set("isSystem"sv, is_system);
- entry.set("matchedSelectorIndexes"sv, move(matched_selector_indexes));
- if (inherited_node_id.has_value())
- entry.set("inheritedNodeId"sv, inherited_node_id->value());
- else
- entry.set("inherited"sv, JsonValue {});
-
- entries.must_append(move(entry));
-}
-
-JsonArray StyleComputer::collect_devtools_applied_style_rules(Layout::BegunRead const& read, DOM::AbstractElement abstract_element, bool include_inherited, bool include_user_agent_styles)
-{
- JsonArray entries;
-
- auto append_rules_for_abstract_element = [&](DOM::AbstractElement current_element, Optional<UniqueNodeID> inherited_node_id) {
- if (auto inline_style = current_element.inline_style()) {
- if (!inherited_node_id.has_value() || has_inherited_declaration(m_document, inline_style->properties(), inline_style->custom_properties()))
- append_devtools_applied_style_entry(entries, serialize_devtools_inline_style(m_document, current_element, *inline_style), inherited_node_id);
- }
-
- auto node = current_element.element().style_node_id();
- if (node == 0)
- return;
- Vector<StyleEngine::RuleMatch> matches;
- if (!style_engine().match_element(read, node, matches, StyleEngine::MatchPurpose::Exact))
- return;
-
- // The engine reports the rules in the order the cascade applies them, and the panel lists
- // the winning one first.
- for (auto const& match : matches.in_reverse()) {
- if (match.pseudo_element != NumericLimits<u32>::max())
- continue;
- auto target = style_engine_rule_target(read, StyleEngineRuleID { match.rule });
- if (!target.has_value() || !target->source_style_sheet)
- continue;
- if (target->cascade_origin == CascadeOrigin::UserAgent && !include_user_agent_styles)
- continue;
- if (inherited_node_id.has_value()) {
- struct Context {
- GC::Ref<DOM::Document const> document;
- bool has_inherited_declaration { false };
- } context { m_document };
- Parser::ValueParserFFI::rust_declaration_data_visit(target->declaration.data(), &context, [](void* raw_context, Parser::ValueParserFFI::FfiDeclaredProperty const* property) {
- auto& context = *static_cast<Context*>(raw_context);
- if (context.has_inherited_declaration)
- return;
- if (property->name.length == 0)
- context.has_inherited_declaration = is_inherited_property(static_cast<PropertyID>(property->property_id));
- else
- context.has_inherited_declaration = custom_property_inherits(context.document, Utf16FlyString::from_utf16({ reinterpret_cast<char16_t const*>(property->name.utf16), property->name.length }));
- });
- if (!context.has_inherited_declaration)
- continue;
- }
- auto* rule = target->source_style_sheet->rules().rule_for_identity(target->rule_identity);
- if (!rule)
- continue;
- append_devtools_applied_style_entry(entries, serialize_devtools_applied_rule(m_document, *rule, current_element), inherited_node_id);
- }
- };
-
- append_rules_for_abstract_element(abstract_element, {});
-
- if (!include_inherited)
- return entries;
-
- for (auto current_element = abstract_element.element_to_inherit_style_from(); current_element.has_value(); current_element = current_element->element_to_inherit_style_from())
- append_rules_for_abstract_element(*current_element, current_element->element().unique_id());
-
- return entries;
-}
-
Vector<StyleProperty> StyleComputer::collect_presentational_hint_properties(DOM::AbstractElement abstract_element)
{
Vector<StyleProperty> properties;
@@ -1862,20 +1419,8 @@ Vector<StyleProperty> StyleComputer::collect_presentational_hint_properties(DOM:
return properties;
}
-RefPtr<CustomPropertyData const> StyleComputer::engine_custom_property_environment(Layout::BegunRead const& read, u64 identity, RefPtr<CustomPropertyData const> const& inherited) const
+static OrderedHashMap<Utf16FlyString, StyleProperty> own_values_of_custom_property_store(void const* store)
{
- if (!StyleEngine::is_engine_custom_property_environment(identity))
- return {};
- if (auto existing = m_engine_custom_property_environments.get(identity); existing.has_value())
- return *existing;
- u64 parent_identity = 0;
- auto const* store = StyleEngineFFI::style_engine_borrow_engine_custom_property_environment(m_style_engine.host(), &read, identity, &parent_identity);
- if (!store)
- return {};
- if (parent_identity != (inherited ? inherited->identity() : 0)) {
- ComputedValuesFFI::rust_custom_property_store_destroy(store);
- return {};
- }
OrderedHashMap<Utf16FlyString, StyleProperty> own_values;
ComputedValuesFFI::rust_custom_property_store_for_each_own_entry(store, &own_values, [](void* context, size_t name_raw, bool important, void const* data) {
auto& own_values = *static_cast<OrderedHashMap<Utf16FlyString, StyleProperty>*>(context);
@@ -1887,19 +1432,80 @@ RefPtr<CustomPropertyData const> StyleComputer::engine_custom_property_environme
.value = StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(static_cast<StyleValueFFI::StyleValueData const*>(data))),
});
});
- auto data = CustomPropertyData::create(move(own_values), inherited, store, identity);
- m_engine_custom_property_environments.set(identity, data);
- // What its children inherit is the engine's to name too: the children's environments are resolved over it.
- if (auto inheritable = StyleEngineFFI::style_engine_inheritable_custom_property_environment(m_style_engine.host(), &read, identity); inheritable != identity)
- data->set_inheritable(document(), inheritable == (inherited ? inherited->identity() : 0) ? inherited : engine_custom_property_environment(read, inheritable, inherited));
- return data;
+ return own_values;
+}
+
+RefPtr<CustomPropertyData const> StyleComputer::engine_custom_property_declarations_over(Layout::BegunRead const& read, u64 identity, RefPtr<CustomPropertyData const> const& inherited) const
+{
+ if (!m_style_engine.is_engine_custom_property_environment(read, identity))
+ return {};
+ u64 parent_identity = 0;
+ auto const* store = StyleEngineFFI::style_engine_borrow_engine_custom_property_environment(m_style_engine.host(), &read, identity, &parent_identity);
+ if (!store)
+ return {};
+ auto own_values = own_values_of_custom_property_store(store);
+ ComputedValuesFFI::rust_custom_property_store_destroy(store);
+ return CustomPropertyData::create(move(own_values), inherited);
+}
+
+RefPtr<CustomPropertyData const> StyleComputer::engine_custom_property_environment(Layout::BegunRead const& read, u64 identity, RefPtr<CustomPropertyData const> const& inherited) const
+{
+ if (!m_style_engine.is_engine_custom_property_environment(read, identity))
+ return {};
+ u64 parent_identity = 0;
+ auto const* store = StyleEngineFFI::style_engine_borrow_engine_custom_property_environment(m_style_engine.host(), &read, identity, &parent_identity);
+ if (!store)
+ return {};
+ if (parent_identity != (inherited ? inherited->identity() : 0)) {
+ ComputedValuesFFI::rust_custom_property_store_destroy(store);
+ return {};
+ }
+ // NB: The environment is the store, whose reference the engine handed over.
+ return CustomPropertyData::create({}, inherited, store);
+}
+
+RefPtr<CustomPropertyData const> StyleComputer::inheritable_custom_property_environment(Layout::BegunRead const& read, CustomPropertyData const& environment) const
+{
+ // NB: What an environment the style engine resolved hands down is the engine's to name, under the registrations as
+ // they are now: the environments its records resolve over the element's are built over that one.
+ if (m_style_engine.is_engine_custom_property_environment(read, environment.identity())) {
+ auto inheritable = StyleEngineFFI::style_engine_inheritable_custom_property_environment(m_style_engine.host(), &read, environment.identity());
+ if (!inheritable)
+ return nullptr;
+ return CustomPropertyData::of_store(reinterpret_cast<void const*>(static_cast<FlatPtr>(inheritable)));
+ }
+
+ // What one built here hands down is kept by its identity, under the registrations it was made under, so that every
+ // child inherits the same environment.
+ auto generation = document().custom_property_registration_generation();
+ if (m_inheritable_custom_property_environments_generation != generation) {
+ m_inheritable_custom_property_environments.clear();
+ m_inheritable_custom_property_environments_generation = generation;
+ }
+ if (auto existing = m_inheritable_custom_property_environments.get(environment.identity()); existing.has_value())
+ return existing->hands_down_itself ? RefPtr<CustomPropertyData const> { environment } : existing->inheritable;
+
+ RefPtr<CustomPropertyData const> inheritable_parent;
+ if (auto parent = environment.parent())
+ inheritable_parent = inheritable_custom_property_environment(read, *parent);
+ auto inheritable = environment.inheritable_impl(
+ inheritable_parent,
+ [&](Utf16FlyString const& name) { return document().get_registered_custom_property(name); });
+ bool const hands_down_itself = inheritable.ptr() == &environment;
+ m_inheritable_custom_property_environments.set(environment.identity(),
+ InheritableCustomPropertyEnvironment {
+ .environment = environment,
+ .inheritable = hands_down_itself ? nullptr : inheritable,
+ .hands_down_itself = hands_down_itself,
+ });
+ return inheritable;
}
// An environment nothing but the table holds is one no element is in, and the table is the only
-// thing keeping it - and its parent chain - alive.
+// thing keeping it - and what it hands down - alive.
void StyleComputer::sweep_custom_property_environments() const
{
- m_engine_custom_property_environments.remove_all_matching([](auto&, NonnullRefPtr<CustomPropertyData const> const& data) { return data->ref_count() == 1; });
+ m_inheritable_custom_property_environments.remove_all_matching([](auto&, InheritableCustomPropertyEnvironment const& entry) { return entry.environment->ref_count() == 1; });
}
void StyleComputer::update_root_element_font_metrics(ComputedValues const& values)
@@ -1958,15 +1564,14 @@ CSSPixels StyleComputer::absolute_size_mapping(AbsoluteSize absolute_size, CSSPi
VERIFY_NOT_REACHED();
}
-ComputationContext StyleComputer::make_computation_context_for_property(Layout::BegunRead const& read, PropertyID property_id, ComputedStyleWorkingSet const& style, Optional<DOM::AbstractElement> abstract_element) const
+ComputationContext StyleComputer::make_computation_context_for_property(PropertyID property_id, ComputedStyleWorkingSet const& style, Optional<DOM::AbstractElement> abstract_element) const
{
auto subject_inline_axis_is_horizontal = [&]() {
auto writing_mode = [&](DOM::AbstractElement const& candidate) -> Optional<WritingMode> {
- auto record = m_style_engine.style_record_view(read, candidate.style_record_identity());
+ auto record = candidate.installed_style().view();
if (!record.present)
return {};
- auto const* inherited_box = static_cast<ComputedValuesFFI::InheritedBoxValues const*>(record.payloads[to_underlying(StyleGroupIndex::InheritedBoxValues)]);
- return static_cast<WritingMode>(inherited_box->writing_mode);
+ return writing_mode_from_inherited_bits(style_record_inherited_values(record.groups).bits);
};
if (!abstract_element.has_value())
return true;
@@ -2087,7 +1692,7 @@ void StyleComputer::finalize_animated_box_type(Layout::BegunRead const& read, Co
auto box_type = ComputedValuesFFI::rust_animated_box_type_transformation_input(m_style_engine.host(), &read, abstract_element.element().style_node_id().value(), pseudo_element_to_ffi(abstract_element.pseudo_element()));
auto line_height_metrics = input_line_height_metrics(style, abstract_element, box_type.check_input_line_height);
auto* animated_overlay = style.prepare_animated_overlay_for_rust_finalization(Badge<StyleComputer> {});
- ComputedValuesFFI::rust_finalize_animated_box_type(box_type, style.mutable_computed_longhand_table(), animated_overlay, &line_height_metrics);
+ ComputedValuesFFI::rust_finalize_animated_box_type(box_type, style.record(), bit_cast<u32>(style.display_before_box_type_transformation()), animated_overlay, &line_height_metrics);
style.finish_animated_overlay_rust_mutation(Badge<StyleComputer> {});
}
@@ -2116,10 +1721,10 @@ StyleRecordID StyleComputer::intern_document_style(Layout::BegunRead const& read
.viewport_width = viewport_rect.width().to_double(),
.viewport_height = viewport_rect.height().to_double(),
};
- auto computed_properties = CSS::ComputedStyleWorkingSet::create_with_longhand_table(ComputedValuesFFI::rust_create_document_longhand_table(&input));
+ auto computed_properties = CSS::ComputedStyleWorkingSet::create_over_record(StyleRecordRef::adopt(ComputedValuesFFI::rust_create_document_style_record(m_style_engine.host(), &read, &input)));
// The font group inputs borrow the font list the working set resolves, so it outlives the call.
auto font_group_inputs = computed_properties->font_group_build_inputs(document(), document().style_scope().style_engine_tree_scope());
- return StyleRecordID { ComputedValuesFFI::rust_intern_document_style(m_style_engine.host(), &read, computed_properties->computed_longhand_table(), &font_group_inputs, &input.length_resolution_context) };
+ return StyleRecordID { ComputedValuesFFI::rust_intern_document_style(m_style_engine.host(), &read, computed_properties->record(), &font_group_inputs, &input.length_resolution_context) };
}
void StyleComputer::publish_sampled_animation_overlays(Layout::BegunRead const& read, ReadonlySpan<SampledAnimationOverlay> overlays, Span<StyleEngineFFI::FfiAnimationOverlayPublication> publications) const
@@ -2148,13 +1753,12 @@ void StyleComputer::publish_sampled_animation_overlays(Layout::BegunRead const&
.style_node = element.style_node_id().value(),
.pseudo_kind = pseudo_element_to_ffi(abstract_element.pseudo_element()),
.style_record = abstract_element.style_record_identity().value(),
- .longhand_table = style.computed_longhand_table(),
+ .record = style.record(),
.animated_overlay = style.animated_overlay(),
.animation_overlay_identity = publishes_overlay ? animated_properties->identity() : 0,
.used_color_scheme = static_cast<u8>(to_underlying(style.color_scheme(used_color_scheme_preference, document().supported_color_schemes()))),
.display_before_box_type_transformation_raw = bit_cast<u32>(style.display_before_box_type_transformation()),
.is_document_element = !abstract_element.pseudo_element().has_value() && element.is_document_element(),
- .inherited_group_count = ComputedValues::inherited_style_group_count,
.custom_property_environment = custom_property_data ? custom_property_data->identity() : 0,
.custom_property_store = custom_property_data ? custom_property_data->rust_store() : nullptr,
.callback_context = &fonts.last(),
@@ -2164,35 +1768,30 @@ void StyleComputer::publish_sampled_animation_overlays(Layout::BegunRead const&
},
});
}
+ // NB: The engine counts the samples it composes, by whether they rebuilt every group.
StyleEngineFFI::style_engine_publish_sampled_animation_overlays(m_style_engine.host(), &read, inputs.data(), inputs.size(), publications.data());
- auto& counters = document().style_invalidation_counters();
- for (auto const& published : publications) {
- VERIFY(published.view.present);
- if (published.rebuilt_every_group)
- counters.animated_style_full_builds++;
- else
- counters.animated_style_overlay_builds++;
- }
+ for (auto const& published : publications)
+ VERIFY(published.record);
}
StyleRecordID StyleComputer::intern_computed_style_inputs(Layout::BegunRead const& read, DOM::AbstractElement abstract_element, ComputedValues const& values) const
{
- return record_computed_style_inputs(read, Optional<DOM::AbstractElement> { abstract_element }, values, 0).new_style_record;
+ return install_computed_style_inputs(read, Optional<DOM::AbstractElement> { abstract_element }, values);
}
StyleRecordID StyleComputer::intern_anonymous_layout_style(Layout::BegunRead const& read, ComputedValues const& values) const
{
- return record_computed_style_inputs(read, {}, values, 0).new_style_record;
+ return install_computed_style_inputs(read, {}, values);
}
-StyleEngine::StyleRecordDelta StyleComputer::record_computed_style_inputs(Layout::BegunRead const& read, Optional<DOM::AbstractElement> abstract_element, ComputedValues const& values, StyleNodeID style_node_id) const
+StyleRecordID StyleComputer::install_computed_style_inputs(Layout::BegunRead const& read, Optional<DOM::AbstractElement> abstract_element, ComputedValues const& values) const
{
auto const& base = values.base_values();
- // An unassigned record cannot own an animation overlay, so a layout-derived copy of an
- // animated style interns its final merged payloads directly. Splitting off the base there
- // would intern (and paint) the un-animated values.
- bool const unassigned_with_animations = style_node_id == 0 && (values.has_animated_values() || values.animated_properties());
- auto const& payload_source = unassigned_with_animations ? values : base;
+ // A record no element is assigned cannot own an animation overlay, so a layout-derived copy of an
+ // animated style installs its final merged payloads directly. Splitting off the base there
+ // would install (and paint) the un-animated values.
+ bool const has_animations = values.has_animated_values() || values.animated_properties();
+ auto const& payload_source = has_animations ? values : base;
Array<void const*, to_underlying(StyleGroupIndex::Count)> payloads;
for (size_t index = 0; index < payloads.size(); ++index)
payloads[index] = payload_source.style_group_payload(static_cast<StyleGroupIndex>(index));
@@ -2201,24 +1800,16 @@ StyleEngine::StyleRecordDelta StyleComputer::record_computed_style_inputs(Layout
if (abstract_element.has_value()
&& base.reads_counter_style_environment(abstract_element->pseudo_element().has_value()))
counter_style_environment_identity = abstract_element->style_scope().counter_style_environment_identity(read);
- auto animated_properties = style_node_id != 0 ? values.animated_properties() : nullptr;
- u64 animation_overlay_identity = animated_properties ? animated_properties->identity() : 0;
- Array<void const*, to_underlying(StyleGroupIndex::Count)> animation_overlay_payloads;
- if (animated_properties) {
- for (size_t index = 0; index < animation_overlay_payloads.size(); ++index)
- animation_overlay_payloads[index] = values.style_group_payload(static_cast<StyleGroupIndex>(index));
- }
- auto pseudo_kind = pseudo_element_to_ffi(abstract_element.has_value() ? abstract_element->pseudo_element() : Optional<CSS::PseudoElement> {});
- auto publication = const_cast<StyleComputer&>(*this).style_engine().publish_computed_groups(read, style_node_id, pseudo_kind, payloads, ComputedValues::inherited_style_group_count, custom_property_environment ? custom_property_environment->identity() : 0, false, counter_style_environment_identity, animation_overlay_identity, animated_properties ? animated_properties->overlay() : nullptr, animated_properties ? animation_overlay_payloads.span() : ReadonlySpan<void const*> {}, base.computed_longhand_table(), custom_property_environment ? custom_property_environment->rust_store() : nullptr);
- return publication;
+ return const_cast<StyleComputer&>(*this).style_engine().install_host_style_record(read, payloads, payload_source.inherited_set_values(), payload_source.reset_bits(), custom_property_environment ? custom_property_environment->identity() : 0, counter_style_environment_identity, base.record().get(), custom_property_environment ? custom_property_environment->rust_store() : nullptr);
}
RefPtr<ComputedValues const> StyleComputer::engine_transient_pseudo_element_style(Layout::BegunRead const& read, DOM::Element const& element, StyleEngine::DemandedPseudoElement pseudo_element)
{
auto answer = StyleEngineFFI::style_engine_answer_pseudo_element_record_demand(m_style_engine.host(), &read, element.style_node_id().value(), StyleEngine::PseudoElementRecordDemand::ReadOnly, pseudo_element);
- auto view = computed_style_record_view(read, StyleRecordID { answer.record.style_record });
- if (!view)
+ InstalledStyle const style { answer.record.host_record };
+ if (!style)
return {};
+ auto view = computed_style_record_view(style);
// The engine holds the record only until the element's styles are next read or settled.
return ComputedValues::Builder { *view }.build();
}
@@ -2233,7 +1824,6 @@ NonnullRefPtr<ComputedStyleWorkingSet> StyleComputer::reconstruct_computed_prope
// transformation input.
if (auto const* animated_properties = computed_values.animated_properties(); animated_properties && animated_properties->has_property(PropertyID::Display))
style->set_display_before_box_type_transformation(computed_values.base_values().display());
- style->freeze_computed_longhand_table();
apply_animated_properties_to_reconstruction(*style, computed_values);
return style;
}
@@ -2246,15 +1836,15 @@ void StyleComputer::apply_animated_properties_to_reconstruction(ComputedStyleWor
style.install_animated_overlay(Badge<StyleComputer> {}, animated_properties->overlay());
}
-NonnullRefPtr<ComputedStyleWorkingSet> StyleComputer::reconstruct_computed_properties_for_animation(Layout::BegunRead const& read, StyleRecordID style_record) const
+NonnullRefPtr<ComputedStyleWorkingSet> StyleComputer::reconstruct_computed_properties_for_animation(InstalledStyle const& installed_style) const
{
- auto record = m_style_engine.style_record_view(read, style_record);
+ auto record = installed_style.view();
VERIFY(record.present);
auto style = ComputedStyleWorkingSet::create_for_animation_update(
- static_cast<ComputedValuesFFI::ComputedLonghandTable const*>(record.longhand_table),
+ record.longhand_table_record,
static_cast<ComputedValuesFFI::AnimatedOverlay const*>(record.animated_overlay));
if (record.animated_overlay && ComputedValuesFFI::rust_animated_overlay_contains(static_cast<ComputedValuesFFI::AnimatedOverlay const*>(record.animated_overlay), to_underlying(PropertyID::Display))) {
- auto const* box = static_cast<ComputedValuesFFI::BoxValues const*>(record.base_payloads[to_underlying(StyleGroupIndex::BoxValues)]);
+ auto const* box = &style_record_group<ComputedValues::BoxValues>(StyleEngineFFI::style_engine_view_base_groups(&record));
style->set_display_before_box_type_transformation(display_from_ffi_display(box->display));
}
return style;
diff --git a/Libraries/LibWeb/CSS/StyleComputer.h b/Libraries/LibWeb/CSS/StyleComputer.h
index 5769b305d9a..e91191df616 100644
--- a/Libraries/LibWeb/CSS/StyleComputer.h
+++ b/Libraries/LibWeb/CSS/StyleComputer.h
@@ -115,21 +115,33 @@ public:
// authoritative shared record rather than layout-owned complete computed values.
[[nodiscard]] StyleRecordID intern_anonymous_layout_style(Layout::BegunRead const& read, ComputedValues const&) const;
- [[nodiscard]] ComputedStyleRecordView computed_style_record_view(Layout::BegunRead const& read, StyleRecordID) const;
[[nodiscard]] ComputedStyleRecordView computed_style_record_view(InstalledStyle const&) const;
// The style an element or a pseudo-element installs as `style_record`, which a style update answered.
[[nodiscard]] InstalledStyle install_style(Layout::BegunRead const& read, StyleRecordID style_record) const;
- void pin_style_record(StyleRecordID) const;
- void unpin_style_record(StyleRecordID) const;
+ // A style installation swaps in the styles the render side noted the elements hold as it published them, so it
+ // tells the render side only of the elements whose styles the installation cleared before swapping theirs in.
+ void begin_style_installation();
+ void end_style_installation();
+ // The generation an element and its ancestors take as a style below them moves: one per installation, so that a
+ // walk up from an element stops at the first ancestor another element's walk reached, and a fresh one otherwise.
+ [[nodiscard]] u64 subtree_style_generation_for_move();
+ // Whether the render side is to be told of the custom-property environment `identity`, which it was not yet in this
+ // installation. Outside of one, it always is.
+ [[nodiscard]] bool custom_property_environment_needs_note(CustomPropertyData const&) const;
void begin_style_record_view_epoch() const;
void end_style_record_view_epoch() const;
- [[nodiscard]] u64 computed_style_record_view_pin_count() const { return m_computed_style_record_view_pin_count; }
void sweep_custom_property_environments() const;
// The environment the style engine resolved under `identity`, materialized over the data the
// element inherits, which must be the environment the engine resolved it over. Nothing when
// the identity is no engine environment or was resolved over another.
[[nodiscard]] RefPtr<CustomPropertyData const> engine_custom_property_environment(Layout::BegunRead const& read, u64 identity, RefPtr<CustomPropertyData const> const& inherited) const;
+ // The environment `environment` was built over: the one the engine resolved it over, or the node its chain lies over.
+ // What a child of an element holding `environment` inherits of it, under the registrations as they are now.
+ [[nodiscard]] RefPtr<CustomPropertyData const> inheritable_custom_property_environment(Layout::BegunRead const& read, CustomPropertyData const& environment) const;
+ // The custom properties the engine's environment `identity` declares of its own, over `inherited` rather than the
+ // environment the engine resolved them over. Nothing where `identity` is not an environment the engine resolved.
+ [[nodiscard]] RefPtr<CustomPropertyData const> engine_custom_property_declarations_over(Layout::BegunRead const& read, u64 identity, RefPtr<CustomPropertyData const> const& inherited) const;
// Refreshes a previously published style outside the drive: re-runs the animated element style
// adjustments and leaves the non-inherited-property inheritance invalidation mark itself.
@@ -149,7 +161,9 @@ public:
void apply_settled_animation_plan(Layout::BegunRead const& read, DOM::AbstractElement&) const;
// Starts the CSS animations of an element or pseudo-element and composes its animations over the record the style
// engine settled for it, once the host has installed it.
- void compose_installed_engine_record(Layout::BegunRead const& read, DOM::AbstractElement, StyleRecordID before_change_style_record) const;
+ void compose_installed_engine_record(Layout::BegunRead const& read, DOM::AbstractElement, InstalledStyle const& before_change_style) const;
+ [[nodiscard]] bool has_animations_to_compose(DOM::AbstractElement) const;
+ void stop_publishing_animated_custom_properties(DOM::AbstractElement) const;
static NonnullRefPtr<StyleValue const> compute_font_size(NonnullRefPtr<StyleValue const> const& absolutized_value, int computed_math_depth, Optional<DOM::AbstractElement> const& inheritance_parent, CSSPixels initial_font_size = InitialValues::font_size());
static NonnullRefPtr<StyleValue const> compute_font_style(NonnullRefPtr<StyleValue const> const& absolutized_value);
@@ -158,19 +172,19 @@ public:
[[nodiscard]] NonnullRefPtr<ComputedStyleWorkingSet> reconstruct_computed_properties(ComputedValues const&) const;
void apply_animated_properties_to_reconstruction(ComputedStyleWorkingSet&, ComputedValues const&) const;
- [[nodiscard]] NonnullRefPtr<ComputedStyleWorkingSet> reconstruct_computed_properties_for_animation(Layout::BegunRead const& read, StyleRecordID) const;
+ [[nodiscard]] NonnullRefPtr<ComputedStyleWorkingSet> reconstruct_computed_properties_for_animation(InstalledStyle const&) const;
void begin_transition_stabilization_epoch();
// https://drafts.csswg.org/css-transitions-2/#defining-before-change-style
- // Keeps `before_change_style_record` as the style a later pass of the stabilization epoch decides the element's
+ // Keeps `before_change_style` as the style a later pass of the stabilization epoch decides the element's
// transitions against, unless a pass already kept one.
- void record_transition_stabilization_baseline(DOM::AbstractElement, StyleRecordID before_change_style_record) const;
- // Keeps `before_change_style_record` that way where the element's style scope can run a later pass at all.
- void record_transition_baseline_for_later_passes(DOM::AbstractElement, StyleRecordID before_change_style_record) const;
- // Runs the whole transition step for an installed record, against the record the element moved away from, which
- // the caller keeps alive. Returns what publishing a started transition's values invalidates, which the caller
- // reacts to like to the rest of the style change.
- [[nodiscard]] RequiredInvalidationAfterStyleChange run_transition_step_for_installed_record(Layout::BegunRead const& read, DOM::AbstractElement, StyleRecordID before_change_style_record) const;
+ void record_transition_stabilization_baseline(DOM::AbstractElement, InstalledStyle const& before_change_style) const;
+ // Keeps `before_change_style` that way where the element's style scope can run a later pass at all.
+ void record_transition_baseline_for_later_passes(DOM::AbstractElement, InstalledStyle const& before_change_style) const;
+ // Runs the whole transition step for an installed record, against the record the element moved away from.
+ // Returns what publishing a started transition's values invalidates, which the caller reacts to like to the rest
+ // of the style change.
+ [[nodiscard]] RequiredInvalidationAfterStyleChange run_transition_step_for_installed_record(Layout::BegunRead const& read, DOM::AbstractElement, InstalledStyle const& before_change_style) const;
void commit_transition_stabilization_epoch();
void for_each_provisional_transition_effect(DOM::AbstractElement const&, Function<void(Animations::KeyframeEffect&)> const&) const;
@@ -180,18 +194,19 @@ public:
private:
virtual void visit_edges(Visitor&) override;
- [[nodiscard]] StyleEngine::StyleRecordDelta record_computed_style_inputs(Layout::BegunRead const& read, Optional<DOM::AbstractElement>, ComputedValues const&, StyleNodeID style_node_id) const;
+ [[nodiscard]] StyleRecordID install_computed_style_inputs(Layout::BegunRead const& read, Optional<DOM::AbstractElement>, ComputedValues const&) const;
private:
- // `sampled_style_record` names the record the working set was reconstructed from, where it was.
- void collect_animation_effects_into(Layout::BegunRead const& read, DOM::AbstractElement, ReadonlySpan<GC::Ref<Animations::KeyframeEffect>>, ComputedStyleWorkingSet&, StyleRecordID sampled_style_record) const;
+ // Samples over the record the element holds, which the working set was reconstructed from.
+ void collect_animation_effects_into(Layout::BegunRead const& read, DOM::AbstractElement, ReadonlySpan<GC::Ref<Animations::KeyframeEffect>>, ComputedStyleWorkingSet&) const;
struct AnimationSample;
- [[nodiscard]] NonnullOwnPtr<AnimationSample> begin_animation_sample(Layout::BegunRead const& read, DOM::AbstractElement, ReadonlySpan<GC::Ref<Animations::KeyframeEffect>>, ComputedStyleWorkingSet&, StyleRecordID sampled_style_record) const;
+ [[nodiscard]] NonnullOwnPtr<AnimationSample> begin_animation_sample(Layout::BegunRead const& read, DOM::AbstractElement, ReadonlySpan<GC::Ref<Animations::KeyframeEffect>>, ComputedStyleWorkingSet&) const;
void finish_animation_sample(AnimationSample&, ComputedValuesFFI::FfiHostAnimationSampleResult const&) const;
void finish_animation_refresh(Layout::BegunRead const& read, DOM::AbstractElement, ComputedStyleWorkingSet&) const;
- void publish_animated_custom_properties(Layout::BegunRead const&, ComputedStyleWorkingSet&, DOM::AbstractElement) const;
- void invalidate_animated_custom_property_readers(Layout::BegunRead const&, DOM::AbstractElement, OrderedHashMap<Utf16FlyString, NonnullRefPtr<StyleValue const>> const& animated_values, RefPtr<CustomPropertyData const> old_data, bool recompute_style) const;
- RefPtr<ComputedStyleWorkingSet> start_needed_transitions(Layout::BegunRead const& read, DOM::AbstractElement, StyleRecordID before_change_style_record) const;
+ void publish_animated_custom_properties(ComputedStyleWorkingSet&, DOM::AbstractElement) const;
+ [[nodiscard]] bool animated_custom_properties_may_move(DOM::AbstractElement, size_t animated_value_count) const;
+ void invalidate_animated_custom_property_readers(DOM::AbstractElement, bool recompute_style) const;
+ RefPtr<ComputedStyleWorkingSet> start_needed_transitions(Layout::BegunRead const& read, DOM::AbstractElement, InstalledStyle const& before_change_style) const;
[[nodiscard]] bool has_provisional_transition_states(DOM::AbstractElement) const;
void finalize_animated_box_type(Layout::BegunRead const& read, ComputedStyleWorkingSet&, DOM::AbstractElement) const;
@@ -209,6 +224,16 @@ public:
SheetID sheet_id;
};
[[nodiscard]] Vector<NonAuthorStyleSheet>& non_author_style_sheets() { return m_non_author_style_sheets; }
+ // What decides which user-agent and user sheets a document holds, and the namespace its HTML elements are in.
+ struct NonAuthorStyleSheetsKey {
+ bool in_quirks_mode { false };
+ bool needs_mathml_and_svg_user_agent_style_sheets { false };
+ bool is_html_document { false };
+ StyleSheetState const* user_style_sheet { nullptr };
+ bool operator==(NonAuthorStyleSheetsKey const&) const = default;
+ };
+ // The key the recorded sheets were collected under, if any were.
+ [[nodiscard]] Optional<NonAuthorStyleSheetsKey>& non_author_style_sheets_key() { return m_non_author_style_sheets_key; }
[[nodiscard]] StyleEngineRuleID style_engine_rule_id_for(Layout::BegunRead const& read, RustRule const&) const;
[[nodiscard]] SheetID style_engine_sheet_id_for(StyleSheetState const&) const;
@@ -235,7 +260,6 @@ public:
// Forgets the style node ids that left their nodes, once a rendering update took in what the lanes reported.
void forget_style_nodes_retired_beside_lanes() { m_style_nodes_retired_beside_lanes.clear(); }
void prepare_elements_for_style_computation();
- void for_each_style_node(Function<void(DOM::Element&)>) const;
// Style scopes are numbered per document, with zero naming the document's own scope. A scope is
// never reused, so a sheet detached with an identity that has been retired detaches nothing
@@ -265,8 +289,14 @@ private:
mutable Optional<MediaEnvironmentSnapshot> m_style_update_media_environment;
mutable Optional<Parser::ValueParserFFI::FfiMediaEnvironment> m_style_update_ffi_media_environment;
u64 m_viewport_environment_version { 0 };
- // The environments the style engine resolved, by the identity it minted, materialized once.
- mutable HashMap<u64, NonnullRefPtr<CustomPropertyData const>> m_engine_custom_property_environments;
+ // What each environment built here hands down, by its identity, under the registrations of the generation below.
+ struct InheritableCustomPropertyEnvironment {
+ NonnullRefPtr<CustomPropertyData const> environment;
+ RefPtr<CustomPropertyData const> inheritable;
+ bool hands_down_itself { false };
+ };
+ mutable HashMap<u64, InheritableCustomPropertyEnvironment> m_inheritable_custom_property_environments;
+ mutable u64 m_inheritable_custom_property_environments_generation { 0 };
struct ProvisionalTransitionState {
GC::Ptr<DOM::Element> element;
@@ -279,19 +309,21 @@ private:
};
// Whether the animation collection of the computation in progress resolved a keyframe-borne
// `inherit` for a non-inherited property; folded into the explicit-inheritance bookkeeping.
- mutable u32 m_keyframes_inherited_non_inherited_style_groups { 0 };
mutable Vector<ProvisionalTransitionState> m_provisional_transition_states;
mutable HashMap<u64, size_t> m_provisional_transition_state_indices;
mutable HashMap<u64, Vector<size_t>> m_provisional_transition_state_indices_by_target;
// Whether the engine keeps a before-change style the current stabilization epoch recorded.
mutable bool m_transition_baselines_recorded { false };
- ComputationContext make_computation_context_for_property(Layout::BegunRead const& read, PropertyID, ComputedStyleWorkingSet const&, Optional<DOM::AbstractElement>) const;
+ ComputationContext make_computation_context_for_property(PropertyID, ComputedStyleWorkingSet const&, Optional<DOM::AbstractElement>) const;
CSSPixelRect m_viewport_rect;
mutable StyleEngine m_style_engine;
- mutable u64 m_computed_style_record_view_pin_count { 0 };
mutable u32 m_style_record_view_epoch_depth { 0 };
+ u32 m_style_installation_depth { 0 };
+ u64 m_subtree_style_generation { 0 };
+ u64 m_installation_subtree_style_generation { 0 };
+ mutable HashMap<u64, NonnullRefPtr<CustomPropertyData const>> m_custom_property_environments_noted_during_installation;
// Indexed by each kind's dense index; see style_node_is_text(). The element-kind table also
// holds shadow roots: a root gets no style, but it has a StyleNodeID of its own.
Vector<GC::Ptr<DOM::Node>> m_element_style_nodes;
@@ -300,6 +332,7 @@ private:
// The root each scope numbers, by scope minus one.
Vector<GC::Weak<DOM::ShadowRoot>> m_shadow_roots_by_tree_scope;
Vector<NonAuthorStyleSheet> m_non_author_style_sheets;
+ Optional<NonAuthorStyleSheetsKey> m_non_author_style_sheets_key;
HashMap<RefPtr<StyleSheetState const>, SheetID> m_constructed_sheet_ids;
HashMap<SharedCompiledStyleSheetKey, RefPtr<SharedCompiledStyleSheet>> m_shared_compiled_style_sheets;
// The shared compiled sheets that no tree scope holds any longer, least recently detached first.
@@ -307,36 +340,4 @@ private:
HashMap<u64, WeakPtr<StyleSheetState const>> m_style_engine_sheet_sources;
};
-// Keeps a style record alive for as long as it is held, as a transition step that reads the record an element moved
-// away from needs. A null record pins nothing.
-class StyleRecordPin {
- AK_MAKE_NONCOPYABLE(StyleRecordPin);
- AK_MAKE_NONMOVABLE(StyleRecordPin);
-
-public:
- StyleRecordPin(StyleComputer const& style_computer, StyleRecordID style_record)
- : m_style_computer(style_computer)
- , m_style_record(style_record)
- {
- if (!!m_style_record)
- m_style_computer->pin_style_record(m_style_record);
- }
-
- ~StyleRecordPin()
- {
- if (!!m_style_record)
- m_style_computer->unpin_style_record(m_style_record);
- }
-
- StyleRecordID style_record() const { return m_style_record; }
-
-private:
- GC::Ref<StyleComputer const> m_style_computer;
- StyleRecordID m_style_record;
-};
-
-// The custom properties an element's animations sample moved from `old_data`: its descendants take what it hands down
-// now, as they take an environment that a style reaction moved.
-void move_custom_property_environment_below_animated_element(Layout::BegunRead const&, DOM::Element&, RefPtr<CustomPropertyData const> old_data);
-
}
diff --git a/Libraries/LibWeb/Rust/Cargo.toml b/Libraries/LibWeb/Rust/Cargo.toml
index f0eda5e208b..aadf58988ef 100644
--- a/Libraries/LibWeb/Rust/Cargo.toml
+++ b/Libraries/LibWeb/Rust/Cargo.toml
@@ -22,6 +22,7 @@ libcompositing_rust = { path = "../../LibCompositing/Rust" }
libgfx_rust = { path = "../../LibGfx/Rust", default-features = false }
liburl_rust = { path = "../../LibURL/Rust", default-features = false }
libweb_html_tokenizer = { path = "../HTML/Parser/Rust" }
+rayon = "1.12"
rustc-demangle = "0.1"
serde_json = { version = "1", features = ["float_roundtrip", "preserve_order"] }
smallvec = { version = "1.16.3", features = ["const_generics"] }
diff --git a/Libraries/LibWeb/Rust/src/css/property_metadata.rs b/Libraries/LibWeb/Rust/src/css/property_metadata.rs
index 5f7b4348c58..93c25a0e9f9 100644
--- a/Libraries/LibWeb/Rust/src/css/property_metadata.rs
+++ b/Libraries/LibWeb/Rust/src/css/property_metadata.rs
@@ -297,15 +297,13 @@ fn shorthand_leaf_longhands() -> &'static [(u16, Box<[u16]>)] {
})
}
-/// The shorthand whose longhands, through any shorthand nested in it, are exactly `longhands`: the one a value pending
-/// substitution in each of them was written for.
-pub(crate) fn shorthand_with_leaf_longhands(mut longhands: Vec<u16>) -> Option<u16> {
- longhands.sort_unstable();
- longhands.dedup();
- shorthand_leaf_longhands()
- .iter()
- .find(|(_, leaves)| **leaves == *longhands)
- .map(|(shorthand, _)| *shorthand)
+/// Whether `longhand` is one of the longhands of `shorthand`, through any shorthand nested in it.
+pub(crate) fn shorthand_has_leaf_longhand(shorthand: u16, longhand: u16) -> bool {
+ property_is_shorthand(shorthand)
+ && shorthand_leaf_longhands()[usize::from(shorthand - FIRST_SHORTHAND_PROPERTY_ID)]
+ .1
+ .binary_search(&longhand)
+ .is_ok()
}
/// The shorthands whose longhands, through any shorthand nested in it, include all of `longhands`, with the fewest
diff --git a/Libraries/LibWeb/Rust/src/css/style/cascade.rs b/Libraries/LibWeb/Rust/src/css/style/cascade.rs
index 7c6c6516ecc..54865c189db 100644
--- a/Libraries/LibWeb/Rust/src/css/style/cascade.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/cascade.rs
@@ -4,53 +4,21 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! Cascade priority and winner groups.
+//! Cascade priorities, and what a winning declaration is and where it comes from.
//!
-//! A declaration's priority is a comparison program over stable identities, not a number baked into
-//! the declaration. Components that change globally - layer topology, stylesheet order - are
-//! referenced indirectly, so moving a layer or a sheet updates one token instead of rewriting every
-//! declaration that lives in it.
-//!
-//! The components, outermost first, follow the cascade sorting order:
+//! The components of a priority, outermost first, follow the cascade sorting order:
//! origin and importance, encapsulation context, element-attached styles, layers, specificity,
//! scope proximity, and order of appearance. Importance reverses two of them - context and layers -
//! which is why importance is folded into the key when it is built rather than checked at every
//! comparison.
-//!
-//! Winner groups intern the declarations which win for one style node. Thousands of elements with
-//! the same cascade answer therefore share one state and retain only a compact handle. States in
-//! turn share property-range groups, so changing one winner does not copy every unaffected one.
-use super::column::BitColumn;
-use super::column::Column;
-use super::column::PagedColumn;
-use super::column::PagedColumnPage;
-use super::column::RemovablePagedColumnPage;
-use super::custom_property_cascade::CustomPropertyNames;
-use super::fast_hash::FastMap as HashMap;
-use super::fast_hash::fast_hasher;
-use super::intern_table::InternIdentity;
-use super::intern_table::InternTable;
-use super::intern_table::content_hash;
-
-use smallvec::SmallVec;
use std::hash::Hash;
-use std::hash::Hasher;
-use std::sync::OnceLock;
-use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
use crate::css::cascaded_properties::CascadeOrigin;
-use super::partial_view::Lookup;
-use super::program::CascadeLayerID;
-use super::program::RuleID;
+use super::input_types::ElementDeclarationKind;
+use super::pipeline::rule_store::RuleID;
use super::selector::Specificity;
-use super::sorted_merge::SortedMergeEntry;
-use super::sorted_merge::merge_sorted_by;
-use super::transaction::ElementDeclarationKind;
-use super::transaction::ProgramVersion;
-use super::tree::PseudoElementTarget;
-use super::tree::StyleNodeID;
/// Where an element-sourced declaration sits relative to the rules of its context.
///
@@ -146,26 +114,11 @@ impl CascadePriority {
}
}
- /// The priority below every declaration's.
- #[must_use]
- pub fn lowest() -> Self {
- Self {
- origin_importance: 0,
- context: 0,
- element_attachment: ElementAttachment::Rule,
- layer: 0,
- specificity: Specificity::default(),
- scope_proximity: 0,
- sheet_rank: 0,
- rule_rank: 0,
- }
- }
-
/// Whether a `revert` or `revert-layer` declared at this priority rolls back past a declaration
/// at `other`, so that the declaration takes no part in what the property reverts to.
#[must_use]
pub fn reverts_past(&self, operator: CascadeOperator, other: &Self) -> bool {
- // UA, user, and author, in the order `CascadeStratum` groups origins.
+ // UA, user, and author.
let origin_group = |origin_importance: u8| match origin_importance {
0 | 8 => 0,
1 | 7 => 1,
@@ -176,7 +129,7 @@ impl CascadePriority {
CascadeOperator::Revert => origin_group(other.origin_importance) >= origin_group(self.origin_importance),
// https://drafts.csswg.org/css-cascade-5/#valdef-all-revert-layer
// The cascaded value rolls back to the earlier layers of the declaration's origin and
- // context, important or not. This matches CascadeStratum::is_below().
+ // context, important or not.
CascadeOperator::RevertLayer => {
// NB: Inline styles occupy a separate cascade step, even though they share the implicit outer
// layer's rank with unlayered style rules, so a revert-layer in them only rolls back other
@@ -192,6 +145,18 @@ impl CascadePriority {
}
}
+ /// The origin of the declaration this priority was built for.
+ #[must_use]
+ pub fn cascade_origin(&self) -> CascadeOrigin {
+ match self.origin_importance {
+ 0 | 8 => CascadeOrigin::UserAgent,
+ 1 | 7 => CascadeOrigin::User,
+ 2 | 6 => CascadeOrigin::AuthorPresentationalHint,
+ 3 | 5 => CascadeOrigin::Author,
+ rank => unreachable!("origin-importance rank {rank} names no origin"),
+ }
+ }
+
/// The origin the priority was built from, as its rank among normal declarations.
fn origin(&self) -> u8 {
match self.is_important() {
@@ -219,77 +184,14 @@ impl CascadePriority {
false => self.layer,
}
}
-
- /// The origin of the declaration this priority was built for.
- #[must_use]
- pub fn cascade_origin(&self) -> CascadeOrigin {
- match self.origin_importance {
- 0 | 8 => CascadeOrigin::UserAgent,
- 1 | 7 => CascadeOrigin::User,
- 2 | 6 => CascadeOrigin::AuthorPresentationalHint,
- 3 | 5 => CascadeOrigin::Author,
- rank => unreachable!("origin-importance rank {rank} names no origin"),
- }
- }
-
- /// Where among an element's encapsulation contexts an author declaration's priority places it:
- /// the `context_depth` it was built from. `None` for the other origins.
- #[must_use]
- pub fn author_context_depth(&self) -> Option<u32> {
- if self.origin_importance == origin_importance_rank(CascadeOrigin::Author, false) {
- Some(u32::MAX - self.context)
- } else if self.origin_importance == origin_importance_rank(CascadeOrigin::Author, true) {
- Some(self.context)
- } else {
- None
- }
- }
-
- #[cfg(test)]
- pub(super) fn exact_output_placeholder() -> Self {
- Self::new(PriorityInputs {
- origin: CascadeOrigin::Author,
- important: false,
- context_depth: 0,
- element_attachment: ElementAttachment::Rule,
- layer_rank: 0,
- specificity: Specificity::default(),
- scope_proximity: 0,
- sheet_rank: 0,
- rule_rank: 0,
- })
- }
}
// -- Winners and stopping keys -----------------------------------------------------------------
-/// A longhand property identity, matching the property metadata tables.
-pub type PropertyID = u16;
-
-const WINNER_GROUP_PROPERTY_COUNT: PropertyID = 32;
-const INLINE_WINNER_GROUP_COUNT: usize =
- crate::css::property_metadata::LAST_LONGHAND_PROPERTY_ID as usize / WINNER_GROUP_PROPERTY_COUNT as usize + 1;
-
-/// Canonical identity of a specified value. Two declarations that specify the same value share it,
-/// however differently they were written and whichever rule they came from.
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
-pub struct SpecifiedValueID(pub u64);
-
-define_id! {
- /// Identity of one shared continuation below a CSS-wide cascade operator. Zero means no
- /// continuation is required.
- default pub struct CascadeContinuationID(pub);
-}
-
-impl InternIdentity for CascadeContinuationID {
- fn index(self) -> usize {
- self.0 as usize - 1
- }
-}
-
/// A CSS-wide keyword acts as a cascade operator rather than an eagerly flattened value, so its
/// dependency on parent style, origin, and layer topology stays explicit and repairable.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
+#[repr(u8)]
pub enum CascadeOperator {
/// An ordinary declared value.
#[default]
@@ -303,23 +205,22 @@ pub enum CascadeOperator {
RevertLayer,
}
-/// What has to be unchanged for an existing computed value to be reusable without resolving.
-///
-/// Declaration identity and source position are deliberately absent. They are retained for
-/// diagnostics but are not semantic, which is exactly what makes a theme swap that produces
-/// identical values free downstream. Transition generation and animation base changes *are*
-/// semantic and do participate.
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
-pub struct SpecifiedWinnerKey {
- pub value: SpecifiedValueID,
- pub operator: CascadeOperator,
- /// Where a `revert` or `revert-layer` resumes. Changing the ceiling changes the meaning of the
- /// same written value.
- pub continuation: CascadeContinuationID,
- /// Animation and transition relevance for this property.
- pub animation_relevance: u32,
- /// Whether the declaration overrides an animation at this cascade level.
- pub important: bool,
+impl CascadeOperator {
+ /// The operator of the largest number.
+ pub(crate) const LAST: Self = Self::RevertLayer;
+
+ /// The operator `bits` numbers, which is one.
+ pub(crate) fn from_bits(bits: u8) -> Self {
+ match bits {
+ 0 => Self::Declared,
+ 1 => Self::Inherit,
+ 2 => Self::Initial,
+ 3 => Self::Unset,
+ 4 => Self::Revert,
+ 5 => Self::RevertLayer,
+ _ => unreachable!("not a cascade operator"),
+ }
+ }
}
/// The winning declaration for one property of one style node.
@@ -327,2725 +228,165 @@ pub struct SpecifiedWinnerKey {
pub enum WinnerSource {
Rule(RuleID),
Element(ElementDeclarationKind),
- ExactCascade,
-}
-
-/// The winning declaration for one property of one style node.
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
-pub struct PropertyWinner {
- pub property: PropertyID,
- /// Retained separately from the ordering tuple because semantic state reuse can span an
- /// importance edit, while source publication still has to identify the winning declaration.
- pub important: bool,
- pub key: SpecifiedWinnerKey,
- pub priority: CascadePriority,
- /// Provenance, retained for diagnostics. Not part of any stopping key.
- pub source: WinnerSource,
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
-pub enum CascadeAttachment {
- StyleSheet,
- InlineStyle,
-}
-
-/// The priority stratum removed by a CSS-wide continuation.
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
-pub enum CascadeContinuationCeiling {
- Origin {
- origin_group: u8,
- },
- Layer {
- origin: u8,
- important: bool,
- context: u32,
- layer: CascadeLayerID,
- layer_rank: u64,
- attachment: CascadeAttachment,
- },
-}
-
-/// One interned continuation and the winner reached below its ceiling.
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
-pub struct CascadeContinuation {
- pub ceiling: CascadeContinuationCeiling,
- pub winner: Option<PropertyWinner>,
}
-/// The origin, importance, encapsulation context, attachment, and layer occupied by one contender.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub struct CascadeStratum {
- origin: u8,
- origin_group: u8,
- important: bool,
- context: u32,
- layer: CascadeLayerID,
- layer_rank: u64,
- attachment: CascadeAttachment,
-}
+#[cfg(test)]
+mod tests {
+ use super::*;
-impl CascadeStratum {
- #[must_use]
- pub fn new(
- origin: CascadeOrigin,
- important: bool,
- context: u32,
- layer: CascadeLayerID,
- layer_rank: u64,
- attachment: CascadeAttachment,
- ) -> Self {
- let origin_group = match origin {
- CascadeOrigin::UserAgent => 0,
- CascadeOrigin::User => 1,
- CascadeOrigin::Author | CascadeOrigin::AuthorPresentationalHint => 2,
- };
- Self {
- origin: origin as u8,
- origin_group,
+ fn inputs(origin: CascadeOrigin, important: bool) -> PriorityInputs {
+ PriorityInputs {
+ origin,
important,
- context,
- layer,
- layer_rank,
- attachment,
+ context_depth: 0,
+ element_attachment: ElementAttachment::Rule,
+ layer_rank: 100,
+ specificity: Specificity::default(),
+ scope_proximity: 0,
+ sheet_rank: 10,
+ rule_rank: 10,
}
}
- pub(crate) fn ceiling(self, operator: CascadeOperator) -> Option<CascadeContinuationCeiling> {
- match operator {
- CascadeOperator::Revert => Some(CascadeContinuationCeiling::Origin {
- origin_group: self.origin_group,
- }),
- CascadeOperator::RevertLayer => Some(CascadeContinuationCeiling::Layer {
- origin: self.origin,
- important: self.important,
- context: self.context,
- layer: self.layer,
- layer_rank: self.layer_rank,
- attachment: self.attachment,
- }),
- _ => None,
- }
- }
+ #[test]
+ fn the_origin_ladder_puts_importance_where_the_cascade_does() {
+ let normal_ua = CascadePriority::new(inputs(CascadeOrigin::UserAgent, false));
+ let normal_user = CascadePriority::new(inputs(CascadeOrigin::User, false));
+ let hint = CascadePriority::new(inputs(CascadeOrigin::AuthorPresentationalHint, false));
+ let normal_author = CascadePriority::new(inputs(CascadeOrigin::Author, false));
+ let important_author = CascadePriority::new(inputs(CascadeOrigin::Author, true));
+ let important_user = CascadePriority::new(inputs(CascadeOrigin::User, true));
+ let important_ua = CascadePriority::new(inputs(CascadeOrigin::UserAgent, true));
- pub(crate) fn is_below(self, ceiling: CascadeContinuationCeiling) -> bool {
- match ceiling {
- // https://drafts.csswg.org/css-cascade-5/#valdef-all-revert
- // The cascaded value rolls back as if no rules of the reverting declaration's origin were
- // specified, important or not, and a user declaration also rolls back past the author's.
- CascadeContinuationCeiling::Origin { origin_group } => self.origin_group < origin_group,
- CascadeContinuationCeiling::Layer {
- origin,
- important: _,
- context,
- layer: _,
- layer_rank,
- attachment,
- } => {
- if self.origin != origin || self.context != context {
- return true;
- }
- if attachment == CascadeAttachment::InlineStyle {
- // NB: Inline styles occupy a separate cascade step, even though they share
- // the implicit outer layer's rank with unlayered style rules.
- return self.attachment != CascadeAttachment::InlineStyle;
- }
+ let ladder = [
+ normal_ua,
+ normal_user,
+ hint,
+ normal_author,
+ important_author,
+ important_user,
+ important_ua,
+ ];
+ assert!(ladder.windows(2).all(|pair| pair[0] < pair[1]));
- // https://drafts.csswg.org/css-cascade-5/#revert-layer
- // The cascaded value is rolled back to the earlier layer, so that the specified
- // value is calculated as if no rules were specified in the current cascade layer.
- self.layer_rank < layer_rank
- }
- }
+ // A presentational hint loses to an author rule, however specific the hint's source.
+ assert!(hint < normal_author);
}
-}
-/// One contender supplied to the complete ordered-choice reducer.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub struct CascadeCandidate {
- pub winner: PropertyWinner,
- pub stratum: CascadeStratum,
-}
-
-/// The index of the greatest of `candidates`, which are in cascade order, that every ceiling a
-/// `revert` or `revert-layer` set leaves standing.
-pub(super) fn highest_candidate_below(
- candidates: &[CascadeCandidate],
- ceilings: &[CascadeContinuationCeiling],
-) -> Option<usize> {
- candidates
- .iter()
- .rposition(|candidate| ceilings.iter().all(|&ceiling| candidate.stratum.is_below(ceiling)))
-}
-
-/// The semantic winner rows which changed between two cascade states.
-///
-/// Priority and provenance are deliberately absent. They explain why a declaration won, but a
-/// computed value only has to run again when the complete specified-winner key changed.
-#[derive(Debug, Default, PartialEq, Eq)]
-pub struct CascadeWinnerDelta {
- properties: SmallVec<[PropertyID; 8]>,
-}
+ #[test]
+ fn importance_reverses_layer_order() {
+ let mut early = inputs(CascadeOrigin::Author, false);
+ early.layer_rank = 10;
+ let mut late = inputs(CascadeOrigin::Author, false);
+ late.layer_rank = 20;
+ assert!(
+ CascadePriority::new(early) < CascadePriority::new(late),
+ "later layers win"
+ );
-impl CascadeWinnerDelta {
- #[must_use]
- pub fn properties(&self) -> &[PropertyID] {
- &self.properties
+ early.important = true;
+ late.important = true;
+ assert!(
+ CascadePriority::new(late) < CascadePriority::new(early),
+ "and the order reverses for important declarations"
+ );
}
- #[must_use]
- pub fn is_empty(&self) -> bool {
- self.properties.is_empty()
- }
+ #[test]
+ fn importance_reverses_encapsulation_context() {
+ let mut outer = inputs(CascadeOrigin::Author, false);
+ outer.context_depth = 0;
+ let mut inner = inputs(CascadeOrigin::Author, false);
+ inner.context_depth = 2;
+ assert!(
+ CascadePriority::new(inner) < CascadePriority::new(outer),
+ "outer contexts win for normal declarations"
+ );
- /// NB: Substitution can change a specified winner without changing its declaration.
- pub(super) fn include_substituted_properties(&mut self, properties: &[PropertyID]) {
- self.properties.extend_from_slice(properties);
- self.properties.sort_unstable();
- self.properties.dedup();
+ outer.important = true;
+ inner.important = true;
+ assert!(
+ CascadePriority::new(outer) < CascadePriority::new(inner),
+ "inner contexts win for important ones"
+ );
}
-}
-
-/// One exact replacement in a retained cascade state. `None` restores the implicit winner.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub struct PropertyWinnerUpdate {
- pub property: PropertyID,
- pub winner: Option<PropertyWinner>,
-}
-
-/// The greatest cascade candidate for each semantic output key.
-///
-/// Inputs may arrive in selector-dispatch order or as a complete declaration batch. An index gives
-/// both plans constant-time top-1 reduction and lookup, while one deferred sort preserves ordered
-/// publication without retaining any losing declaration.
-#[derive(Clone)]
-pub(super) struct Top1Cascade<Key, Priority, Payload> {
- winners: Vec<Top1Winner<Key, Priority, Payload>>,
- winner_by_key: HashMap<Key, usize>,
- sorted: bool,
-}
-
-#[derive(Clone)]
-pub(super) struct Top1Winner<Key, Priority, Payload> {
- pub(super) key: Key,
- pub(super) priority: Priority,
- pub(super) payload: Payload,
-}
-
-impl<Key, Priority, Payload> Top1Cascade<Key, Priority, Payload>
-where
- Key: Copy + Hash + Ord,
- Priority: Ord,
-{
- #[must_use]
- pub(super) fn with_capacity(capacity: usize) -> Self {
- Self {
- winners: Vec::with_capacity(capacity),
- winner_by_key: HashMap::with_capacity_and_hasher(capacity, Default::default()),
- sorted: true,
- }
- }
+ #[test]
+ fn an_element_attached_style_beats_every_rule_in_its_context() {
+ let mut rule = inputs(CascadeOrigin::Author, false);
+ rule.layer_rank = u64::MAX - 1;
+ rule.specificity = Specificity {
+ ids: 100,
+ classes: 100,
+ types: 100,
+ };
+ let mut inline = inputs(CascadeOrigin::Author, false);
+ inline.element_attachment = ElementAttachment::InlineStyle;
+ inline.layer_rank = 0;
- pub(super) fn clear(&mut self) {
- self.winners.clear();
- self.winner_by_key.clear();
- self.sorted = true;
+ assert!(CascadePriority::new(rule) < CascadePriority::new(inline));
}
- /// Join one candidate into the top-1 relation. A later equal-priority row wins, matching
- /// cascade source-order tie breaking after the priority program has compared equal.
- pub(super) fn consider(&mut self, key: Key, priority: Priority, payload: Payload) {
- match self.winner_by_key.entry(key) {
- std::collections::hash_map::Entry::Occupied(entry) => {
- let winner = &mut self.winners[*entry.get()];
- if priority >= winner.priority {
- *winner = Top1Winner { key, priority, payload };
- }
- }
- std::collections::hash_map::Entry::Vacant(entry) => {
- entry.insert(self.winners.len());
- self.sorted = self.sorted && self.winners.last().is_none_or(|winner| winner.key < key);
- self.winners.push(Top1Winner { key, priority, payload });
- }
- }
- }
+ #[test]
+ fn specificity_then_proximity_then_source_order_break_ties() {
+ let base = inputs(CascadeOrigin::Author, false);
+ let mut specific = base;
+ specific.specificity = Specificity {
+ classes: 1,
+ ..Specificity::default()
+ };
+ assert!(CascadePriority::new(base) < CascadePriority::new(specific));
- #[must_use]
- pub(super) fn winner(&self, key: &Key) -> Option<&Top1Winner<Key, Priority, Payload>> {
- self.winner_by_key.get(key).map(|&index| &self.winners[index])
- }
+ let mut near = base;
+ near.scope_proximity = 1;
+ let mut far = base;
+ far.scope_proximity = 5;
+ assert!(
+ CascadePriority::new(far) < CascadePriority::new(near),
+ "nearer scopes win"
+ );
- pub(super) fn unordered_winners(&self) -> impl Iterator<Item = &Top1Winner<Key, Priority, Payload>> {
- self.winners.iter()
- }
+ let mut early = base;
+ early.rule_rank = 10;
+ let mut late = base;
+ late.rule_rank = 20;
+ assert!(CascadePriority::new(early) < CascadePriority::new(late));
- pub(super) fn winners(&mut self) -> impl Iterator<Item = &Top1Winner<Key, Priority, Payload>> {
- if !self.sorted {
- self.winners.sort_unstable_by_key(|winner| winner.key);
- for (index, winner) in self.winners.iter().enumerate() {
- *self
- .winner_by_key
- .get_mut(&winner.key)
- .expect("every top-1 winner has an index") = index;
- }
- self.sorted = true;
- }
- self.winners.iter()
+ let mut early_sheet = base;
+ early_sheet.sheet_rank = 1;
+ early_sheet.rule_rank = u64::MAX;
+ let mut late_sheet = base;
+ late_sheet.sheet_rank = 2;
+ late_sheet.rule_rank = 0;
+ assert!(
+ CascadePriority::new(early_sheet) < CascadePriority::new(late_sheet),
+ "sheet order outranks position within a sheet"
+ );
}
-}
-
-define_id! {
- /// Identity of an interned winner group.
- interned pub struct WinnerGroupID(pub);
-}
-define_id! {
- /// Identity of the custom declarations one cascade target resolves, in the order its
- /// custom-property environment lists them: each winning declaration's name, importance,
- /// operator and specified value. Zero is the empty list.
- default pub struct CustomDeclarationListID(pub);
-}
+ #[test]
+ fn importance_is_weighed_per_declaration_not_per_rule() {
+ // Two author rules, the less specific one marking its declaration important. Ordering the
+ // rules once by specificity would let the more specific normal declaration win; weighing
+ // each declaration with its own importance puts the important one on a higher rung.
+ let mut specific = inputs(CascadeOrigin::Author, false);
+ specific.specificity = Specificity {
+ ids: 1,
+ ..Specificity::default()
+ };
+ specific.rule_rank = 20;
-define_id! {
- /// Identity of provenance parallel to one interned winner group.
- interned struct WinnerProvenanceGroupID(pub);
-}
+ let mut important = inputs(CascadeOrigin::Author, true);
+ important.specificity = Specificity {
+ classes: 1,
+ ..Specificity::default()
+ };
+ important.rule_rank = 10;
-define_id! {
- /// Identity of one exact priority retained by winner provenance.
- interned struct CascadePriorityID(pub);
-}
-
-define_id! {
- /// Identity of one factorized sparse cascade state.
- interned pub struct CascadeStateID(pub);
-}
-
-/// Whether a winner-group lookup requires topology-dependent priorities to still be current.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub(super) enum WinnerPriorityCoverage {
- Retained,
- Current,
-}
-
-/// The coverage required to reuse one node's retained cascade answer.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub(super) struct WinnerGroupKey {
- pub(super) node: StyleNodeID,
- pub(super) pseudo: Option<PseudoElementTarget>,
- pub(super) program_version: ProgramVersion,
- pub(super) priority: WinnerPriorityCoverage,
-}
-
-impl WinnerGroupKey {
- #[must_use]
- pub fn retained(node: StyleNodeID, program_version: ProgramVersion) -> Self {
- Self {
- node,
- pseudo: None,
- program_version,
- priority: WinnerPriorityCoverage::Retained,
- }
- }
-
- #[must_use]
- pub fn current(node: StyleNodeID, program_version: ProgramVersion) -> Self {
- Self {
- node,
- pseudo: None,
- program_version,
- priority: WinnerPriorityCoverage::Current,
- }
- }
-
- #[must_use]
- pub fn current_pseudo(node: StyleNodeID, pseudo: PseudoElementTarget, program_version: ProgramVersion) -> Self {
- Self {
- node,
- pseudo: Some(pseudo),
- program_version,
- priority: WinnerPriorityCoverage::Current,
- }
- }
-}
-
-/// The exact per-node coverage gap preventing reuse of a retained winner group.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub(super) enum WinnerGroupGap {
- MissingNode(StyleNodeID),
- StaleProgram {
- node: StyleNodeID,
- retained: ProgramVersion,
- required: ProgramVersion,
- },
- StalePriority(StyleNodeID),
-}
-
-/// The exact aggregate coverage gap preventing a whole-column proof.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub(super) enum WinnerGroupCoverageGap {
- StaleProgram {
- retained: ProgramVersion,
- required: ProgramVersion,
- },
- InsufficientProgramRows {
- retained: usize,
- required: usize,
- },
- InsufficientPriorityRows {
- retained: usize,
- required: usize,
- },
-}
-
-/// Why an interned group token could not be restored after an answer-cache hit.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub(super) enum WinnerGroupTokenGap {
- StaleGeneration { retained: u64, current: u64 },
- NotAnElement,
-}
-
-const WINNER_RULE_PAGE_SHIFT: usize = 6;
-const WINNER_RULE_PAGE_SIZE: usize = 1 << WINNER_RULE_PAGE_SHIFT;
-const WINNER_RULE_NODE_LIMIT: usize = 32;
-
-struct WinnerRuleIndexPage {
- entries: [u32; WINNER_RULE_PAGE_SIZE],
-}
-
-impl Default for WinnerRuleIndexPage {
- fn default() -> Self {
- Self {
- entries: [u32::MAX; WINNER_RULE_PAGE_SIZE],
- }
- }
-}
-
-impl PagedColumnPage for WinnerRuleIndexPage {
- type Value = u32;
-
- const SHIFT: usize = WINNER_RULE_PAGE_SHIFT;
-
- fn get(&self, index: usize) -> Option<u32> {
- (self.entries[index] != u32::MAX).then_some(self.entries[index])
- }
-
- fn insert(&mut self, index: usize, value: u32) {
- self.entries[index] = value;
- }
-}
-
-impl RemovablePagedColumnPage for WinnerRuleIndexPage {
- fn remove(&mut self, index: usize) -> Option<u32> {
- let previous = self.get(index)?;
- self.entries[index] = u32::MAX;
- Some(previous)
- }
-}
-
-#[derive(Clone, Copy)]
-struct WinnerRuleNodeReference {
- node: StyleNodeID,
- references: u32,
-}
-
-#[derive(Clone)]
-struct WinnerRuleReferenceEntry {
- rule: RuleID,
- references: u64,
- nodes: Option<Vec<WinnerRuleNodeReference>>,
-}
-
-/// A safe dense-and-sparse set of rules whose declarations currently win somewhere.
-///
-/// The sparse index is paged instead of reading uninitialized memory. Rule identity ranges without
-/// winners allocate no page, while the dense entries keep reference-count updates cache-local.
-#[derive(Default)]
-struct WinnerRuleReferences {
- indices: PagedColumn<WinnerRuleIndexPage>,
- entries: Vec<WinnerRuleReferenceEntry>,
-}
-
-impl Clone for WinnerRuleReferences {
- fn clone(&self) -> Self {
- let mut clone = Self::default();
- clone.entries.reserve(self.entries.len());
- for entry in &self.entries {
- let index = u32::try_from(clone.entries.len()).expect("winner rule inventory exhausted");
- clone.entries.push(entry.clone());
- clone.indices.insert(entry.rule.0 as usize, index);
- }
- clone
- }
-}
-
-impl WinnerRuleReferences {
- fn retain(&mut self, rule: RuleID) {
- if let Some(index) = self.indices.get(rule.0 as usize) {
- self.entries[index as usize].references += 1;
- return;
- }
- let index = u32::try_from(self.entries.len()).expect("winner rule inventory exhausted");
- self.entries.push(WinnerRuleReferenceEntry {
- rule,
- references: 1,
- nodes: Some(Vec::new()),
- });
- let (previous, _) = self.indices.insert(rule.0 as usize, index);
- debug_assert!(previous.is_none());
- }
-
- fn release(&mut self, rule: RuleID) {
- let index = self
- .indices
- .get(rule.0 as usize)
- .expect("a released winner rule must be retained") as usize;
- self.entries[index].references -= 1;
- if self.entries[index].references != 0 {
- return;
- }
- self.indices.remove(rule.0 as usize);
- self.entries.swap_remove(index);
- if let Some(moved) = self.entries.get(index) {
- self.indices.insert(moved.rule.0 as usize, index as u32);
- }
- }
-
- fn contains(&self, rule: RuleID) -> bool {
- self.indices.get(rule.0 as usize).is_some()
- }
-
- fn retain_node(&mut self, rule: RuleID, node: StyleNodeID) {
- let index = self
- .indices
- .get(rule.0 as usize)
- .expect("a winning node must reference a retained winner rule") as usize;
- let Some(nodes) = &mut self.entries[index].nodes else {
- return;
- };
- match nodes.binary_search_by_key(&node, |reference| reference.node) {
- Ok(index) => nodes[index].references += 1,
- Err(_) if nodes.len() == WINNER_RULE_NODE_LIMIT => self.entries[index].nodes = None,
- Err(index) => nodes.insert(index, WinnerRuleNodeReference { node, references: 1 }),
- }
- }
-
- fn release_node(&mut self, rule: RuleID, node: StyleNodeID) {
- let index = self
- .indices
- .get(rule.0 as usize)
- .expect("a released winning node must reference a retained winner rule") as usize;
- let Some(nodes) = &mut self.entries[index].nodes else {
- return;
- };
- let node_index = nodes
- .binary_search_by_key(&node, |reference| reference.node)
- .expect("a released winning node must be retained");
- nodes[node_index].references -= 1;
- if nodes[node_index].references == 0 {
- nodes.remove(node_index);
- }
- }
-
- fn nodes(&self, rule: RuleID) -> Option<impl Iterator<Item = StyleNodeID> + '_> {
- let index = self.indices.get(rule.0 as usize)? as usize;
- Some(
- self.entries[index]
- .nodes
- .as_ref()?
- .iter()
- .map(|reference| reference.node),
- )
- }
-}
-
-/// One context's winner-row replacements. The catalog identities remain eager,
-/// but columns and rule postings stay unchanged until installation.
-/// NB: The owner explicitly installs or releases every pending reference.
-#[derive(Clone, Default)]
-pub(super) struct WinnerEffects {
- entries: Vec<PendingWinnerNode>,
- writes: Vec<WinnerNodeWrite>,
- by_node: Column<u32>,
-}
-
-#[derive(Clone, Copy)]
-enum WinnerReference {
- #[cfg(test)]
- Retained,
- Pending,
-}
-
-#[derive(Clone)]
-
-enum WinnerNodeWrite {
- Set {
- node: StyleNodeID,
- target: Option<PseudoElementTarget>,
- state: CascadeStateID,
- version: ProgramVersion,
- priority_current: bool,
- },
- Remove(StyleNodeID),
-}
-
-#[derive(Clone)]
-
-struct PendingWinnerNode {
- element: Option<(CascadeStateID, ProgramVersion)>,
- pseudos: Vec<PseudoWinnerRow>,
- replace_rows: bool,
-}
-
-impl WinnerEffects {
- fn entry_index(&mut self, node: StyleNodeID) -> Option<usize> {
- let node_index = node.element_index()? as usize;
- if let Some(&index) = self.by_node.get(node_index).filter(|&&index| index != 0) {
- return Some(index as usize - 1);
- }
- let index = self.entries.len();
- self.by_node.insert(
- node_index,
- u32::try_from(index + 1).expect("winner effect identity space exhausted"),
- );
- self.entries.push(PendingWinnerNode {
- element: None,
- pseudos: Vec::new(),
- replace_rows: false,
- });
- Some(index)
- }
-
- fn entry(&self, node: StyleNodeID) -> Option<&PendingWinnerNode> {
- let index = *self.by_node.get(node.element_index()? as usize)?;
- (index != 0).then(|| &self.entries[index as usize - 1])
- }
-
- fn push_write(&mut self, write: WinnerNodeWrite) {
- self.writes.push(write);
- }
-
- pub(super) fn view<'a>(&'a self, groups: &'a WinnerGroups) -> WinnerView<'a> {
- WinnerView {
- groups,
- effects: Some(self),
- }
- }
-
- pub(super) fn set(
- &mut self,
- groups: &mut WinnerGroups,
- node: StyleNodeID,
- state: CascadeStateID,
- version: ProgramVersion,
- ) -> bool {
- let Some(index) = self.entry_index(node) else {
- return false;
- };
- groups.retain_pending(state);
- self.entries[index].element = Some((state, version));
- self.push_write(WinnerNodeWrite::Set {
- node,
- target: None,
- state,
- version,
- priority_current: true,
- });
- true
- }
-
- pub(super) fn set_pseudo(
- &mut self,
- groups: &mut WinnerGroups,
- node: StyleNodeID,
- pseudo: PseudoElementTarget,
- state: CascadeStateID,
- version: ProgramVersion,
- ) -> bool {
- if node.element_index().is_none() {
- return false;
- }
- let Some(index) = self.entry_index(node) else {
- return false;
- };
- groups.retain_pending(state);
- let rows = &mut self.entries[index].pseudos;
- let new = PseudoWinnerRow {
- pseudo,
- state: (state, version),
- priority_current: true,
- stamp: groups.stamp,
- };
- if let Some(row) = rows.iter_mut().find(|row| row.pseudo == pseudo) {
- *row = new;
- } else {
- rows.push(new);
- }
- self.push_write(WinnerNodeWrite::Set {
- node,
- target: Some(pseudo),
- state,
- version,
- priority_current: true,
- });
- true
- }
-
- /// A pseudo refresh may reduce the full cascade to get its pseudo winners, but the element
- /// winner has already been compared with its computed record in this flush. Leave that row
- /// and its identity intact when installing the refreshed pseudo rows.
- pub(super) fn discard_element_row(&mut self, groups: &mut WinnerGroups, node: StyleNodeID) {
- if let Some(index) = node.element_index().map(|index| index as usize)
- && let Some(entry) = self.by_node.get(index).copied()
- && entry != 0
- {
- self.entries[entry as usize - 1].element = None;
- }
- self.writes.retain(|write| {
- if let WinnerNodeWrite::Set {
- node: owner,
- target: None,
- state,
- ..
- } = write
- && *owner == node
- {
- groups.release_pending(*state);
- return false;
- }
- true
- });
- }
-
- /// Refresh the version and stamp of an unchanged pseudo row without replacing the cascade
- /// state shared by its cohort. Only a changed winner set needs a new state identity.
- pub(super) fn preserve_equal_pseudo_states(&mut self, groups: &mut WinnerGroups, node: StyleNodeID) {
- for write in &mut self.writes {
- let WinnerNodeWrite::Set {
- node: owner,
- target: Some(pseudo),
- state,
- ..
- } = write
- else {
- continue;
- };
- if *owner != node {
- continue;
- }
- let Some((_, _, retained, _)) = groups.pseudo_states(node).find(|row| row.0 == *pseudo) else {
- continue;
- };
- if retained == *state || !groups.states_are_semantically_equal(retained, *state) {
- continue;
- }
- groups.retain_pending(retained);
- groups.release_pending(*state);
- *state = retained;
- if let Some(index) = node.element_index().map(|index| index as usize)
- && let Some(entry) = self.by_node.get(index).copied()
- && entry != 0
- && let Some(row) = self.entries[entry as usize - 1]
- .pseudos
- .iter_mut()
- .find(|row| row.pseudo == *pseudo)
- {
- row.state.0 = retained;
- }
- }
- }
-
- pub(super) fn mark_pseudo_inventory_incomplete(&mut self, node: StyleNodeID, pseudo: PseudoElementTarget) {
- let index = self.by_node[node.element_index().expect("element winner") as usize] as usize - 1;
- if let Some(row) = self.entries[index].pseudos.iter_mut().find(|row| row.pseudo == pseudo) {
- row.priority_current = false;
- }
- // NB: Inventory coverage is finalized immediately after producing this row.
- if let Some(WinnerNodeWrite::Set { priority_current, .. }) = self.writes.last_mut() {
- *priority_current = false;
- }
- }
-
- pub(super) fn set_from_token(
- &mut self,
- groups: &mut WinnerGroups,
- node: StyleNodeID,
- generation: u64,
- state: CascadeStateID,
- version: ProgramVersion,
- ) -> Result<(), WinnerGroupTokenGap> {
- if generation != groups.generation {
- return Err(WinnerGroupTokenGap::StaleGeneration {
- retained: generation,
- current: groups.generation,
- });
- }
- self.set(groups, node, state, version)
- .then_some(())
- .ok_or(WinnerGroupTokenGap::NotAnElement)
- }
-
- pub(super) fn copy_node_rows(
- &mut self,
- groups: &mut WinnerGroups,
- source: StyleNodeID,
- target: StyleNodeID,
- version: ProgramVersion,
- ) -> Option<usize> {
- let (_, state) = self
- .view(groups)
- .token_for(WinnerGroupKey::current(source, version))
- .sparse()
- .ok()?;
- let pseudos: SmallVec<[_; 2]> = self.view(groups).pseudo_states(source).collect();
- let index = self.entry_index(target)?;
-
- let entry = &mut self.entries[index];
- entry.element = None;
- entry.pseudos.clear();
- entry.replace_rows = true;
- self.push_write(WinnerNodeWrite::Remove(target));
- let _ = self.set(groups, target, state, version);
- for &(pseudo, version, state, current) in &pseudos {
- let _ = self.set_pseudo(groups, target, pseudo, state, version);
- if !current {
- self.mark_pseudo_inventory_incomplete(target, pseudo);
- }
- }
-
- Some(1 + pseudos.len())
- }
-
- pub(super) fn release_pending_all(self, groups: &mut crate::fork::ForkShared<WinnerGroups>) {
- for write in self.writes {
- if let WinnerNodeWrite::Set { state, .. } = write {
- groups.release_pending(state);
- }
- }
- }
-
- pub(super) fn install(self, groups: &mut WinnerGroups) {
- if self.writes.is_empty() {
- return;
- }
- for write in self.writes {
- match write {
- WinnerNodeWrite::Remove(node) => groups.remove(node),
- WinnerNodeWrite::Set {
- node,
- target,
- state,
- version,
- priority_current,
- } => {
- let installed = match target {
- Some(pseudo) => {
- groups.set_pseudo_with_reference(node, pseudo, state, version, WinnerReference::Pending)
- }
- None => groups.set_with_reference(node, state, version, WinnerReference::Pending),
- };
- if installed
- && !priority_current
- && let Some(pseudo) = target
- {
- groups.mark_pseudo_inventory_incomplete(node, pseudo);
- }
- }
- }
- }
- }
-}
-
-#[derive(Clone, Copy)]
-pub(super) struct WinnerView<'a> {
- groups: &'a WinnerGroups,
- effects: Option<&'a WinnerEffects>,
-}
-
-impl<'a> WinnerView<'a> {
- pub(super) fn node_rows_are_semantically_equal(
- &self,
- other: &WinnerGroups,
- node: StyleNodeID,
- program_version: ProgramVersion,
- ) -> bool {
- let key = WinnerGroupKey::current(node, program_version);
- let current_rows_are_equal = match (self.token_for(key), other.token_for(key)) {
- (Lookup::Known((_, left)), Lookup::Known((_, right))) => other.states_are_semantically_equal(left, right),
- (Lookup::Missing(_), Lookup::Missing(_)) => true,
- (Lookup::Known(_), Lookup::Missing(_)) | (Lookup::Missing(_), Lookup::Known(_)) => false,
- (Lookup::KnownAbsent, _) | (_, Lookup::KnownAbsent) => unreachable!("winner groups are sparse"),
- };
- if !current_rows_are_equal {
- return false;
- }
-
- let mut left: Vec<_> = self.pseudo_states(node).collect();
- let mut right: Vec<_> = other.pseudo_states(node).collect();
- // NB: Exact verification can materialize pseudo rows missing from the sparse retained
- // cache. Compare the retained rows; additional recomputed rows do not imply a change.
- left.sort_unstable_by_key(|row| row.0);
- right.sort_unstable_by_key(|row| row.0);
- left.iter().all(|&(left_pseudo, _, left_state, left_current)| {
- right
- .binary_search_by_key(&left_pseudo, |row| row.0)
- .ok()
- .is_some_and(|index| {
- let (_, _, right_state, right_current) = right[index];
- left_current == right_current && other.states_are_semantically_equal(left_state, right_state)
- })
- })
- }
-
- pub(super) fn retained(groups: &'a WinnerGroups) -> Self {
- Self { groups, effects: None }
- }
-
- pub(super) fn lookup(&self, key: WinnerGroupKey) -> Lookup<&'a (CascadeStateID, ProgramVersion), WinnerGroupGap> {
- let entry = self.effects.and_then(|effects| effects.entry(key.node));
- let pending = entry.and_then(|entry| match key.pseudo {
- Some(pseudo) => entry
- .pseudos
- .iter()
- .find(|row| row.pseudo == pseudo)
- .map(|row| (&row.state, row.priority_current)),
- None => entry.element.as_ref().map(|row| (row, true)),
- });
- let Some((row, current)) = pending else {
- if entry.is_some_and(|entry| entry.replace_rows) {
- return Lookup::Missing(WinnerGroupGap::MissingNode(key.node));
- }
- return self.groups.lookup(key);
- };
- if row.1 != key.program_version {
- return Lookup::Missing(WinnerGroupGap::StaleProgram {
- node: key.node,
- retained: row.1,
- required: key.program_version,
- });
- }
- if key.priority == WinnerPriorityCoverage::Current && !current {
- return Lookup::Missing(WinnerGroupGap::StalePriority(key.node));
- }
- Lookup::Known(row)
- }
-
- pub(super) fn token_for(&self, key: WinnerGroupKey) -> Lookup<(u64, CascadeStateID), WinnerGroupGap> {
- match self.lookup(key).sparse() {
- Ok(&(state, _)) => Lookup::Known((self.groups.generation, state)),
- Err(gap) => Lookup::Missing(gap),
- }
- }
-
- pub(super) fn pseudo_states(
- &self,
- node: StyleNodeID,
- ) -> impl Iterator<Item = (PseudoElementTarget, ProgramVersion, CascadeStateID, bool)> + 'a {
- let entry = self.effects.and_then(|effects| effects.entry(node));
- let groups = self.groups;
- groups
- .pseudo_states(node)
- .filter_map(move |old| {
- if entry.is_some_and(|entry| entry.replace_rows) {
- return None;
- }
- Some(
- entry
- .and_then(|entry| entry.pseudos.iter().find(|row| row.pseudo == old.0))
- .map_or(old, |row| (row.pseudo, row.state.1, row.state.0, row.priority_current)),
- )
- })
- .chain(
- entry
- .into_iter()
- .flat_map(|entry| &entry.pseudos)
- .filter(move |row| {
- entry.is_some_and(|entry| entry.replace_rows)
- || !groups.pseudo_states(node).any(|old| old.0 == row.pseudo)
- })
- .map(|row| (row.pseudo, row.state.1, row.state.0, row.priority_current)),
- )
- }
-
- pub(super) fn row_stamp(&self, node: StyleNodeID) -> Option<u64> {
- if let Some(entry) = self.effects.and_then(|effects| effects.entry(node)) {
- if entry.element.is_some() {
- return Some(self.groups.stamp);
- }
- if entry.replace_rows {
- return None;
- }
- }
- self.groups.row_stamp(node)
- }
-
- pub(super) fn pseudo_row_stamp(&self, node: StyleNodeID, pseudo: PseudoElementTarget) -> Option<u64> {
- if let Some(entry) = self.effects.and_then(|effects| effects.entry(node)) {
- if let Some(row) = entry.pseudos.iter().find(|row| row.pseudo == pseudo) {
- return Some(row.stamp);
- }
- if entry.replace_rows {
- return None;
- }
- }
- self.groups.pseudo_row_stamp(node, pseudo)
- }
-
- #[cfg(test)]
- pub(super) fn winner(&self, key: WinnerGroupKey, property: PropertyID) -> Lookup<PropertyWinner, WinnerGroupGap> {
- let state = match self.lookup(key).sparse() {
- Ok(&(state, _)) => state,
- Err(gap) => return Lookup::Missing(gap),
- };
- match self.groups.winner_in_state(state, property) {
- Some(winner) => Lookup::Known(winner),
- None => Lookup::KnownAbsent,
- }
- }
-
- pub(super) fn pseudo_state(
- &self,
- node: StyleNodeID,
- pseudo: PseudoElementTarget,
- ) -> Option<(ProgramVersion, CascadeStateID, bool)> {
- if let Some(entry) = self.effects.and_then(|effects| effects.entry(node)) {
- if let Some(row) = entry.pseudos.iter().find(|row| row.pseudo == pseudo) {
- return Some((row.state.1, row.state.0, row.priority_current));
- }
- if entry.replace_rows {
- return None;
- }
- }
- self.groups
- .pseudo_rows_by_node
- .get(node.element_index()? as usize)
- .and_then(|rows| rows.iter().find(|row| row.pseudo == pseudo))
- .map(|row| (row.state.1, row.state.0, row.priority_current))
- }
-}
-
-impl std::ops::Deref for WinnerView<'_> {
- type Target = WinnerGroups;
- fn deref(&self) -> &WinnerGroups {
- self.groups
- }
-}
-
-/// A state's winners substitute `attr()`.
-pub(super) const STATE_READS_ATTRIBUTES: u8 = 1 << 0;
-/// A state's winners are written with a tree-counting function.
-pub(super) const STATE_READS_SIBLING_POSITION: u8 = 1 << 1;
-/// A state's winners substitute `inherit()`, which reads the parent's custom-property environment.
-pub(super) const STATE_READS_INHERIT_FUNCTION: u8 = 1 << 2;
-/// A state's winners substitute `if()`, whose conditions read the document's media features and
-/// the element's lengths.
-pub(super) const STATE_READS_IF_FUNCTION: u8 = 1 << 3;
-/// A state's winners call a custom function, whose definition and the conditions inside it the
-/// cascade does not decide.
-pub(super) const STATE_READS_CUSTOM_FUNCTION: u8 = 1 << 4;
-/// A state's winners are written with a random function whose random base value is drawn for the
-/// element.
-pub(super) const STATE_READS_ELEMENT_RANDOM_BASE: u8 = 1 << 5;
-/// A state's winners are written with a container-relative length, which reads the sizes of the
-/// element's query containers.
-pub(super) const STATE_READS_CONTAINER_UNITS: u8 = 1 << 6;
-/// What a state's winners read has been decided.
-const STATE_READS_DECIDED: u8 = 1 << 7;
-/// A state's summary has been decided.
-const STATE_SUMMARY_DECIDED: u64 = 1 << 63;
-/// A state's summary holds a winner written with a substitution.
-const STATE_SUMMARY_HAS_SUBSTITUTIONS: u64 = 1 << 32;
-
-/// What the engine asks of a state's winners' written values for each element it computes a record for.
-/// A complete summary depends on the winners alone.
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
-pub(super) struct StateSummary {
- /// The style groups of each non-inherited property the state declares `inherit` for, and every group for a value
- /// the engine cannot see the spelling of.
- pub(super) explicitly_inherited_groups: u32,
- /// Whether a longhand winner is written with a substitution.
- pub(super) has_substitutions: bool,
- /// Whether any winner's written value could not be inspected. Such summaries are not cached.
- pub(super) has_unknown_values: bool,
-}
-
-/// Interned per-node winning declarations.
-///
-/// Sparse and shared: never one heap object per property per element. A node retains one state
-/// identity, and states share property-range winner groups. A node without a row reconstructs its
-/// state from its cascade input or from the exact cold cascade.
-#[derive(Clone, Default)]
-pub struct WinnerGroups {
- states: InternTable<CascadeStateID, Box<[WinnerGroupRef]>>,
- /// What a state holds beside its longhand winners: the target's custom declarations. Two
- /// states with equal winners but different custom declarations are different states, so a
- /// state that is unchanged is unchanged in the environment it declares as well.
- state_custom_declarations: Vec<CustomDeclarationListID>,
- custom_declaration_list_ids: HashMap<Box<[super::program::CustomDeclaration]>, CustomDeclarationListID>,
- state_reference_counts: Vec<u32>,
- state_pending_reference_counts: Vec<u32>,
- state_winning_rules: Vec<Box<[RuleID]>>,
- /// What each state's winners read beyond the cascade, as `STATE_READS_*` bits, decided the
- /// first time it is asked and `STATE_READS_DECIDED` from then on. A state's winners never
- /// change, and neither does what they read.
- state_reads: Vec<crate::fork::ForkCopied<AtomicU8>>,
- /// Each state's [`StateSummary`], packed, decided the first time it is asked where every winner's written value was
- /// found, and `STATE_SUMMARY_DECIDED` from then on.
- state_summaries: Vec<crate::fork::ForkCopied<AtomicU64>>,
- /// The custom properties each state's winners read through `var()`. `None` when they cannot be listed.
- state_custom_property_reads: Vec<OnceLock<Option<CustomPropertyNames>>>,
- groups: InternTable<WinnerGroupID, Box<[SemanticPropertyWinner]>>,
- provenance_groups: InternTable<WinnerProvenanceGroupID, Box<[WinnerProvenance]>>,
- priorities: InternTable<CascadePriorityID, CascadePriority>,
- continuations: InternTable<CascadeContinuationID, CascadeContinuation>,
- winner_entry_count: usize,
- winner_rule_references: WinnerRuleReferences,
- column: Column<Option<(CascadeStateID, ProgramVersion)>>,
- /// The flush that published each node's row: a row published in the current flush holds the
- /// cascade of the node's current answer.
- stamps: Column<u64>,
- stamp: u64,
- pseudo_rows_by_node: crate::fork::ForkShared<Column<Vec<PseudoWinnerRow>>>,
- priority_current: BitColumn,
- row_count: usize,
- priority_current_row_count: usize,
- newest_program_version: ProgramVersion,
- newest_version_row_count: usize,
- generation: u64,
- #[cfg(test)]
- group_hash_computations: usize,
-}
-
-#[derive(Clone)]
-struct PseudoWinnerRow {
- pseudo: PseudoElementTarget,
- state: (CascadeStateID, ProgramVersion),
- priority_current: bool,
- /// The flush that published the row's state.
- stamp: u64,
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
-struct SemanticPropertyWinner {
- property: PropertyID,
- key: SpecifiedWinnerKey,
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
-struct WinnerProvenance {
- important: bool,
- source: WinnerSource,
- priority: CascadePriorityID,
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
-struct WinnerGroupRef {
- winners: WinnerGroupID,
- provenance: WinnerProvenanceGroupID,
-}
-
-impl WinnerGroups {
- #[must_use]
- pub fn new() -> Self {
- Self::default()
- }
-
- pub(super) fn verification_copy(&self) -> Self {
- let pseudo_rows_by_node = self.pseudo_rows_by_node.clone();
- Self {
- states: self.states.clone(),
- state_custom_declarations: self.state_custom_declarations.clone(),
- custom_declaration_list_ids: self.custom_declaration_list_ids.clone(),
- state_reference_counts: self.state_reference_counts.clone(),
- state_pending_reference_counts: self.state_pending_reference_counts.clone(),
- state_winning_rules: self.state_winning_rules.clone(),
- state_reads: self
- .state_reads
- .iter()
- .map(|reads| crate::fork::ForkCopied::new(AtomicU8::new(reads.load(Ordering::Relaxed))))
- .collect(),
- state_summaries: self
- .state_summaries
- .iter()
- .map(|summary| crate::fork::ForkCopied::new(AtomicU64::new(summary.load(Ordering::Relaxed))))
- .collect(),
- state_custom_property_reads: self.state_custom_property_reads.clone(),
- groups: self.groups.clone(),
- provenance_groups: self.provenance_groups.clone(),
- priorities: self.priorities.clone(),
- continuations: self.continuations.clone(),
- winner_entry_count: self.winner_entry_count,
- winner_rule_references: self.winner_rule_references.clone(),
- column: self.column.clone(),
- stamps: self.stamps.clone(),
- stamp: self.stamp,
- pseudo_rows_by_node,
- priority_current: self.priority_current.clone(),
- row_count: self.row_count,
- priority_current_row_count: self.priority_current_row_count,
- newest_program_version: self.newest_program_version,
- newest_version_row_count: self.newest_version_row_count,
- generation: self.generation,
-
- #[cfg(test)]
- group_hash_computations: self.group_hash_computations,
- }
- }
-
- /// Resolve one property's ordered contenders and intern only the continuation payloads needed
- /// by `revert` and `revert-layer` operators.
- pub fn resolve_candidates(&mut self, candidates: &mut [CascadeCandidate]) -> Option<PropertyWinner> {
- // CascadePriority is the total declaration order, so equal keys are interchangeable here.
- let candidate = candidates.iter().max_by_key(|candidate| candidate.winner.priority)?;
- if candidate.stratum.ceiling(candidate.winner.key.operator).is_none() {
- return Some(candidate.winner);
- }
- candidates.sort_unstable_by_key(|candidate| candidate.winner.priority);
- self.resolve_candidates_below(candidates, &mut Vec::new())
- }
-
- fn resolve_candidates_below(
- &mut self,
- candidates: &[CascadeCandidate],
- ceilings: &mut Vec<CascadeContinuationCeiling>,
- ) -> Option<PropertyWinner> {
- let index = highest_candidate_below(candidates, ceilings)?;
- let candidate = candidates[index];
- let mut winner = candidate.winner;
- let Some(ceiling) = candidate.stratum.ceiling(candidate.winner.key.operator) else {
- return Some(winner);
- };
- ceilings.push(ceiling);
- // Higher candidates already failed a ceiling, and the new ceiling excludes this one.
- let continuation_winner = self.resolve_candidates_below(&candidates[..index], ceilings);
- ceilings.pop();
- let continuation = self.intern_continuation(CascadeContinuation {
- ceiling,
- winner: continuation_winner,
- });
- winner.key.continuation = continuation;
- Some(winner)
- }
-
- fn intern_continuation(&mut self, continuation: CascadeContinuation) -> CascadeContinuationID {
- let hash = content_hash(continuation);
- if let Some(id) = self
- .continuations
- .find(hash, |_id, candidate| *candidate == continuation)
- {
- return id;
- }
- let id = CascadeContinuationID(
- u32::try_from(self.continuations.len() + 1).expect("cascade continuation space exhausted"),
- );
- self.continuations.insert(hash, id, continuation);
- id
- }
-
- #[must_use]
- pub fn continuation(&self, id: CascadeContinuationID) -> Option<CascadeContinuation> {
- (id != CascadeContinuationID::default()).then(|| self.continuations[id])
- }
-
- /// Follow CSS-wide continuations to the declaration consumed by the legacy exact cascade.
- #[must_use]
- pub fn resolved_winner(&self, mut winner: PropertyWinner) -> Option<PropertyWinner> {
- loop {
- let Some(continuation) = self.continuation(winner.key.continuation) else {
- return Some(winner);
- };
- winner = continuation.winner?;
- }
- }
-
- #[must_use]
- #[cfg(test)]
- pub fn continuation_count(&self) -> usize {
- self.continuations.len()
- }
-
- /// Intern an already sorted state, reusing unchanged groups directly from its previous state.
- pub fn intern_sorted(&mut self, winners: &[PropertyWinner], previous: Option<CascadeStateID>) -> CascadeStateID {
- self.intern_sorted_with_custom_declarations(winners, &[], previous)
- }
-
- /// Intern the custom declarations a target resolves beside its winners.
- pub(super) fn intern_custom_declaration_list(
- &mut self,
- declarations: &[super::program::CustomDeclaration],
- ) -> CustomDeclarationListID {
- if declarations.is_empty() {
- return CustomDeclarationListID::default();
- }
- if let Some(&id) = self.custom_declaration_list_ids.get(declarations) {
- return id;
- }
- // Every list is interned once, so the identities are dense.
- let id = CustomDeclarationListID(
- u32::try_from(self.custom_declaration_list_ids.len() + 1).expect("custom declaration list space exhausted"),
- );
- let list: Box<[_]> = declarations.into();
-
- self.custom_declaration_list_ids.insert(list, id);
- id
- }
-
- /// Intern an already sorted state together with the custom declarations its target
- /// resolves, reusing unchanged groups directly from its previous state.
- pub(super) fn intern_sorted_with_custom_declarations(
- &mut self,
- winners: &[PropertyWinner],
- custom_declarations: &[super::program::CustomDeclaration],
- previous: Option<CascadeStateID>,
- ) -> CascadeStateID {
- let custom_declarations = self.intern_custom_declaration_list(custom_declarations);
- debug_assert!(winners.windows(2).all(|pair| pair[0].property < pair[1].property));
- let mut groups = SmallVec::new();
- let mut previous_group_index = 0;
- for winners in winners.chunk_by(|left, right| {
- left.property / WINNER_GROUP_PROPERTY_COUNT == right.property / WINNER_GROUP_PROPERTY_COUNT
- }) {
- let bucket = winners[0].property / WINNER_GROUP_PROPERTY_COUNT;
- let previous_group = previous.and_then(|previous| {
- let previous_groups = &self.states[previous];
- while previous_group_index < previous_groups.len()
- && self.group_bucket(previous_groups[previous_group_index]) < bucket
- {
- previous_group_index += 1;
- }
- previous_groups
- .get(previous_group_index)
- .copied()
- .filter(|&group| self.group_bucket(group) == bucket)
- });
- let group = previous_group
- .filter(|&group| self.group_matches(group, winners))
- .unwrap_or_else(|| self.intern_group(winners));
- groups.push(group);
- }
- if let Some(previous) = previous
- && self.states[previous].as_ref() == groups.as_slice()
- && self.state_custom_declarations[previous.0 as usize] == custom_declarations
- {
- return previous;
- }
- self.intern_group_ids(groups, custom_declarations)
- }
-
- fn intern_group_ids(
- &mut self,
- groups: SmallVec<[WinnerGroupRef; INLINE_WINNER_GROUP_COUNT]>,
- custom_declarations: CustomDeclarationListID,
- ) -> CascadeStateID {
- let hash = content_hash((&groups, custom_declarations));
- let state_custom_declarations = &self.state_custom_declarations;
- if let Some(id) = self.states.find(hash, |id, candidate| {
- candidate.as_ref() == groups.as_slice() && state_custom_declarations[id.0 as usize] == custom_declarations
- }) {
- return id;
- }
- let id = CascadeStateID(u32::try_from(self.states.len()).expect("cascade state space exhausted"));
- let mut winning_rules = Vec::new();
- for &group in &groups {
- for mut winner in self.group_winners(group) {
- loop {
- if let WinnerSource::Rule(rule) = winner.source {
- winning_rules.push(rule);
- }
- let Some(continuation) = self.continuation(winner.key.continuation) else {
- break;
- };
- let Some(next) = continuation.winner else {
- break;
- };
- winner = next;
- }
- }
- }
- winning_rules.sort_unstable();
- winning_rules.dedup();
- let groups = groups.into_boxed_slice();
- let winning_rules = winning_rules.into_boxed_slice();
-
- self.states.insert(hash, id, groups);
- self.state_custom_declarations.push(custom_declarations);
- self.state_reference_counts.push(0);
- self.state_pending_reference_counts.push(0);
- self.state_winning_rules.push(winning_rules);
- self.state_reads.push(crate::fork::ForkCopied::new(AtomicU8::new(0)));
- self.state_summaries
- .push(crate::fork::ForkCopied::new(AtomicU64::new(0)));
- self.state_custom_property_reads.push(OnceLock::new());
- id
- }
-
- /// Apply exact property replacements without rebuilding unaffected winner groups.
- ///
- /// Updates are ordered and unique by property. The caller is responsible for performing any
- /// contender repair needed to produce the replacement winner.
- pub fn apply_property_updates(
- &mut self,
- previous: CascadeStateID,
- updates: &[PropertyWinnerUpdate],
- ) -> (CascadeStateID, CascadeWinnerDelta) {
- debug_assert!(updates.windows(2).all(|pair| pair[0].property < pair[1].property));
- debug_assert!(
- updates
- .iter()
- .all(|update| update.winner.is_none_or(|winner| winner.property == update.property))
- );
- // A state derived by property updates is for a target with no custom declarations: one
- // with them never takes this path, so a state that held some no longer does.
- if updates.is_empty() {
- let state = if self.state_custom_declarations[previous.0 as usize] == CustomDeclarationListID::default() {
- previous
- } else {
- let groups = SmallVec::from_slice(&self.states[previous]);
- self.intern_group_ids(groups, CustomDeclarationListID::default())
- };
- return (state, CascadeWinnerDelta::default());
- }
-
- let mut groups = SmallVec::from_slice(&self.states[previous]);
- let mut changed_properties = SmallVec::new();
- let mut old_winners: SmallVec<[PropertyWinner; WINNER_GROUP_PROPERTY_COUNT as usize]> = SmallVec::new();
- let mut winners: SmallVec<[PropertyWinner; WINNER_GROUP_PROPERTY_COUNT as usize]> = SmallVec::new();
- let mut update_start = 0;
- while update_start < updates.len() {
- let bucket = updates[update_start].property / WINNER_GROUP_PROPERTY_COUNT;
- let update_end = update_start
- + updates[update_start..]
- .partition_point(|update| update.property / WINNER_GROUP_PROPERTY_COUNT == bucket);
- let group_index = groups.partition_point(|&group| self.group_bucket(group) < bucket);
- let old_group = groups
- .get(group_index)
- .copied()
- .filter(|&group| self.group_bucket(group) == bucket);
- old_winners.clear();
- if let Some(group) = old_group {
- old_winners.extend(self.group_winners(group));
- }
- let bucket_updates = &updates[update_start..update_end];
- winners.clear();
- winners.reserve((old_winners.len() + bucket_updates.len()).min(WINNER_GROUP_PROPERTY_COUNT as usize));
- for entry in merge_sorted_by(&old_winners, bucket_updates, |old, update| {
- old.property.cmp(&update.property)
- }) {
- match entry {
- SortedMergeEntry::Both(old, update) => match update.winner {
- Some(winner) => {
- if old.key != winner.key {
- changed_properties.push(update.property);
- }
- winners.push(winner);
- }
- None => changed_properties.push(update.property),
- },
- SortedMergeEntry::Left(old) => {
- winners.push(*old);
- }
- SortedMergeEntry::Right(update) => {
- if let Some(winner) = update.winner {
- winners.push(winner);
- changed_properties.push(update.property);
- }
- }
- }
- }
-
- match (old_group, winners.is_empty()) {
- (Some(_), true) => {
- groups.remove(group_index);
- }
- (Some(old_group), false) => {
- let new_group = if old_winners == winners {
- old_group
- } else {
- self.intern_group(&winners)
- };
- groups[group_index] = new_group;
- }
- (None, false) => {
- let new_group = self.intern_group(&winners);
- groups.insert(group_index, new_group);
- }
- (None, true) => {}
- }
- update_start = update_end;
- }
-
- let state = if self.states[previous].as_ref() == groups.as_slice()
- && self.state_custom_declarations[previous.0 as usize] == CustomDeclarationListID::default()
- {
- previous
- } else {
- self.intern_group_ids(groups, CustomDeclarationListID::default())
- };
- (
- state,
- CascadeWinnerDelta {
- properties: changed_properties,
- },
- )
- }
-
- fn intern_group(&mut self, winners: &[PropertyWinner]) -> WinnerGroupRef {
- let semantic = winners.iter().map(|winner| SemanticPropertyWinner {
- property: winner.property,
- key: winner.key,
- });
- // Neighboring winners mostly come from the same declaration block and share its priority,
- // so each run of equal priorities is interned once.
- let mut last_priority = None;
- let provenance: SmallVec<[_; WINNER_GROUP_PROPERTY_COUNT as usize]> = winners
- .iter()
- .map(|winner| {
- let priority = match last_priority {
- Some((priority, id)) if priority == winner.priority => id,
- _ => {
- let id = self.intern_priority(winner.priority);
- last_priority = Some((winner.priority, id));
- id
- }
- };
- WinnerProvenance {
- important: winner.important,
- source: winner.source,
- priority,
- }
- })
- .collect();
- let mut hasher = fast_hasher();
- winners.len().hash(&mut hasher);
- for winner in semantic.clone() {
- winner.hash(&mut hasher);
- }
- let hash = hasher.finish();
- #[cfg(test)]
- {
- self.group_hash_computations += 1;
- }
- if let Some(id) = self
- .groups
- .find(hash, |_id, group| group.iter().copied().eq(semantic.clone()))
- {
- return WinnerGroupRef {
- winners: id,
- provenance: self.intern_provenance_group(&provenance),
- };
- }
- let id = WinnerGroupID(u32::try_from(self.groups.len()).expect("winner group space exhausted"));
- let semantic: Box<[_]> = semantic.collect();
- self.winner_entry_count += semantic.len();
-
- self.groups.insert(hash, id, semantic);
- WinnerGroupRef {
- winners: id,
- provenance: self.intern_provenance_group(&provenance),
- }
- }
-
- fn intern_provenance_group(&mut self, provenance: &[WinnerProvenance]) -> WinnerProvenanceGroupID {
- let hash = content_hash(provenance);
- if let Some(id) = self
- .provenance_groups
- .find(hash, |_id, candidate| candidate.as_ref() == provenance)
- {
- return id;
- }
- let id = WinnerProvenanceGroupID(
- u32::try_from(self.provenance_groups.len()).expect("winner provenance group space exhausted"),
- );
-
- self.provenance_groups.insert(hash, id, provenance.into());
- id
- }
-
- fn intern_priority(&mut self, priority: CascadePriority) -> CascadePriorityID {
- let hash = content_hash(priority);
- if let Some(id) = self.priorities.find(hash, |_id, candidate| *candidate == priority) {
- return id;
- }
- let id = CascadePriorityID(u32::try_from(self.priorities.len()).expect("cascade priority space exhausted"));
- self.priorities.insert(hash, id, priority);
- id
- }
-
- fn group_matches(&self, group: WinnerGroupRef, winners: &[PropertyWinner]) -> bool {
- self.group_winners(group).eq(winners.iter().copied())
- }
-
- fn group_winners(&self, group: WinnerGroupRef) -> impl Iterator<Item = PropertyWinner> + '_ {
- self.groups[group.winners]
- .iter()
- .zip(&self.provenance_groups[group.provenance])
- .map(|(winner, provenance)| PropertyWinner {
- property: winner.property,
- important: provenance.important,
- key: winner.key,
- priority: self.priorities[provenance.priority],
- source: provenance.source,
- })
- }
-
- fn group_bucket(&self, group: WinnerGroupRef) -> PropertyID {
- self.groups[group.winners]
- .first()
- .expect("a winner group is non-empty")
- .property
- / WINNER_GROUP_PROPERTY_COUNT
- }
-
- /// Name the flush whose publications the rows record from now on.
- pub fn begin_flush(&mut self, stamp: u64) {
- self.stamp = stamp;
- }
-
- /// The flush that published the node's row, when it has one.
- #[must_use]
- pub fn row_stamp(&self, node: StyleNodeID) -> Option<u64> {
- let index = node.element_index()? as usize;
- self.column.get(index)?.as_ref()?;
- Some(self.stamps.get(index).copied().unwrap_or(0))
- }
-
- /// The flush that published the node's row for a pseudo-element, when it has one.
- #[must_use]
- pub fn pseudo_row_stamp(&self, node: StyleNodeID, pseudo: PseudoElementTarget) -> Option<u64> {
- node.element_index()
- .and_then(|index| self.pseudo_rows_by_node.get(index as usize))
- .and_then(|rows| rows.iter().find(|row| row.pseudo == pseudo))
- .map(|row| row.stamp)
- }
-
- #[must_use]
- pub fn winner_in_state(&self, state: CascadeStateID, property: PropertyID) -> Option<PropertyWinner> {
- let groups = &self.states[state];
- let index = groups.partition_point(|group| {
- self.groups[group.winners]
- .last()
- .is_some_and(|winner| winner.property < property)
- });
- let group = *groups.get(index)?;
- let winners = &self.groups[group.winners];
- winners
- .binary_search_by_key(&property, |winner| winner.property)
- .ok()
- .map(|index| {
- let provenance = &self.provenance_groups[group.provenance][index];
- PropertyWinner {
- property: winners[index].property,
- important: provenance.important,
- key: winners[index].key,
- priority: self.priorities[provenance.priority],
- source: provenance.source,
- }
- })
- }
-
- /// What `state`'s winners read beyond the cascade, as `STATE_READS_*` bits, once decided.
- pub(super) fn state_reads(&self, state: CascadeStateID) -> Option<u8> {
- let reads = self.state_reads.get(state.0 as usize)?.load(Ordering::Relaxed);
- (reads & STATE_READS_DECIDED != 0).then_some(reads & !STATE_READS_DECIDED)
- }
-
- pub(super) fn note_state_reads(&self, state: CascadeStateID, reads: u8) {
- if let Some(slot) = self.state_reads.get(state.0 as usize) {
- slot.store(reads | STATE_READS_DECIDED, Ordering::Relaxed);
- }
- }
-
- /// The summary of `state`'s winners, once decided.
- pub(super) fn state_summary(&self, state: CascadeStateID) -> Option<StateSummary> {
- let packed = self.state_summaries.get(state.0 as usize)?.load(Ordering::Relaxed);
- (packed & STATE_SUMMARY_DECIDED != 0).then_some(StateSummary {
- explicitly_inherited_groups: packed as u32,
- has_substitutions: packed & STATE_SUMMARY_HAS_SUBSTITUTIONS != 0,
- has_unknown_values: false,
- })
- }
-
- pub(super) fn note_state_summary(&self, state: CascadeStateID, summary: StateSummary) {
- debug_assert!(!summary.has_unknown_values);
- if let Some(slot) = self.state_summaries.get(state.0 as usize) {
- let substitutions = if summary.has_substitutions {
- STATE_SUMMARY_HAS_SUBSTITUTIONS
- } else {
- 0
- };
- slot.store(
- u64::from(summary.explicitly_inherited_groups) | substitutions | STATE_SUMMARY_DECIDED,
- Ordering::Relaxed,
- );
- }
- }
-
- pub(super) fn state_custom_property_reads(
- &self,
- state: CascadeStateID,
- decide: impl FnOnce() -> Option<CustomPropertyNames>,
- ) -> Option<CustomPropertyNames> {
- match self.state_custom_property_reads.get(state.0 as usize) {
- Some(slot) => slot.get_or_init(decide).clone(),
- None => decide(),
- }
- }
-
- pub(super) fn winner_count_in_state(&self, state: CascadeStateID) -> usize {
- self.states[state]
- .iter()
- .map(|group| self.groups[group.winners].len())
- .sum()
- }
-
- pub fn winners_in_state(&self, state: CascadeStateID) -> impl Iterator<Item = PropertyWinner> + '_ {
- self.states[state].iter().flat_map(|&group| self.group_winners(group))
- }
-
- pub(super) fn rules_for_compaction(&self, state: CascadeStateID) -> Option<&[RuleID]> {
- self.winners_in_state(state)
- .all(|winner| {
- matches!(winner.source, WinnerSource::Rule(_))
- && winner.key.continuation == CascadeContinuationID::default()
- })
- .then(|| self.state_winning_rules[state.0 as usize].as_ref())
- }
-
- pub(super) fn states_are_semantically_equal(&self, left: CascadeStateID, right: CascadeStateID) -> bool {
- left == right
- || (self.custom_declarations_of(left) == self.custom_declarations_of(right)
- && self.states[left]
- .iter()
- .map(|group| group.winners)
- .eq(self.states[right].iter().map(|group| group.winners)))
- }
-
- /// The custom declarations a state's target resolves: identical lists share one identity.
- pub(super) fn custom_declarations_of(&self, state: CascadeStateID) -> CustomDeclarationListID {
- self.state_custom_declarations[state.0 as usize]
- }
-
- pub(super) fn properties_in_state(&self, state: CascadeStateID) -> impl Iterator<Item = PropertyID> {
- self.states[state]
- .iter()
- .flat_map(move |group| self.groups[group.winners].iter().map(|winner| winner.property))
- }
-
- /// Compare the semantic winners consumed by two computed-style publications.
- ///
- /// Missing retained coverage is not the implicit cascade result. It conservatively reports
- /// every explicit current winner, but the returned property list alone cannot prove semantic
- /// equality when `previous` is `None`.
- ///
- /// Missing rows represent the implicit cascade result, so inserting or removing an explicit
- /// winner changes that property. Equal specified keys stop even when the winning rule or its
- /// priority changed.
- #[must_use]
- pub fn semantic_delta(&self, previous: Option<CascadeStateID>, current: CascadeStateID) -> CascadeWinnerDelta {
- CascadeWinnerDelta {
- properties: self.semantic_delta_properties(previous, current).collect(),
- }
- }
-
- /// Iterate changed properties in order without allocating a delta list.
- pub(super) fn semantic_delta_properties(
- &self,
- previous: Option<CascadeStateID>,
- current: CascadeStateID,
- ) -> impl Iterator<Item = PropertyID> {
- let (previous, current): (&[WinnerGroupRef], &[WinnerGroupRef]) = if previous == Some(current) {
- (&[], &[])
- } else {
- (
- previous.map_or(&[], |state| self.states[state].as_ref()),
- self.states[current].as_ref(),
- )
- };
- merge_sorted_by(previous, current, move |old, new| {
- self.group_bucket(*old).cmp(&self.group_bucket(*new))
- })
- .filter_map(|entry| match entry {
- SortedMergeEntry::Both(old, new) if old.winners != new.winners => {
- Some((Some(old.winners), Some(new.winners)))
- }
- SortedMergeEntry::Both(..) => None,
- SortedMergeEntry::Left(old) => Some((Some(old.winners), None)),
- SortedMergeEntry::Right(new) => Some((None, Some(new.winners))),
- })
- .flat_map(move |(previous, current)| self.group_semantic_delta(previous, current))
- }
-
- /// Hash the set of properties represented by a state, deliberately leaving their values out.
- /// This identifies candidates which can seed a first computation and then be corrected by the
- /// exact semantic delta.
- pub(super) fn property_shape_hash(&self, state: CascadeStateID) -> u64 {
- let mut hasher = fast_hasher();
- for property in self.properties_in_state(state) {
- property.hash(&mut hasher);
- }
- hasher.finish()
- }
-
- pub(super) fn property_shapes_are_equal(&self, left: CascadeStateID, right: CascadeStateID) -> bool {
- if left == right {
- return true;
- }
- let left = &self.states[left];
- let right = &self.states[right];
- // Each property belongs to a fixed bucket, so equal shapes have corresponding groups.
- left.len() == right.len()
- && left.iter().zip(right.iter()).all(|(left, right)| {
- if left.winners == right.winners {
- return true;
- }
- let left = &self.groups[left.winners];
- let right = &self.groups[right.winners];
- left.len() == right.len()
- && left
- .iter()
- .map(|winner| winner.property)
- .eq(right.iter().map(|winner| winner.property))
- })
- }
-
- fn group_semantic_delta(
- &self,
- previous: Option<WinnerGroupID>,
- current: Option<WinnerGroupID>,
- ) -> impl Iterator<Item = PropertyID> {
- let previous: &[SemanticPropertyWinner] = previous.map_or(&[], |group| self.groups[group].as_ref());
- let current: &[SemanticPropertyWinner] = current.map_or(&[], |group| self.groups[group].as_ref());
- merge_sorted_by(previous, current, |old, new| old.property.cmp(&new.property)).filter_map(|entry| match entry {
- SortedMergeEntry::Both(old, new) => (old.key != new.key).then_some(old.property),
- SortedMergeEntry::Left(old) => Some(old.property),
- SortedMergeEntry::Right(new) => Some(new.property),
- })
- }
-
- #[must_use]
- pub fn payload_count(&self) -> usize {
- self.groups.len()
- }
-
- #[must_use]
- pub fn state_count(&self) -> usize {
- self.states.len()
- }
-
- #[must_use]
- pub fn winner_entry_count(&self) -> usize {
- self.winner_entry_count
- }
-
- #[must_use]
- pub fn generation(&self) -> u64 {
- self.generation
- }
-
- #[must_use]
- fn set_with_reference(
- &mut self,
- node: StyleNodeID,
- state: CascadeStateID,
- program_version: ProgramVersion,
- reference: WinnerReference,
- ) -> bool {
- let Some(index) = node.element_index().map(|index| index as usize) else {
- self.release_unused_reference(state, reference);
- return false;
- };
- self.column.ensure(index);
- self.stamps.insert(index, self.stamp);
- if self.column[index] == Some((state, program_version)) {
- self.set_priority_current(index, true);
- self.release_unused_reference(state, reference);
- return true;
- }
- if let Some((previous, previous_version)) = self.column[index] {
- self.update_winner_rule_node_references(previous, node, false);
- self.release_state(previous);
- if previous_version == self.newest_program_version {
- self.newest_version_row_count -= 1;
- }
- } else {
- self.row_count += 1;
- }
- if program_version > self.newest_program_version {
- self.newest_program_version = program_version;
- self.newest_version_row_count = 0;
- }
- self.column[index] = Some((state, program_version));
- match reference {
- #[cfg(test)]
- WinnerReference::Retained => self.retain_state(state),
- WinnerReference::Pending => self.transfer_pending(state),
- }
- self.update_winner_rule_node_references(state, node, true);
- if program_version == self.newest_program_version {
- self.newest_version_row_count += 1;
- }
- self.set_priority_current(index, true);
- true
- }
-
- #[must_use]
- fn set_pseudo_with_reference(
- &mut self,
- node: StyleNodeID,
- pseudo: PseudoElementTarget,
- state: CascadeStateID,
- program_version: ProgramVersion,
- reference: WinnerReference,
- ) -> bool {
- let Some(index) = node.element_index().map(|index| index as usize) else {
- self.release_unused_reference(state, reference);
- return false;
- };
- let existing = self
- .pseudo_rows_by_node
- .get(index)
- .and_then(|rows| rows.iter().position(|row| row.pseudo == pseudo));
- self.pseudo_rows_by_node.ensure(index);
- if let Some(existing) = existing {
- let row = &mut self.pseudo_rows_by_node[index][existing];
- row.stamp = self.stamp;
- if row.state == (state, program_version) {
- row.priority_current = true;
- self.release_unused_reference(state, reference);
- return true;
- }
- let previous = row.state.0;
- *row = PseudoWinnerRow {
- pseudo,
- state: (state, program_version),
- priority_current: true,
- stamp: self.stamp,
- };
- self.update_winner_rule_node_references(previous, node, false);
- self.release_state(previous);
- } else {
- self.pseudo_rows_by_node[index].push(PseudoWinnerRow {
- pseudo,
- state: (state, program_version),
- priority_current: true,
- stamp: self.stamp,
- });
- }
- match reference {
- #[cfg(test)]
- WinnerReference::Retained => self.retain_state(state),
- WinnerReference::Pending => self.transfer_pending(state),
- }
- self.update_winner_rule_node_references(state, node, true);
- true
- }
-
- pub fn remove(&mut self, node: StyleNodeID) {
- let Some(index) = node.element_index().map(|index| index as usize) else {
- return;
- };
- if let Some((previous, program_version)) = self.column.get_mut(index).and_then(Option::take) {
- self.update_winner_rule_node_references(previous, node, false);
- self.release_state(previous);
- self.row_count -= 1;
- if program_version == self.newest_program_version {
- self.newest_version_row_count -= 1;
- }
- }
- self.set_priority_current(index, false);
- if let Some(rows) = self.pseudo_rows_by_node.get_mut(index) {
- let rows = std::mem::take(rows);
- for row in rows {
- self.update_winner_rule_node_references(row.state.0, node, false);
- self.release_state(row.state.0);
- }
- }
- }
-
- fn transfer_pending(&mut self, state: CascadeStateID) {
- self.retain_state(state);
- self.release_pending(state);
- }
-
- fn release_unused_reference(&mut self, state: CascadeStateID, reference: WinnerReference) {
- match reference {
- #[cfg(test)]
- WinnerReference::Retained => {}
- WinnerReference::Pending => self.release_pending(state),
- }
- }
-
- #[cfg(test)]
- pub fn set(&mut self, node: StyleNodeID, state: CascadeStateID, version: ProgramVersion) -> bool {
- self.set_with_reference(node, state, version, WinnerReference::Retained)
- }
-
- #[cfg(test)]
- pub fn set_pseudo(
- &mut self,
- node: StyleNodeID,
- pseudo: PseudoElementTarget,
- state: CascadeStateID,
- version: ProgramVersion,
- ) -> bool {
- self.set_pseudo_with_reference(node, pseudo, state, version, WinnerReference::Retained)
- }
-
- #[cfg(test)]
- pub(super) fn pending_reference_count(&self) -> u64 {
- self.state_pending_reference_counts
- .iter()
- .map(|&count| u64::from(count))
- .sum()
- }
-
- fn retain_pending(&mut self, state: CascadeStateID) {
- let count = &mut self.state_pending_reference_counts[state.0 as usize];
- *count = count.checked_add(1).expect("winner pending reference count exhausted");
- }
-
- fn release_pending(&mut self, state: CascadeStateID) {
- self.state_pending_reference_counts[state.0 as usize] -= 1;
- }
-
- fn retain_state(&mut self, state: CascadeStateID) {
- let index = state.0 as usize;
- if self.state_reference_counts[index] == 0 {
- for &rule in &self.state_winning_rules[index] {
- self.winner_rule_references.retain(rule);
- }
- }
- self.state_reference_counts[index] += 1;
- }
-
- fn release_state(&mut self, state: CascadeStateID) {
- let index = state.0 as usize;
- self.state_reference_counts[index] -= 1;
- if self.state_reference_counts[index] == 0 {
- for &rule in &self.state_winning_rules[index] {
- self.winner_rule_references.release(rule);
- }
- }
- }
-
- fn update_winner_rule_node_references(&mut self, state: CascadeStateID, node: StyleNodeID, retain: bool) {
- let winner_rule_references = &mut self.winner_rule_references;
- for &rule in &self.state_winning_rules[state.0 as usize] {
- if retain {
- winner_rule_references.retain_node(rule, node);
- } else {
- winner_rule_references.release_node(rule, node);
- }
- }
- }
-
- #[must_use]
- pub fn rule_is_a_winner(&self, rule: RuleID) -> bool {
- self.winner_rule_references.contains(rule)
- }
-
- pub fn winning_nodes(&self, rule: RuleID) -> Option<impl Iterator<Item = StyleNodeID> + '_> {
- self.winner_rule_references.nodes(rule)
- }
-
- fn priority_is_current(&self, index: usize) -> bool {
- self.priority_current.contains(index)
- }
-
- fn set_priority_current(&mut self, index: usize, current: bool) {
- if !self.priority_current.set(index, current).0 {
- return;
- }
- if current {
- self.priority_current_row_count += 1;
- } else {
- self.priority_current_row_count -= 1;
- }
- }
-
- /// Keep semantic winner keys while marking their topology-dependent priorities stale.
- pub fn invalidate_priorities(&mut self) {
- if self.priority_current_row_count != 0 {
- self.priority_current.clear();
- self.priority_current_row_count = 0;
- }
- for rows in self.pseudo_rows_by_node.iter_mut() {
- for row in rows {
- row.priority_current = false;
- }
- }
- }
-
- #[must_use]
- pub(super) fn token_for(&self, key: WinnerGroupKey) -> Lookup<(u64, CascadeStateID), WinnerGroupGap> {
- match self.lookup(key).sparse() {
- Ok(&(state, _)) => Lookup::Known((self.generation, state)),
- Err(gap) => Lookup::Missing(gap),
- }
- }
-
- #[must_use]
- pub(super) fn coverage_at_least(
- &self,
- program_version: ProgramVersion,
- row_count: usize,
- ) -> Lookup<(), WinnerGroupCoverageGap> {
- if self.newest_program_version != program_version {
- return Lookup::Missing(WinnerGroupCoverageGap::StaleProgram {
- retained: self.newest_program_version,
- required: program_version,
- });
- }
- // Departed nodes lose their rows at the commit barrier and arriving nodes have no row yet.
- // Therefore the resident row count names exactly the connected elements that must already
- // have a winner row, and covering it proves there is no connected-element gap.
- if self.newest_version_row_count < row_count {
- return Lookup::Missing(WinnerGroupCoverageGap::InsufficientProgramRows {
- retained: self.newest_version_row_count,
- required: row_count,
- });
- }
- if self.priority_current_row_count < row_count {
- return Lookup::Missing(WinnerGroupCoverageGap::InsufficientPriorityRows {
- retained: self.priority_current_row_count,
- required: row_count,
- });
- }
- Lookup::Known(())
- }
-
- /// Start retained winner coverage for a new program version with no proven rows.
- pub fn begin_program_version(&mut self, version: ProgramVersion) {
- if version > self.newest_program_version {
- self.newest_program_version = version;
- self.newest_version_row_count = 0;
- }
- }
-
- /// Advance rows whose retained winners were proven unchanged by a program transaction.
- pub fn advance_program_version_where(
- &mut self,
- from: ProgramVersion,
- to: ProgramVersion,
- mut can_advance: impl FnMut(StyleNodeID) -> bool,
- ) {
- if from == to {
- return;
- }
- debug_assert!(to > from);
- self.begin_program_version(to);
- for (index, slot) in self.column.iter_mut().enumerate().skip(1) {
- let Some((_, version)) = slot else {
- continue;
- };
- if *version != from {
- continue;
- }
- let node = StyleNodeID::element(u32::try_from(index).expect("style node identity space exhausted"));
- if !can_advance(node) {
- continue;
- }
- *version = to;
- if to == self.newest_program_version {
- self.newest_version_row_count += 1;
- }
- }
- for (index, rows) in self.pseudo_rows_by_node.iter_mut().enumerate().skip(1) {
- if rows.is_empty() {
- continue;
- }
- let node = StyleNodeID::element(u32::try_from(index).expect("style node identity space exhausted"));
- for row in rows {
- if row.state.1 == from && can_advance(node) {
- row.state.1 = to;
- }
- }
- }
- }
-
- pub fn active_states(&self) -> impl Iterator<Item = CascadeStateID> + '_ {
- self.states
- .iter()
- .zip(&self.state_reference_counts)
- .enumerate()
- .filter(|(_, (_, references))| **references > 0)
- .map(|(index, _)| CascadeStateID(u32::try_from(index).expect("cascade state identity space exhausted")))
- }
-
- pub(super) fn pseudo_states(
- &self,
- node: StyleNodeID,
- ) -> impl Iterator<Item = (PseudoElementTarget, ProgramVersion, CascadeStateID, bool)> + '_ {
- let rows = node
- .element_index()
- .and_then(|index| self.pseudo_rows_by_node.get(index as usize))
- .into_iter()
- .flatten();
- rows.map(|row| (row.pseudo, row.state.1, row.state.0, row.priority_current))
- }
-
- pub(super) fn mark_pseudo_inventory_incomplete(&mut self, node: StyleNodeID, pseudo: PseudoElementTarget) {
- if let Some(row) = node
- .element_index()
- .and_then(|index| self.pseudo_rows_by_node.get_mut(index as usize))
- .and_then(|rows| rows.iter_mut().find(|row| row.pseudo == pseudo))
- {
- row.priority_current = false;
- }
- }
-
- /// The winning declaration for one property of one node, if a group is resident.
- #[must_use]
- pub(super) fn winner(&self, key: WinnerGroupKey, property: PropertyID) -> Lookup<PropertyWinner, WinnerGroupGap> {
- let state = match self.lookup(key).sparse() {
- Ok(&(state, _)) => state,
- Err(gap) => return Lookup::Missing(gap),
- };
- match self.winner_in_state(state, property) {
- Some(winner) => Lookup::Known(winner),
- None => Lookup::KnownAbsent,
- }
- }
-}
-
-impl WinnerGroups {
- pub(super) fn lookup(&self, key: WinnerGroupKey) -> Lookup<&(CascadeStateID, ProgramVersion), WinnerGroupGap> {
- if let Some(pseudo) = key.pseudo {
- let Some(row) = key
- .node
- .element_index()
- .and_then(|index| self.pseudo_rows_by_node.get(index as usize))
- .and_then(|rows| rows.iter().find(|row| row.pseudo == pseudo))
- else {
- return Lookup::Missing(WinnerGroupGap::MissingNode(key.node));
- };
- if row.state.1 != key.program_version {
- return Lookup::Missing(WinnerGroupGap::StaleProgram {
- node: key.node,
- retained: row.state.1,
- required: key.program_version,
- });
- }
- if key.priority == WinnerPriorityCoverage::Current && !row.priority_current {
- return Lookup::Missing(WinnerGroupGap::StalePriority(key.node));
- }
- return Lookup::Known(&row.state);
- }
- let Some(index) = key.node.element_index().map(|index| index as usize) else {
- return Lookup::Missing(WinnerGroupGap::MissingNode(key.node));
- };
- let Some(row @ (_, retained_program_version)) = self.column.get(index).and_then(Option::as_ref) else {
- return Lookup::Missing(WinnerGroupGap::MissingNode(key.node));
- };
- if *retained_program_version != key.program_version {
- return Lookup::Missing(WinnerGroupGap::StaleProgram {
- node: key.node,
- retained: *retained_program_version,
- required: key.program_version,
- });
- }
- if key.priority == WinnerPriorityCoverage::Current && !self.priority_is_current(index) {
- return Lookup::Missing(WinnerGroupGap::StalePriority(key.node));
- }
- Lookup::Known(row)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn inputs(origin: CascadeOrigin, important: bool) -> PriorityInputs {
- PriorityInputs {
- origin,
- important,
- context_depth: 0,
- element_attachment: ElementAttachment::Rule,
- layer_rank: 100,
- specificity: Specificity::default(),
- scope_proximity: 0,
- sheet_rank: 10,
- rule_rank: 10,
- }
- }
-
- #[test]
- fn pending_winners_share_completed_states_without_installing_donors() {
- let mut groups = WinnerGroups::new();
- let earlier = StyleNodeID::element(1);
- let later = StyleNodeID::element(2);
- let before = PseudoElementTarget::new(super::super::tree::PseudoElementKind(0));
- let after = PseudoElementTarget::new(super::super::tree::PseudoElementKind(2));
- let old = groups.intern_sorted(&[winner(1, 10, 1)], None);
- let new = groups.intern_sorted(&[winner(1, 20, 2)], None);
- assert!(groups.set(earlier, old, ProgramVersion(1)));
- assert!(groups.set_pseudo(earlier, after, old, ProgramVersion(1)));
- groups.begin_flush(2);
- let mut effects = WinnerEffects::default();
- assert!(effects.set(&mut groups, later, new, ProgramVersion(2)));
- assert!(effects.set_pseudo(&mut groups, later, before, new, ProgramVersion(2)));
- effects.mark_pseudo_inventory_incomplete(later, before);
- assert_eq!(
- effects.copy_node_rows(&mut groups, later, earlier, ProgramVersion(2)),
- Some(2)
- );
- // Replacing the producer afterwards must not change its consumer's completed payload.
- assert!(effects.set(&mut groups, later, old, ProgramVersion(2)));
- let key = WinnerGroupKey::current(earlier, ProgramVersion(2));
- assert!(matches!(groups.lookup(key), Lookup::Missing(_)));
- assert!(!groups.rule_is_a_winner(RuleID(2)));
- assert_eq!(
- effects.view(&groups).token_for(key),
- Lookup::Known((groups.generation(), new))
- );
- assert_eq!(
- effects.view(&groups).pseudo_state(earlier, before),
- Some((ProgramVersion(2), new, false))
- );
- assert_eq!(effects.view(&groups).pseudo_state(earlier, after), None);
- assert_eq!(effects.view(&groups).row_stamp(earlier), Some(2));
- effects.install(&mut groups);
- assert_eq!(groups.token_for(key), Lookup::Known((groups.generation(), new)));
- assert_eq!(
- groups.pseudo_states(earlier).collect::<Vec<_>>(),
- vec![(before, ProgramVersion(2), new, false)]
- );
- assert_eq!(
- groups.winning_nodes(RuleID(2)).unwrap().collect::<Vec<_>>(),
- vec![earlier, later]
- );
- assert!(groups.state_pending_reference_counts.iter().all(|&count| count == 0));
- }
-
- #[test]
- fn the_origin_ladder_puts_importance_where_the_cascade_does() {
- let normal_ua = CascadePriority::new(inputs(CascadeOrigin::UserAgent, false));
- let normal_user = CascadePriority::new(inputs(CascadeOrigin::User, false));
- let hint = CascadePriority::new(inputs(CascadeOrigin::AuthorPresentationalHint, false));
- let normal_author = CascadePriority::new(inputs(CascadeOrigin::Author, false));
- let important_author = CascadePriority::new(inputs(CascadeOrigin::Author, true));
- let important_user = CascadePriority::new(inputs(CascadeOrigin::User, true));
- let important_ua = CascadePriority::new(inputs(CascadeOrigin::UserAgent, true));
-
- let ladder = [
- normal_ua,
- normal_user,
- hint,
- normal_author,
- important_author,
- important_user,
- important_ua,
- ];
- assert!(ladder.windows(2).all(|pair| pair[0] < pair[1]));
-
- // A presentational hint loses to an author rule, however specific the hint's source.
- assert!(hint < normal_author);
- }
-
- #[test]
- fn importance_reverses_layer_order() {
- let mut early = inputs(CascadeOrigin::Author, false);
- early.layer_rank = 10;
- let mut late = inputs(CascadeOrigin::Author, false);
- late.layer_rank = 20;
- assert!(
- CascadePriority::new(early) < CascadePriority::new(late),
- "later layers win"
- );
-
- early.important = true;
- late.important = true;
- assert!(
- CascadePriority::new(late) < CascadePriority::new(early),
- "and the order reverses for important declarations"
- );
- }
-
- #[test]
- fn importance_reverses_encapsulation_context() {
- let mut outer = inputs(CascadeOrigin::Author, false);
- outer.context_depth = 0;
- let mut inner = inputs(CascadeOrigin::Author, false);
- inner.context_depth = 2;
- assert!(
- CascadePriority::new(inner) < CascadePriority::new(outer),
- "outer contexts win for normal declarations"
- );
-
- outer.important = true;
- inner.important = true;
- assert!(
- CascadePriority::new(outer) < CascadePriority::new(inner),
- "inner contexts win for important ones"
- );
- }
-
- #[test]
- fn an_element_attached_style_beats_every_rule_in_its_context() {
- let mut rule = inputs(CascadeOrigin::Author, false);
- rule.layer_rank = u64::MAX - 1;
- rule.specificity = Specificity {
- ids: 100,
- classes: 100,
- types: 100,
- };
- let mut inline = inputs(CascadeOrigin::Author, false);
- inline.element_attachment = ElementAttachment::InlineStyle;
- inline.layer_rank = 0;
-
- assert!(CascadePriority::new(rule) < CascadePriority::new(inline));
- }
-
- #[test]
- fn specificity_then_proximity_then_source_order_break_ties() {
- let base = inputs(CascadeOrigin::Author, false);
- let mut specific = base;
- specific.specificity = Specificity {
- classes: 1,
- ..Specificity::default()
- };
- assert!(CascadePriority::new(base) < CascadePriority::new(specific));
-
- let mut near = base;
- near.scope_proximity = 1;
- let mut far = base;
- far.scope_proximity = 5;
- assert!(
- CascadePriority::new(far) < CascadePriority::new(near),
- "nearer scopes win"
- );
-
- let mut early = base;
- early.rule_rank = 10;
- let mut late = base;
- late.rule_rank = 20;
- assert!(CascadePriority::new(early) < CascadePriority::new(late));
-
- let mut early_sheet = base;
- early_sheet.sheet_rank = 1;
- early_sheet.rule_rank = u64::MAX;
- let mut late_sheet = base;
- late_sheet.sheet_rank = 2;
- late_sheet.rule_rank = 0;
- assert!(
- CascadePriority::new(early_sheet) < CascadePriority::new(late_sheet),
- "sheet order outranks position within a sheet"
- );
- }
-
- fn winner_key(value: u64) -> SpecifiedWinnerKey {
- SpecifiedWinnerKey {
- value: SpecifiedValueID(value),
- operator: CascadeOperator::Declared,
- continuation: CascadeContinuationID::default(),
- animation_relevance: 0,
- important: false,
- }
- }
-
- fn winner(property: PropertyID, value: u64, rule: u32) -> PropertyWinner {
- PropertyWinner {
- property,
- important: false,
- key: winner_key(value),
- priority: CascadePriority::new(inputs(CascadeOrigin::Author, false)),
- source: WinnerSource::Rule(RuleID(rule)),
- }
- }
-
- fn candidate(
- value: u64,
- rule: u32,
- operator: CascadeOperator,
- origin: CascadeOrigin,
- important: bool,
- layer: CascadeLayerID,
- layer_rank: u64,
- ) -> CascadeCandidate {
- let mut priority_inputs = inputs(origin, important);
- priority_inputs.layer_rank = layer_rank;
- priority_inputs.rule_rank = u64::from(rule);
- let mut winner = winner(1, value, rule);
- winner.key.operator = operator;
- let priority = CascadePriority::new(priority_inputs);
- winner.priority = priority;
- CascadeCandidate {
- winner,
- stratum: CascadeStratum::new(origin, important, 0, layer, layer_rank, CascadeAttachment::StyleSheet),
- }
- }
-
- #[test]
- fn author_revert_continues_to_the_user_agent_origin() {
- let mut groups = WinnerGroups::new();
- let mut candidates = [
- candidate(
- 10,
- 1,
- CascadeOperator::Declared,
- CascadeOrigin::UserAgent,
- false,
- CascadeLayerID::UNLAYERED,
- 0,
- ),
- candidate(
- 20,
- 2,
- CascadeOperator::Declared,
- CascadeOrigin::Author,
- false,
- CascadeLayerID::UNLAYERED,
- 0,
- ),
- candidate(
- 30,
- 3,
- CascadeOperator::Revert,
- CascadeOrigin::Author,
- false,
- CascadeLayerID::UNLAYERED,
- 0,
- ),
- ];
-
- let winner = groups.resolve_candidates(&mut candidates).unwrap();
- assert_eq!(winner.key.operator, CascadeOperator::Revert);
- assert_eq!(groups.resolved_winner(winner).unwrap().key.value, SpecifiedValueID(10));
- assert_eq!(groups.continuation_count(), 1);
-
- let same = groups.resolve_candidates(&mut candidates).unwrap();
- assert_eq!(same.key.continuation, winner.key.continuation);
- assert_eq!(
- groups.continuation_count(),
- 1,
- "equal cascade states share their continuation"
- );
- }
-
- #[test]
- fn revert_layer_continues_across_three_normal_layers() {
- let mut groups = WinnerGroups::new();
- let mut candidates = [
- candidate(
- 10,
- 1,
- CascadeOperator::Declared,
- CascadeOrigin::Author,
- false,
- CascadeLayerID(1),
- 1,
- ),
- candidate(
- 20,
- 2,
- CascadeOperator::Declared,
- CascadeOrigin::Author,
- false,
- CascadeLayerID(2),
- 2,
- ),
- candidate(
- 30,
- 3,
- CascadeOperator::RevertLayer,
- CascadeOrigin::Author,
- false,
- CascadeLayerID(3),
- 3,
- ),
- ];
-
- let winner = groups.resolve_candidates(&mut candidates).unwrap();
- assert_eq!(groups.resolved_winner(winner).unwrap().key.value, SpecifiedValueID(20));
- }
-
- #[test]
- fn revert_layer_continues_from_the_implicit_outer_layer() {
- let mut groups = WinnerGroups::new();
- let mut candidates = [
- candidate(
- 10,
- 1,
- CascadeOperator::Declared,
- CascadeOrigin::Author,
- false,
- CascadeLayerID(1),
- 1,
- ),
- candidate(
- 20,
- 2,
- CascadeOperator::RevertLayer,
- CascadeOrigin::Author,
- false,
- CascadeLayerID::UNLAYERED,
- 2,
- ),
- ];
-
- let winner = groups.resolve_candidates(&mut candidates).unwrap();
- assert_eq!(groups.resolved_winner(winner).unwrap().key.value, SpecifiedValueID(10));
- }
-
- #[test]
- fn important_revert_layer_follows_reversed_layer_order() {
- let mut groups = WinnerGroups::new();
- let mut candidates = [
- candidate(
- 20,
- 2,
- CascadeOperator::Declared,
- CascadeOrigin::Author,
- false,
- CascadeLayerID(1),
- 1,
- ),
- candidate(
- 10,
- 1,
- CascadeOperator::RevertLayer,
- CascadeOrigin::Author,
- true,
- CascadeLayerID(2),
- 2,
- ),
- candidate(
- 30,
- 3,
- CascadeOperator::Declared,
- CascadeOrigin::Author,
- true,
- CascadeLayerID(3),
- 3,
- ),
- ];
-
- let winner = groups.resolve_candidates(&mut candidates).unwrap();
- assert_eq!(winner.source, WinnerSource::Rule(RuleID(1)));
- assert_eq!(groups.resolved_winner(winner).unwrap().key.value, SpecifiedValueID(20));
- }
-
- #[test]
- fn top_1_cascade_keeps_one_greatest_row_per_output() {
- let mut top_1 = Top1Cascade::with_capacity(4);
- top_1.consider(2_u16, 5_u32, "first");
- top_1.consider(1, 7, "other property");
- top_1.consider(2, 3, "loser");
- top_1.consider(2, 5, "later tie");
-
- assert_eq!(top_1.winner(&1).map(|winner| winner.payload), Some("other property"));
- assert_eq!(top_1.winner(&2).map(|winner| winner.payload), Some("later tie"));
- assert!(top_1.winner(&3).is_none());
- assert_eq!(top_1.winners().map(|winner| winner.key).collect::<Vec<_>>(), vec![1, 2]);
-
- top_1.clear();
- assert!(top_1.winners().next().is_none());
- top_1.consider(3, 9, "reused");
- assert_eq!(top_1.winner(&3).map(|winner| winner.payload), Some("reused"));
- }
-
- #[test]
- fn a_cascade_operator_is_part_of_the_specified_key() {
- let declared = winner_key(1);
- let inherited = SpecifiedWinnerKey {
- operator: CascadeOperator::Inherit,
- ..declared
- };
- assert_ne!(declared, inherited);
-
- // Two reverts differing only in where they resume are different specified winners.
- let revert = SpecifiedWinnerKey {
- operator: CascadeOperator::RevertLayer,
- continuation: CascadeContinuationID(1),
- ..declared
- };
- let deeper = SpecifiedWinnerKey {
- continuation: CascadeContinuationID(2),
- ..revert
- };
- assert_ne!(revert, deeper);
- }
-
- #[test]
- fn importance_is_part_of_the_specified_key() {
- let declared = winner_key(1);
- let important = SpecifiedWinnerKey {
- important: true,
- ..declared
- };
- assert_ne!(declared, important);
- }
-
- #[test]
- fn semantic_winner_deltas_ignore_provenance_and_report_exact_properties() {
- let mut groups = WinnerGroups::new();
- let before = groups.intern_sorted(&[winner(1, 10, 1), winner(3, 30, 1), winner(5, 50, 1)], None);
- let semantic_group_count = groups.payload_count();
- let same_values = groups.intern_sorted(&[winner(1, 10, 2), winner(3, 30, 2), winner(5, 50, 2)], None);
- assert_ne!(before, same_values);
- assert_eq!(groups.payload_count(), semantic_group_count);
- assert!(groups.semantic_delta(Some(before), same_values).is_empty());
-
- let after = groups.intern_sorted(
- &[winner(1, 11, 2), winner(2, 20, 2), winner(5, 50, 2), winner(7, 70, 2)],
- None,
- );
- assert_eq!(groups.semantic_delta(Some(before), after).properties(), &[1, 2, 3, 7]);
- assert_eq!(groups.semantic_delta(None, after).properties(), &[1, 2, 5, 7]);
- }
-
- #[test]
- fn winner_provenance_retains_exact_priority_without_semantic_identity() {
- let mut groups = WinnerGroups::new();
- let mut before_winner = winner(1, 10, 1);
- let mut before_inputs = inputs(CascadeOrigin::Author, false);
- before_inputs.rule_rank = 1;
- before_winner.priority = CascadePriority::new(before_inputs);
- let before = groups.intern_sorted(&[before_winner], None);
- let semantic_group_count = groups.payload_count();
-
- let mut after_winner = before_winner;
- let mut after_inputs = before_inputs;
- after_inputs.rule_rank = 2;
- after_winner.priority = CascadePriority::new(after_inputs);
- let after = groups.intern_sorted(&[after_winner], None);
-
- assert_ne!(before, after);
- assert_eq!(groups.payload_count(), semantic_group_count);
- assert!(groups.semantic_delta(Some(before), after).is_empty());
- assert_eq!(
- groups.winner_in_state(before, 1).unwrap().priority,
- before_winner.priority
- );
- assert_eq!(
- groups.winner_in_state(after, 1).unwrap().priority,
- after_winner.priority
- );
- }
-
- #[test]
- fn importance_is_weighed_per_declaration_not_per_rule() {
- // Two author rules, the less specific one marking its declaration important. Ordering the
- // rules once by specificity would let the more specific normal declaration win; weighing
- // each declaration with its own importance puts the important one on a higher rung.
- let mut specific = inputs(CascadeOrigin::Author, false);
- specific.specificity = Specificity {
- ids: 1,
- ..Specificity::default()
- };
- specific.rule_rank = 20;
-
- let mut important = inputs(CascadeOrigin::Author, true);
- important.specificity = Specificity {
- classes: 1,
- ..Specificity::default()
- };
- important.rule_rank = 10;
-
- assert!(
- CascadePriority::new(specific) < CascadePriority::new(important),
- "an important author declaration outranks a more specific normal one"
- );
+ assert!(
+ CascadePriority::new(specific) < CascadePriority::new(important),
+ "an important author declaration outranks a more specific normal one"
+ );
// The same rule's other declaration, written without `!important`, does not.
let mut normal = important;
@@ -3055,233 +396,4 @@ mod tests {
"and the same rule's normal declaration still loses to the more specific one"
);
}
-
- #[test]
- fn equal_winner_sets_share_one_state() {
- let mut groups = WinnerGroups::new();
- let first = groups.intern_sorted(&[winner(1, 5, 2), winner(2, 1, 1)], None);
- let second = groups.intern_sorted(&[winner(1, 5, 2), winner(2, 1, 1)], None);
- assert_eq!(first, second);
- assert_eq!(groups.payload_count(), 1);
- assert_eq!(groups.winners_in_state(first).next().unwrap().property, 1);
-
- let different = groups.intern_sorted(&[winner(1, 5, 2)], None);
- assert_ne!(first, different);
- }
-
- #[test]
- fn compaction_rules_require_direct_rule_winners() {
- let mut groups = WinnerGroups::new();
- let state = groups.intern_sorted(&[winner(1, 1, 5), winner(2, 2, 3), winner(33, 3, 5)], None);
- assert_eq!(
- groups.rules_for_compaction(state),
- Some([RuleID(3), RuleID(5)].as_slice())
- );
-
- for source in [
- WinnerSource::Element(ElementDeclarationKind::InlineStyle),
- WinnerSource::ExactCascade,
- ] {
- let mut non_rule = winner(1, 1, 3);
- non_rule.source = source;
- let state = groups.intern_sorted(&[non_rule], None);
- assert!(groups.rules_for_compaction(state).is_none());
- }
-
- let mut candidates = [candidate(
- 1,
- 3,
- CascadeOperator::Revert,
- CascadeOrigin::Author,
- false,
- CascadeLayerID::UNLAYERED,
- 0,
- )];
- let reverted = groups.resolve_candidates(&mut candidates).unwrap();
- let state = groups.intern_sorted(&[reverted], None);
- assert!(groups.rules_for_compaction(state).is_none());
-
- let empty = groups.intern_sorted(&[], None);
- assert_eq!(groups.rules_for_compaction(empty), Some([].as_slice()));
- }
-
- #[test]
- fn cascade_states_share_unmodified_property_groups() {
- let mut groups = WinnerGroups::new();
- let first = groups.intern_sorted(&[winner(1, 1, 1), winner(33, 2, 2)], None);
- let first_group_ids = groups.states[first.0 as usize].clone();
- let group_hash_computations = groups.group_hash_computations;
- let unchanged = groups.intern_sorted(&[winner(1, 1, 1), winner(33, 2, 2)], Some(first));
-
- assert_eq!(unchanged, first);
- assert_eq!(groups.group_hash_computations, group_hash_computations);
-
- let second = groups.intern_sorted(&[winner(1, 1, 1), winner(33, 3, 3)], Some(first));
-
- assert_ne!(first, second);
- assert_eq!(groups.state_count(), 2);
- assert_eq!(groups.payload_count(), 3);
- assert_eq!(groups.winner_entry_count(), 3);
- assert_eq!(groups.states[second.0 as usize][0], first_group_ids[0]);
- assert_eq!(groups.group_hash_computations, group_hash_computations + 1);
- assert_eq!(groups.winner_in_state(first, 1), groups.winner_in_state(second, 1));
- assert_ne!(groups.winner_in_state(first, 33), groups.winner_in_state(second, 33));
- }
-
- #[test]
- fn exact_property_updates_touch_only_their_winner_groups() {
- let mut groups = WinnerGroups::new();
- let before = groups.intern_sorted(&[winner(1, 10, 1), winner(2, 20, 2), winner(33, 30, 3)], None);
- let before_groups = groups.states[before.0 as usize].clone();
- let (after, delta) = groups.apply_property_updates(
- before,
- &[
- PropertyWinnerUpdate {
- property: 2,
- winner: Some(winner(2, 20, 4)),
- },
- PropertyWinnerUpdate {
- property: 33,
- winner: None,
- },
- PropertyWinnerUpdate {
- property: 34,
- winner: Some(winner(34, 40, 5)),
- },
- ],
- );
-
- assert_ne!(after, before);
- assert_eq!(delta.properties(), &[33, 34]);
- assert_eq!(groups.states[after.0 as usize].len(), 2);
- assert_eq!(groups.winner_in_state(after, 1), groups.winner_in_state(before, 1));
- assert_eq!(
- groups.winner_in_state(after, 2).unwrap().source,
- WinnerSource::Rule(RuleID(4))
- );
- assert!(groups.winner_in_state(after, 33).is_none());
- assert_eq!(groups.winner_in_state(after, 34).unwrap().key, winner_key(40));
- assert_ne!(groups.states[after.0 as usize][0], before_groups[0]);
- assert_ne!(groups.states[after.0 as usize][1], before_groups[1]);
-
- let payload_count = groups.payload_count();
- let (unchanged, delta) = groups.apply_property_updates(
- after,
- &[PropertyWinnerUpdate {
- property: 34,
- winner: groups.winner_in_state(after, 34),
- }],
- );
- assert_eq!(unchanged, after);
- assert!(delta.is_empty());
- assert_eq!(groups.payload_count(), payload_count);
- }
-
- #[test]
- fn active_winner_rules_are_indexed_across_shared_groups() {
- let mut groups = WinnerGroups::new();
- let first = groups.intern_sorted(&[winner(1, 1, 3), winner(2, 2, 5)], None);
- let second = groups.intern_sorted(&[winner(1, 3, 5)], None);
- let sparse = groups.intern_sorted(&[winner(1, 4, 100_000)], None);
- let first_node = StyleNodeID::element(1);
- let second_node = StyleNodeID::element(2);
- let sparse_node = StyleNodeID::element(3);
-
- assert!(groups.set(first_node, first, ProgramVersion(1)));
- assert!(groups.set(second_node, first, ProgramVersion(1)));
- assert!(groups.rule_is_a_winner(RuleID(3)));
- assert!(groups.rule_is_a_winner(RuleID(5)));
- assert!(groups.set(sparse_node, sparse, ProgramVersion(1)));
- assert!(groups.rule_is_a_winner(RuleID(100_000)));
- assert_eq!(groups.winner_rule_references.entries.len(), 3);
-
- assert!(groups.set(first_node, second, ProgramVersion(1)));
- groups.remove(second_node);
- assert!(!groups.rule_is_a_winner(RuleID(3)));
- assert!(groups.rule_is_a_winner(RuleID(5)));
-
- groups.remove(first_node);
- assert!(!groups.rule_is_a_winner(RuleID(5)));
- groups.remove(sparse_node);
- assert!(!groups.rule_is_a_winner(RuleID(100_000)));
- assert!(groups.winner_rule_references.entries.is_empty());
- }
-
- #[test]
- fn broad_winner_rule_node_postings_fall_back_to_the_rule_count() {
- let mut groups = WinnerGroups::new();
- let state = groups.intern_sorted(&[winner(1, 1, 3)], None);
- for index in 1..=WINNER_RULE_NODE_LIMIT + 1 {
- assert!(groups.set(
- StyleNodeID::element(u32::try_from(index).unwrap()),
- state,
- ProgramVersion(1),
- ));
- }
-
- assert!(groups.rule_is_a_winner(RuleID(3)));
- assert!(groups.winning_nodes(RuleID(3)).is_none());
-
- for index in 1..=WINNER_RULE_NODE_LIMIT + 1 {
- groups.remove(StyleNodeID::element(u32::try_from(index).unwrap()));
- }
- assert!(!groups.rule_is_a_winner(RuleID(3)));
- }
-
- #[test]
- fn pseudo_cascade_states_are_sparse_and_independent_from_the_element_column() {
- let mut groups = WinnerGroups::new();
- let node = StyleNodeID::element(1);
- let before = PseudoElementTarget::new(super::super::tree::PseudoElementKind(1));
- let after = PseudoElementTarget::new(super::super::tree::PseudoElementKind(2));
- let element_state = groups.intern_sorted(&[winner(1, 10, 1)], None);
- let before_state = groups.intern_sorted(&[winner(1, 20, 2)], None);
- let after_state = groups.intern_sorted(&[winner(1, 30, 3)], None);
-
- assert!(groups.set(node, element_state, ProgramVersion(1)));
- assert!(groups.set_pseudo(node, before, before_state, ProgramVersion(1)));
- assert!(groups.set_pseudo(node, after, after_state, ProgramVersion(1)));
-
- assert!(matches!(
- groups.winner(WinnerGroupKey::current(node, ProgramVersion(1)), 1),
- Lookup::Known(winner) if winner.key == winner_key(10)
- ));
- assert!(matches!(
- groups.winner(WinnerGroupKey::current_pseudo(node, before, ProgramVersion(1)), 1),
- Lookup::Known(winner) if winner.key == winner_key(20)
- ));
- assert!(matches!(
- groups.winner(WinnerGroupKey::current_pseudo(node, after, ProgramVersion(1)), 1),
- Lookup::Known(winner) if winner.key == winner_key(30)
- ));
-
- groups.invalidate_priorities();
- assert!(matches!(
- groups.lookup(WinnerGroupKey::current_pseudo(node, before, ProgramVersion(1))),
- Lookup::Missing(WinnerGroupGap::StalePriority(stale_node)) if stale_node == node
- ));
- assert!(matches!(
- groups.lookup(WinnerGroupKey {
- node,
- pseudo: Some(before),
- program_version: ProgramVersion(1),
- priority: WinnerPriorityCoverage::Retained,
- }),
- Lookup::Known(_)
- ));
-
- groups.remove(node);
- assert!(matches!(
- groups.lookup(WinnerGroupKey {
- node,
- pseudo: Some(before),
- program_version: ProgramVersion(1),
- priority: WinnerPriorityCoverage::Retained,
- }),
- Lookup::Missing(WinnerGroupGap::MissingNode(missing)) if missing == node
- ));
- assert_eq!(groups.state_reference_counts[element_state.0 as usize], 0);
- assert_eq!(groups.state_reference_counts[before_state.0 as usize], 0);
- assert_eq!(groups.state_reference_counts[after_state.0 as usize], 0);
- }
}
diff --git a/Libraries/LibWeb/Rust/src/css/style/computed.rs b/Libraries/LibWeb/Rust/src/css/style/computed.rs
index e5b8e7968ac..fac514b0724 100644
--- a/Libraries/LibWeb/Rust/src/css/style/computed.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/computed.rs
@@ -4,225 +4,395 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! Dense identities for the shared computed-group payloads of live base styles.
+//! The style records elements and pseudo-elements are assigned, by identity.
//!
-//! `ComputedValues` already factorizes its immutable payload into independently shared groups.
-//! This catalog gives each shared payload a dense identity and interns their ordered tuple. Equal
-//! handles therefore prove equal computed groups without comparing a complete `ComputedValues`
-//! object. The converse is intentionally not claimed yet: separately allocated payloads with equal
-//! values remain distinct until value interning lands. Custom-property environments and the fixed
-//! pseudo-style and environment-dependency flags are retained as separate relations. Originating
-//! elements use dense columns, while actual pseudo-element kinds use sparse assignments. The
-//! complete tuple is interned as the base `StyleRecordID` published for each style target.
-
-use smallvec::SmallVec;
-use std::hash::Hash;
-use std::hash::Hasher;
-use std::num::NonZeroU32;
-
-use super::bridge::ElementBoxKind;
-use super::cascade::CascadeStateID;
-use super::column::BitColumn;
+//! Every record is one the engine installed: its groups with their values, its flags and facts, and the payloads the
+//! host renders from, in a slot of [`InstalledRecords`] that records holding the same values in the
+//! same context share. Originating elements are assigned their records in a dense column, while
+//! actual pseudo-element kinds use sparse rows. An element's or pseudo-element's animations compose
+//! an animation overlay record over the record it is assigned, in a recyclable slot of its own.
+
use super::fast_hash::FastMap as HashMap;
-use super::fast_hash::fast_hasher;
-use super::intern_table::InternIdentity;
-use super::intern_table::InternTable;
-#[cfg(test)]
-use super::tree::PseudoElementKind;
-#[cfg(test)]
-use super::tree::PseudoElementTarget;
+use super::installed_records::{InstalledRecord, InstalledRecordID, InstalledRecords};
use super::tree::StyleNodeID;
-use crate::css::computed_longhand_table::{
- ComputedLonghandTable, DEPENDS_ON_VIEWPORT_METRICS, HIGHLIGHT_COLOR_IS_CURRENT_COLOR, HIGHLIGHT_COLORS_AUTHORED,
- longhand_slot_hash,
-};
+use crate::css::computed_longhand_table::DEPENDS_ON_VIEWPORT_METRICS;
use crate::css::computed_values::computed_group_output_mask;
-use crate::css::computed_values::release_group_payload;
-use crate::css::computed_values::retain_group_payload;
-use crate::css::computed_values::style_group_payloads_equal;
-use crate::css::computed_values::style_group_payloads_hash;
use crate::css::computed_values::style_group_payloads_hold_image_values;
-use crate::css::host_shared::{HostShared, SharedPayload};
+use crate::css::host_shared::HostShared;
use crate::css::style_value::RetainedStyleValueData;
-use crate::css::style_value::retained_value_depends_on_color_scheme;
+use crate::css::style_value::ShadowPayload;
use crate::css::style_value::retained_value_depends_on_current_color;
-use crate::css::style_value::retained_value_may_depend_on_font_metrics;
-// Bit 3 is a node-local production capability carried with publication and stripped before the
-// semantic fixed metadata is interned or exposed through a style-record view.
-pub(crate) const INHERITED_GROUP_SWAP_ELIGIBLE: u8 = 1 << 3;
/// The record holds an `<image>` in a property whose images a layout node loads and observes.
-/// Derived from the published payloads; see `style_group_payloads_hold_image_values`.
+/// Derived from the record's payloads; see `style_group_payloads_hold_image_values`.
pub(crate) const HOLDS_IMAGE_VALUES: u8 = 1 << 4;
/// The record is display:none, or its inheritance parent's record is in a display:none subtree.
pub(crate) const IN_DISPLAY_NONE_SUBTREE: u8 = 1 << 2;
-/// The inherited style groups lead every group tuple; a node's inherited-group column names them.
-pub(crate) const ENGINE_INHERITED_GROUP_COUNT: usize = 7;
+/// The inherited style groups lead every group tuple.
+pub(crate) const ENGINE_INHERITED_GROUP_COUNT: usize = crate::css::computed_values::INHERITED_SET_GROUPS.len();
+
+/// What a view of a record with `facts` holding `payloads` says its values depend on.
+pub(super) fn record_dependency_flags(
+ facts: &super::pipeline::RecordFacts,
+ payloads: &crate::css::computed_values::StyleGroups,
+) -> u8 {
+ // SAFETY: The caller holds a reference to each of the payloads.
+ let holds_image_values = unsafe { style_group_payloads_hold_image_values(&payloads.pointers()) };
+ view_dependency_flags(facts, holds_image_values)
+}
+
+/// What a view of a record with `facts`, whose groups hold images or not, says its values depend on.
+pub(super) fn view_dependency_flags(facts: &super::pipeline::RecordFacts, holds_image_values: bool) -> u8 {
+ facts.publication_dependency_flags() | (u8::from(holds_image_values) * HOLDS_IMAGE_VALUES)
+}
-/// Whether a record with this table may take an inherited-group swap: every property inherits
-/// the way its definition says, no marker is generated for it, and no transition runs on it.
-pub(super) fn table_inherited_group_swap_eligible(table: &ComputedLonghandTable) -> bool {
- table.property_inheritance_is_standard()
- && !table.display_is_list_item()
- && !crate::css::style_compute::has_active_transition_properties(table)
+#[derive(Clone, Copy)]
+pub(crate) struct StyleRecordView<'a> {
+ pub payloads: &'a crate::css::computed_values::StyleGroups,
+ pub base_payloads: &'a crate::css::computed_values::StyleGroups,
+ /// The base record, whose longhands the view reads.
+ pub(in crate::css::style) record: &'a std::sync::Arc<super::pipeline::Record>,
+ pub animated_overlay: Option<&'a crate::css::animated_overlay::AnimatedOverlay>,
+ pub pseudo_element_styles: u64,
+ pub counter_style_environment_identity: u64,
+ pub dependency_flags: u8,
}
-/// What assembling an engine-computed record produced, for the publication counters.
-pub(super) struct EngineComputedAssembly {
- pub(super) delta: (FinalStyleRecordID, FinalStyleRecordID),
- /// Rebuilt groups whose payload equalled the old one and kept its identity.
- pub(super) canonicalized_groups: u32,
- /// Whether the node's group tuple identity stayed put, so nothing propagates from it.
- pub(super) group_set_unchanged: bool,
- /// What the record took the place of, for reverting it.
- pub(super) replaced: ReplacedColumns,
+impl<'a> StyleRecordView<'a> {
+ /// The view of `record`, a record the host holds: an installed record, or the sample of the
+ /// animations over one, which reads the longhands, pseudo-elements and counter styles of the
+ /// record it samples over.
+ pub(crate) fn of_host_record(record: &'a std::sync::Arc<super::pipeline::Record>) -> Self {
+ match record.sample_of_animations() {
+ Some(sample) => Self {
+ payloads: &record.payloads,
+ base_payloads: &sample.base.payloads,
+ record: &sample.base,
+ animated_overlay: Some(&sample.animated_overlay),
+ pseudo_element_styles: sample.base.pseudo_element_styles().bits(),
+ counter_style_environment_identity: sample.base.rare().counter_style_environment_identity,
+ dependency_flags: sample.dependency_flags,
+ },
+ None => Self {
+ payloads: &record.payloads,
+ base_payloads: &record.payloads,
+ record,
+ animated_overlay: None,
+ pseudo_element_styles: record.pseudo_element_styles().bits(),
+ counter_style_environment_identity: record.rare().counter_style_environment_identity,
+ dependency_flags: record.view_dependency_flags(),
+ },
+ }
+ }
}
-/// What an element's columns held before an engine derivation put its record there, which
-/// reverting the derivation puts back. The swap eligibility is the element's, as the host
-/// published it, and not its record's. A composition detached for the derivation is not held
-/// here: `reattach_composition` puts it back.
+/// The longhands of a view's base record, read from its group values.
#[derive(Clone, Copy)]
-pub(super) struct ReplacedColumns {
- inputs: Option<PublishedComputedInputs>,
- inherited_group_swap_eligible: bool,
+pub(crate) struct ViewLonghands<'a>(&'a super::pipeline::Record);
+
+/// The longhands two records hold the very same computed values of, being in groups the records
+/// share.
+#[derive(Clone, Copy)]
+pub(crate) struct SharedLonghands {
+ /// The groups the records share, one bit per group.
+ shared_groups: u32,
}
-const COMPUTED_VALUE_DEPENDENCY_FLAGS: u8 = (INHERITED_GROUP_SWAP_ELIGIBLE - 1)
- | HOLDS_IMAGE_VALUES
- | HIGHLIGHT_COLORS_AUTHORED
- | HIGHLIGHT_COLOR_IS_CURRENT_COLOR;
-define_id! { interned pub struct ComputedGroupID(); }
+impl SharedLonghands {
+ /// Whether both records hold the very same computed value of `property`.
+ pub(crate) fn holds(self, property: u16) -> bool {
+ let layout = crate::css::computed_values::GroupValueLayout::get();
+ let longhand = crate::css::computed_values::LonghandID::new(property);
+ let place = layout.place(longhand);
+ // NB: The inherited bits are no group's: the records' values of them compare by value.
+ layout.holds_value(longhand) && place.bit_field().is_none() && self.shared_groups & (1 << place.group()) != 0
+ }
+}
-define_id! { interned pub struct ComputedGroupSetID(); }
+impl<'a> ViewLonghands<'a> {
+ pub(super) fn of_record(record: &'a super::pipeline::Record) -> Self {
+ Self(record)
+ }
-define_id! { interned pub struct InheritedGroupSetID(); }
+ /// Reads the longhands of a record holding `value_of(property)` for each longhand, as a test does.
+ #[cfg(test)]
+ pub(crate) fn with_test_record<R>(
+ value_of: impl Fn(u16) -> RetainedStyleValueData,
+ read: impl FnOnce(ViewLonghands<'_>) -> R,
+ ) -> R {
+ let record = super::pipeline::Record::of_test_values(value_of);
+ read(ViewLonghands::of_record(&record))
+ }
-define_id! { interned pub struct CustomPropertyEnvironmentID(); }
+ /// The longhands of the style record `record` points at.
+ ///
+ /// # Safety
+ /// `record` must point at a style record that stays live for `'a`.
+ pub(crate) unsafe fn of_raw_record(record: *const std::ffi::c_void) -> Self {
+ // SAFETY: Guaranteed by the caller.
+ Self::of_record(unsafe { &*record.cast::<super::pipeline::Record>() })
+ }
-define_id! { interned pub struct ComputedFixedMetadataID(); }
+ /// Whether these are the longhands of the record of `other`.
+ pub(crate) fn same_record_as(self, other: Self) -> bool {
+ std::ptr::eq(self.0, other.0)
+ }
-define_id! { interned pub struct ComputedLonghandTableID(); }
+ /// The longhands whose computed values these and `other` hold as one, where both are the engine
+ /// records sharing any group.
+ pub(crate) fn shared_with(self, other: Self) -> Option<SharedLonghands> {
+ let shared_groups = self.0.value_groups().shared_group_mask(other.0.value_groups());
+ (shared_groups != 0).then_some(SharedLonghands { shared_groups })
+ }
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
-pub struct StyleRecordID(NonZeroU32);
+ /// Whether these are the longhands of `record`.
+ pub(super) fn are_of_record(self, record: &super::pipeline::Record) -> bool {
+ std::ptr::eq(self.0, record)
+ }
-impl InternIdentity for StyleRecordID {
- fn index(self) -> usize {
- self.raw() as usize - 1
+ pub(crate) fn is_important(self, property: u16) -> bool {
+ self.0.rare().table_flags.is_important(property)
}
-}
-impl StyleRecordID {
- #[must_use]
- pub fn raw(self) -> u32 {
- self.0.get()
+ /// Whether the computed value of `property` was inherited.
+ pub(crate) fn is_inherited(self, property: u16) -> bool {
+ self.0.rare().table_flags.is_inherited(property)
}
-}
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
-struct ComputedFixedMetadata {
- pseudo_element_styles: u64,
- dependency_flags: u8,
- counter_style_environment_identity: u64,
-}
+ /// The handle of the computed value of `property`, where it has one.
+ pub(crate) fn handle(self, property: u16) -> Option<&'a RetainedStyleValueData> {
+ {
+ Some(self.0.longhand(crate::css::computed_values::LonghandID::new(property)))
+ .filter(|value| !value.pointer().is_null())
+ }
+ }
-/// The interned form of one drive's computed longhand table. Provenance in
-/// the source-slot sidecar is per-drive and does not participate in identity.
-struct RetainedLonghandTable {
- table: HostShared<ComputedLonghandTable>,
-}
+ /// One bit per longhand: whether its value is important.
+ pub(crate) fn importance_bits(self) -> &'a [u8] {
+ self.0.rare().table_flags.importance_bits()
+ }
-impl RetainedLonghandTable {
- fn value_view(&self) -> &[SharedPayload] {
- SharedPayload::from_pointer_slice(self.table().value_pointers())
+ /// The computed value of `property`, where it has one.
+ pub(crate) fn value(self, property: u16) -> Option<&'a crate::css::style_value::StyleValueData> {
+ self.handle(property).map(RetainedStyleValueData::data)
}
- fn table(&self) -> &ComputedLonghandTable {
- // SAFETY: The handle owns one reference to a live frozen table.
- unsafe { self.table.deref() }
+ /// https://drafts.csswg.org/css-viewport/#effective-zoom
+ pub(crate) fn effective_zoom(self) -> f32 {
+ self.0.payloads.inherited_values().effective_zoom()
+ }
+
+ /// The dependency flags of the record's table, without whether it is in a `display: none`
+ /// subtree.
+ pub(crate) fn dependency_flags(self) -> u8 {
+ self.0.facts().dependency_flags()
+ }
+
+ /// The overflow keywords before the box adjustments, where they adjusted them.
+ pub(crate) fn overflow_before_adjustment(self) -> Option<[u16; 2]> {
+ self.0.rare().table_flags.overflow_before_adjustment()
+ }
+
+ /// The element's cascaded font size, where it declares one.
+ pub(crate) fn raw_cascaded_font_size(self) -> Option<&'a crate::css::style_value::StyleValueData> {
+ self.0.rare().table_flags.raw_cascaded_font_size_value()
+ }
+
+ /// The animated value of `property` that `overlay` composes over these longhands, where it
+ /// wins over the computed one.
+ pub(crate) fn overlay_value(
+ self,
+ overlay: Option<&'a crate::css::animated_overlay::AnimatedOverlay>,
+ property: u16,
+ ) -> Option<&'a RetainedStyleValueData> {
+ overlay?
+ .get(property)
+ .filter(|entry| crate::css::animated_overlay::overlay_wins(entry, self.is_important(property)))
+ .map(crate::css::animated_overlay::FfiAnimatedOverlayEntry::value_handle)
+ }
+
+ /// The value of `property` as specified: its recorded specified value where the computation did
+ /// not evaluate it, else its computed value.
+ pub(crate) fn specified_value(self, property: u16) -> Option<&'a RetainedStyleValueData> {
+ (!self.0.rare().table_flags.is_evaluated(property))
+ .then(|| self.inheritance_dependent_value(property))
+ .flatten()
+ .or_else(|| self.handle(property))
+ }
+
+ /// Whether `property` was specified as the `currentcolor` keyword itself.
+ pub(crate) fn specified_value_is_current_color(self, property: u16) -> bool {
+ self.specified_value(property)
+ .is_some_and(|value| crate::css::computed_longhand_table::is_current_color_keyword(value.data()))
+ }
+
+ /// Whether each layer of the specified `text-shadow` has the `currentcolor` keyword as its
+ /// color, or no color, in the order the computed layers have; empty for `none`.
+ pub(crate) fn text_shadow_layer_colors_are_current_color(self) -> Vec<bool> {
+ use crate::css::style_value::StyleValueData;
+ let Some(StyleValueData::ValueList { values, .. }) = self
+ .specified_value(crate::css::property_metadata::property_id::TEXT_SHADOW)
+ .map(RetainedStyleValueData::data)
+ else {
+ return Vec::new();
+ };
+ values
+ .as_slice()
+ .iter()
+ .map(|layer| match layer.optional_data() {
+ Some(StyleValueData::Shadow(shadow_payload)) => {
+ let ShadowPayload { color, .. } = &**shadow_payload;
+ color
+ .optional_data()
+ .is_none_or(crate::css::computed_longhand_table::is_current_color_keyword)
+ }
+ _ => false,
+ })
+ .collect()
+ }
+
+ /// Whether the computed `display` is a list item.
+ pub(crate) fn display_is_list_item(self) -> bool {
+ matches!(
+ self.value(crate::css::property_metadata::property_id::DISPLAY),
+ Some(crate::css::style_value::StyleValueData::Display { raw })
+ if crate::css::display::FfiDisplay::from_raw(*raw).is_list_item()
+ )
+ }
+
+ /// The `display` the element computed before its box type transformation.
+ pub(crate) fn display_before_box_type_transformation(self) -> u32 {
+ self.0.rare().value_facts.display_before_box_type_transformation()
}
-}
-/// A fork's table holds its own strong reference.
-impl Clone for RetainedLonghandTable {
- fn clone(&self) -> Self {
- if !self.table.is_null() {
- // SAFETY: The table is a live strong reference, and an interned table is frozen.
- unsafe { crate::css::computed_longhand_table::rust_computed_longhand_table_retain(self.table.as_ptr()) };
+ /// The color scheme the element's colors resolved against.
+ pub(crate) fn effective_color_scheme(self) -> i16 {
+ self.0.effective_color_scheme()
+ }
+
+ /// The value of `property` the element's styles read, as [`Self::effective_value`] answers it
+ /// with what `overlay` composes where `with_animations` asks for that, and which source it is.
+ pub(crate) fn effective_value_and_source(
+ self,
+ overlay: Option<&'a crate::css::animated_overlay::AnimatedOverlay>,
+ property: u16,
+ with_animations: bool,
+ ) -> (&'a RetainedStyleValueData, u8) {
+ use crate::css::computed_longhand_table::{
+ EFFECTIVE_LONGHAND_SOURCE_OVERLAY, EFFECTIVE_LONGHAND_SOURCE_SPECIFIED, EFFECTIVE_LONGHAND_SOURCE_TABLE,
+ };
+ if with_animations && let Some(value) = self.overlay_value(overlay, property) {
+ return (value, EFFECTIVE_LONGHAND_SOURCE_OVERLAY);
+ }
+ match self.0.rare().value_facts.value_read_in_place(property) {
+ Some(value) => (value, EFFECTIVE_LONGHAND_SOURCE_SPECIFIED),
+ None => (
+ self.0.longhand(crate::css::computed_values::LonghandID::new(property)),
+ EFFECTIVE_LONGHAND_SOURCE_TABLE,
+ ),
}
- Self { table: self.table }
}
-}
-impl Drop for RetainedLonghandTable {
- fn drop(&mut self) {
- if !self.table.is_null() {
- unsafe {
- crate::css::computed_longhand_table::rust_computed_longhand_table_release(self.table.cast_mut());
- }
+ /// What the computation settled beside the values, which the host starts an update of the
+ /// element's style from.
+ pub(crate) fn metadata(self) -> crate::css::computed_longhand_table::FfiComputedStyleMetadata {
+ crate::css::computed_longhand_table::FfiComputedStyleMetadata {
+ display_before_box_type_transformation: self.0.rare().value_facts.display_before_box_type_transformation(),
+ effective_color_scheme: self.0.effective_color_scheme(),
+ dependency_flags: self.0.facts().dependency_flags(),
+ in_display_none_subtree: self.0.facts().in_display_none_subtree(),
}
}
-}
-pub(crate) struct StyleRecordView<'a> {
- pub payloads: &'a [SharedPayload],
- pub base_payloads: &'a [SharedPayload],
- /// Always the base record's table: animation overlays store no table entries.
- pub longhand_table: Option<&'a ComputedLonghandTable>,
- pub longhand_values: &'a [SharedPayload],
- pub animated_overlay: Option<&'a crate::css::animated_overlay::AnimatedOverlay>,
- pub pseudo_element_styles: u64,
- pub counter_style_environment_identity: u64,
- pub animation_overlay_identity: u64,
- pub dependency_flags: u8,
-}
+ /// The value of `property` the element's styles read: what `overlay` composes over these
+ /// longhands where it wins, else its recorded `currentcolor`-dependent specified value where
+ /// the computation did not evaluate it, else its computed value, as
+ /// a group build reads it with the animations.
+ pub(crate) fn effective_value(
+ self,
+ overlay: Option<&'a crate::css::animated_overlay::AnimatedOverlay>,
+ property: u16,
+ ) -> &'a RetainedStyleValueData {
+ if let Some(value) = self.overlay_value(overlay, property) {
+ return value;
+ }
+ self.0.effective_value(property)
+ }
-impl StyleRecordView<'_> {
- pub(crate) fn longhand_table_for_partial_drive(&self) -> ComputedLonghandTable {
- let source = self
- .longhand_table
- .expect("a retained style record must carry a longhand table");
- ComputedLonghandTable::copied_for_partial_drive(source)
+ /// Whether the computed `animation-name` names any animation.
+ pub(crate) fn declares_css_animations(self) -> bool {
+ self.0.facts().declares_css_animations()
}
-}
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-struct StyleRecord {
- groups: ComputedGroupSetID,
- inherited_groups: InheritedGroupSetID,
- custom_properties: CustomPropertyEnvironmentID,
- fixed_metadata: ComputedFixedMetadataID,
- longhand_table: Option<ComputedLonghandTableID>,
-}
+ /// Whether the computed `transition-*` values make any longhand transitionable.
+ pub(crate) fn declares_transitions(self) -> bool {
+ self.0.facts().declares_transitions()
+ }
-impl Hash for StyleRecord {
- fn hash<H: Hasher>(&self, state: &mut H) {
- // The inherited subset is derived from the groups, so it contributes no useful entropy.
- self.groups.hash(state);
- self.custom_properties.hash(state);
- self.fixed_metadata.hash(state);
- self.longhand_table.hash(state);
+ /// The computed `display` with what `overlay` composes over it.
+ pub(crate) fn effective_display(
+ self,
+ overlay: Option<&'a crate::css::animated_overlay::AnimatedOverlay>,
+ ) -> crate::css::display::FfiDisplay {
+ self.overlay_value(overlay, crate::css::property_metadata::property_id::DISPLAY)
+ .map_or(self.0.facts().display(), crate::css::style_compute::display_of)
}
-}
-pub struct ComputedMetadataInput<'a> {
- pub pseudo_element_styles: u64,
- pub dependency_flags: u8,
- pub counter_style_environment_identity: u64,
- pub animation_overlay_identity: u64,
- pub animated_overlay: HostShared<crate::css::animated_overlay::AnimatedOverlay>,
- pub animation_overlay_payloads: &'a [SharedPayload],
- /// The drive's frozen computed longhand table, or null when the publisher
- /// carries none. Its values are interned as the record's longhand-table
- /// relation. The style-sheet-context sidecar stays on the drive table:
- /// its cascade source slots are only meaningful against the drive's own
- /// cascade, so folding them into interned identity would split records
- /// across otherwise identical recomputes.
- pub longhand_table: HostShared<ComputedLonghandTable>,
+ /// The computed `writing-mode` with what `overlay` composes over it.
+ pub(crate) fn effective_writing_mode(
+ self,
+ overlay: Option<&'a crate::css::animated_overlay::AnimatedOverlay>,
+ ) -> u8 {
+ self.overlay_value(overlay, crate::css::property_metadata::property_id::WRITING_MODE)
+ .map_or(
+ self.0.payloads.inherited_bits().writing_mode(),
+ crate::css::style_compute::writing_mode_of,
+ )
+ }
+
+ /// The animated values of the properties that inherit which a parent whose animations compose
+ /// `overlay` over these longhands hands down.
+ pub(crate) fn inherited_overrides(
+ self,
+ overlay: Option<&'a crate::css::animated_overlay::AnimatedOverlay>,
+ ) -> impl Iterator<Item = (u16, RetainedStyleValueData)> + 'a {
+ overlay
+ .map_or(&[][..], crate::css::animated_overlay::AnimatedOverlay::entries)
+ .iter()
+ .filter(move |entry| {
+ crate::css::property_metadata::property_is_inherited(entry.property)
+ && crate::css::animated_overlay::overlay_wins(entry, self.is_important(entry.property))
+ })
+ .map(|entry| (entry.property, entry.clone_value()))
+ }
+
+ /// The recorded specified values of the longhands whose computed values depend on what the
+ /// element inherits.
+ pub(crate) fn inheritance_dependent_values(self) -> impl Iterator<Item = (u16, &'a RetainedStyleValueData)> {
+ self.0.inheritance_dependent_values()
+ }
+
+ /// The recorded specified value of `property`, where its computed value depends on what the
+ /// element inherits.
+ pub(crate) fn inheritance_dependent_value(self, property: u16) -> Option<&'a RetainedStyleValueData> {
+ self.inheritance_dependent_values()
+ .find(|(held, _)| *held == property)
+ .map(|(_, value)| value)
+ }
}
+impl<'a> StyleRecordView<'a> {
+ /// The base record's longhands.
+ pub(crate) fn longhands(&self) -> ViewLonghands<'a> {
+ ViewLonghands::of_record(self.record)
+ }
+
+ /// The base record, held, for reading its longhands beyond the view.
+ pub(super) fn retained_record(&self) -> std::sync::Arc<super::pipeline::Record> {
+ self.record.clone()
+ }
+}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct FinalStyleRecordID(u64);
@@ -230,21 +400,33 @@ impl FinalStyleRecordID {
/// No record: what a node holds before its first publication.
pub(crate) const NONE: Self = Self(0);
const ANIMATION_OVERLAY_TAG: u64 = 1 << 63;
- const MAX_BASE_GENERATION: u32 = (1 << 31) - 1;
-
- fn base(style_record: StyleRecordID, generation: u32) -> Self {
- assert!(
- generation <= Self::MAX_BASE_GENERATION,
- "base style-record generation space exhausted"
- );
- Self((u64::from(generation) << 32) | u64::from(style_record.raw()))
- }
+ /// NB: Below the 53 bits a double holds, for script to read an installed record's identity
+ /// exactly through internals.
+ const INSTALLED_TAG: u64 = 1 << 52;
fn animation_overlay(generation: u64) -> Self {
assert!(generation != 0 && generation < Self::ANIMATION_OVERLAY_TAG);
Self(Self::ANIMATION_OVERLAY_TAG | generation)
}
+ /// The identity of a record the engine installed.
+ pub(crate) fn installed(record: InstalledRecordID) -> Self {
+ const _: () = assert!(InstalledRecordID::MAX_GENERATION < 1 << 20);
+ Self(Self::INSTALLED_TAG | (u64::from(record.generation()) << 32) | (u64::from(record.slot()) + 1))
+ }
+
+ /// The record the engine installed that this identity names, if it names one.
+ pub(crate) fn installed_record(self) -> Option<InstalledRecordID> {
+ if self.0 & (Self::ANIMATION_OVERLAY_TAG | Self::INSTALLED_TAG) != Self::INSTALLED_TAG {
+ return None;
+ }
+ let slot = (self.0 as u32).checked_sub(1)?;
+ Some(InstalledRecordID::from_parts(
+ slot,
+ ((self.0 & !Self::INSTALLED_TAG) >> 32) as u32,
+ ))
+ }
+
#[must_use]
pub fn raw(self) -> u64 {
self.0
@@ -260,64 +442,6 @@ impl FinalStyleRecordID {
pub(crate) fn is_animation_overlay(self) -> bool {
self.0 & Self::ANIMATION_OVERLAY_TAG != 0
}
-
- fn base_record(self) -> Option<StyleRecordID> {
- if self.0 & Self::ANIMATION_OVERLAY_TAG != 0 {
- return None;
- }
- if self.0 as u32 == 0 {
- return None;
- }
- Some(StyleRecordID(NonZeroU32::new(self.0 as u32)?))
- }
-
- fn base_generation(self) -> u32 {
- (self.0 >> 32) as u32
- }
-}
-
-/// The composition of an element or pseudo-element, which `ComputedGroupSets::detach_composition`
-/// took off the record its winners decided so that a record derived beneath it can take that
-/// record's place. It stays
-/// pinned until it is reattached or released, each of which consumes it. Dropping it any other way
-/// would leave the pin behind, which debug builds catch, but for the copy a fork of the render
-/// state holds, which goes with the fork's group sets where the fork does not consume it.
-#[derive(Debug)]
-#[must_use]
-pub(crate) struct DetachedComposition {
- record: FinalStyleRecordID,
- /// The record the composition is laid over.
- pub(crate) base: FinalStyleRecordID,
- /// Whether this is a fork's copy, whose pin is the fork's group sets'.
- forked: bool,
-}
-
-impl Clone for DetachedComposition {
- fn clone(&self) -> Self {
- Self {
- record: self.record,
- base: self.base,
- forked: true,
- }
- }
-}
-
-impl DetachedComposition {
- /// The pinned record, with the obligation to unpin it handed to the caller.
- fn into_pinned_record(self) -> FinalStyleRecordID {
- let record = self.record;
- std::mem::forget(self);
- record
- }
-}
-
-impl Drop for DetachedComposition {
- fn drop(&mut self) {
- debug_assert!(
- self.forked || std::thread::panicking(),
- "a detached composition was dropped without being reattached or released"
- );
- }
}
/// A reader's hold on the payloads of every style record published so far: while one is held, the
@@ -368,48 +492,40 @@ impl ReleasedAnimationOverlayRecords {
}
}
+#[derive(Clone)]
struct AnimationOverlayRecord {
// NB: No sampled value enters a permanent interning table. The current assignment owns one
// reference, while detached layout and stabilization baselines can pin an old generation.
- base_style_record: StyleRecordID,
+ /// The installed record the overlay composes over, which it keeps from being freed while it
+ /// lives.
+ base: InstalledRecordID,
source_identity: u64,
- final_style_record: FinalStyleRecordID,
- /// NB: Shared with a copy of the record, as its address is handed out.
- animated_overlay: std::sync::Arc<crate::css::animated_overlay::AnimatedOverlay>,
- /// NB: Shared with a fork of the render state, whose boxes name this array as the host's do.
- payloads: std::sync::Arc<[SharedPayload]>,
- /// The base's flags, with an `<image>` a layout node loads, which a sampled value can hold
- /// where the base does not, and with the display:none subtree a sampled display puts the
- /// record in.
- dependency_flags: u8,
+ /// The record of the style the animations sample over the base: its groups are the base's but for those the
+ /// animated values changed, and it reads the base's longhands beneath them and holds the animated values.
+ /// NB: Shared with a fork of the render state, whose boxes name its groups as the host's do.
+ /// The host holds it for the element or pseudo-element assigned the record.
+ record: std::sync::Arc<super::pipeline::Record>,
pin_count: u64,
is_assigned: bool,
}
-/// A fork's overlay record holds its own reference to each of its payloads.
-impl Clone for AnimationOverlayRecord {
- fn clone(&self) -> Self {
- for (index, payload) in self.payloads.iter().enumerate() {
- retain_group_payload(index, payload.as_ptr());
- }
- Self {
- base_style_record: self.base_style_record,
- source_identity: self.source_identity,
- final_style_record: self.final_style_record,
- animated_overlay: self.animated_overlay.clone(),
- payloads: self.payloads.clone(),
- dependency_flags: self.dependency_flags,
- pin_count: self.pin_count,
- is_assigned: self.is_assigned,
- }
+impl AnimationOverlayRecord {
+ /// What the animations sampled over the base.
+ fn sample(&self) -> &super::pipeline::Sample {
+ self.record
+ .sample_of_animations()
+ .expect("an animation-overlay record is a sample")
}
-}
-impl Drop for AnimationOverlayRecord {
- fn drop(&mut self) {
- for (index, &payload) in self.payloads.iter().enumerate() {
- release_group_payload(index, payload.as_ptr());
- }
+ /// The record's identity.
+ fn final_style_record(&self) -> FinalStyleRecordID {
+ self.sample().identity
+ }
+
+ /// Whether something beside the slot holds the record: the host for the element it applied the record to, a box
+ /// of a fork of the render state, or a fork's copy of the sets.
+ fn is_held_elsewhere(&self) -> bool {
+ std::sync::Arc::strong_count(&self.record) > 1
}
}
@@ -426,6 +542,20 @@ mod animation_overlay_slots {
}
impl AnimationOverlaySlots {
+ /// The records of the sampled styles the overlays hold, retired ones included.
+ pub(super) fn records(&self) -> impl Iterator<Item = &std::sync::Arc<super::super::pipeline::Record>> {
+ self.slots
+ .iter()
+ .flatten()
+ .chain(self.retired.iter())
+ .map(|overlay| &overlay.record)
+ }
+
+ pub(super) fn heap_size(&self) -> usize {
+ use crate::heap_size::vec_bytes;
+ vec_bytes(&self.slots) + vec_bytes(&self.free) + vec_bytes(&self.retired)
+ }
+
pub(super) fn get(&self, slot: u32) -> Option<&AnimationOverlayRecord> {
self.slots[slot as usize].as_ref()
}
@@ -467,7 +597,7 @@ mod animation_overlay_slots {
}
fn retire_record(&mut self, record: AnimationOverlayRecord) -> FinalStyleRecordID {
- let final_style_record = record.final_style_record;
+ let final_style_record = record.final_style_record();
self.retired.push(record);
final_style_record
}
@@ -483,345 +613,62 @@ mod animation_overlay_slots {
}
}
-/// What a caller of `publish` still owns of the components being interned, and, on the way back,
-/// what interning took over from it.
-///
-/// A build hands the catalog the reference it holds instead of making the catalog retain a second
-/// one that the build then releases: build +1, intern +1, release -1 is a net +1 either way, but
-/// only one of the two touches a reference count per published payload.
-#[derive(Clone, Copy, Default)]
-pub struct PendingRecordOwnership {
- /// One bit per group whose payload reference moves into the catalog when it is published.
- pub groups: u32,
- /// Whether the caller holds the reference behind the record's longhand table.
- pub table: bool,
-}
-
-/// The identities a run's catalogs have minted, counted so that a determinism gate can compare
-/// the sharing partition itself instead of the publication that happened to intern it first.
-#[derive(Clone, Copy, Default)]
-pub(super) struct IdentityMints {
- pub groups: u64,
- pub group_sets: u64,
- pub inherited_group_sets: u64,
- pub style_records: u64,
-}
-
-#[derive(Clone)]
-
-struct ComputedGroup {
- index: usize,
- payload: SharedPayload,
- /// The payload's content hash, the key it is interned under. Kept with the group so a
- /// retirement can find its index entry again without hashing the payload a second time.
- content_hash: u64,
-}
-
-#[derive(Clone)]
-
-struct ComputedGroupSet {
- identity_hash: u64,
- /// NB: Shared with a fork of the render state, whose boxes name this array as the host's do.
- payloads: std::sync::Arc<[SharedPayload]>,
- groups: Box<[ComputedGroupID]>,
- canonical_longhand_table: Option<ComputedLonghandTableID>,
-}
-
-#[derive(Clone, Copy)]
-struct PublishedComputedInputs {
- groups: ComputedGroupSetID,
- inherited_groups: InheritedGroupSetID,
- custom_properties: CustomPropertyEnvironmentID,
- fixed_metadata: ComputedFixedMetadataID,
- style_record: StyleRecordID,
- animation_overlay_slot: Option<u32>,
-}
-
#[derive(Clone, Copy)]
struct PseudoComputedRow {
kind: u8,
- flags: u8,
- assignment: Option<PublishedComputedInputs>,
- cascade_versions: [u64; 3],
- cascade_states: [CascadeStateID; 3],
+ published: bool,
+ /// The installed record the pseudo-element is assigned.
+ installed: Option<InstalledRecordID>,
+ /// The slot of the animation overlay composed over `installed`.
+ installed_overlay_slot: Option<u32>,
}
+/// The slot of the animation overlay composed over each element's record, by element.
#[derive(Clone, Default)]
-struct PublishedComputedColumns {
- groups: Vec<u32>,
- inherited_groups: Vec<u32>,
- custom_properties: Vec<u32>,
- fixed_metadata: Vec<u32>,
- animation_overlay_slots: Vec<u32>,
- cascade_versions: Vec<u64>,
- cascade_states: Vec<u32>,
- flags: Vec<u8>,
- /// The element facts the style computation's adjustments read; see
- /// `bridge::element_adjustment_fact`.
- adjustment_facts: Vec<u32>,
- /// The element facts a layout row built for the element records; see
- /// `bridge::element_construction_fact`.
- construction_facts: Vec<u32>,
- /// The principal box the element asks for.
- box_kinds: Vec<ElementBoxKind>,
- /// One plus the element-backed pseudo-element kind the element stands for, or zero.
- associated_pseudo_kinds: Vec<u8>,
- /// The synthetic pseudo-elements the node's last published match answer has rules for, one
- /// bit per kind; held while `HAS_PSEUDO_STYLE_MASK` is set.
- pseudo_style_masks: Vec<u64>,
-}
-
-impl PublishedComputedColumns {
- const ASSIGNED: u8 = 1;
- const INHERITED_GROUP_SWAP_ELIGIBLE: u8 = 1 << 1;
- const HAS_CASCADE_STATE: u8 = 1 << 2;
- /// The node's last published match answer declared past its winners.
- const INCOMPLETE_ANSWER: u8 = 1 << 3;
- /// `pseudo_style_masks` holds the node's mask.
- const HAS_PSEUDO_STYLE_MASK: u8 = 1 << 4;
- /// What the node's last published match answer said, which outlives any record.
- const ANSWER_FLAGS: u8 = Self::INCOMPLETE_ANSWER | Self::HAS_PSEUDO_STYLE_MASK;
-
- fn ensure(&mut self, index: usize) {
- if self.flags.len() > index {
- return;
- }
- let len = index
- .checked_add(1)
- .expect("computed publication column space exhausted");
- self.groups.resize(len, 0);
- self.inherited_groups.resize(len, 0);
- self.custom_properties.resize(len, 0);
- self.fixed_metadata.resize(len, 0);
- self.animation_overlay_slots.resize(len, 0);
- self.cascade_versions.resize(len, 0);
- self.cascade_states.resize(len, 0);
- self.flags.resize(len, 0);
- self.adjustment_facts.resize(len, 0);
- self.construction_facts.resize(len, 0);
- self.box_kinds.resize(len, ElementBoxKind::default());
- self.associated_pseudo_kinds.resize(len, 0);
- self.pseudo_style_masks.resize(len, 0);
- }
-
- fn is_assigned(&self, index: usize) -> bool {
- self.flags.get(index).is_some_and(|flags| flags & Self::ASSIGNED != 0)
- }
-
- fn groups(&self, index: usize) -> Option<ComputedGroupSetID> {
- self.is_assigned(index).then(|| ComputedGroupSetID(self.groups[index]))
- }
-
- fn inherited_groups(&self, index: usize) -> Option<InheritedGroupSetID> {
- self.is_assigned(index)
- .then(|| InheritedGroupSetID(self.inherited_groups[index]))
- }
-
- fn custom_properties(&self, index: usize) -> Option<CustomPropertyEnvironmentID> {
- self.is_assigned(index)
- .then(|| CustomPropertyEnvironmentID(self.custom_properties[index]))
- }
-
- fn fixed_metadata(&self, index: usize) -> Option<ComputedFixedMetadataID> {
- self.is_assigned(index)
- .then(|| ComputedFixedMetadataID(self.fixed_metadata[index]))
- }
+struct AnimationOverlayColumn(Vec<u32>);
- fn animation_overlay_slot(&self, index: usize) -> Option<u32> {
- let encoded = *self.animation_overlay_slots.get(index)?;
- encoded.checked_sub(1)
+impl AnimationOverlayColumn {
+ fn get(&self, index: usize) -> Option<u32> {
+ self.0.get(index)?.checked_sub(1)
}
- fn set_animation_overlay_slot(&mut self, index: usize, slot: Option<u32>) {
- self.animation_overlay_slots[index] = slot.map_or(0, |slot| {
+ fn set(&mut self, index: usize, slot: Option<u32>) {
+ if self.0.len() <= index {
+ self.0.resize(
+ index.checked_add(1).expect("animation overlay column space exhausted"),
+ 0,
+ );
+ }
+ self.0[index] = slot.map_or(0, |slot| {
slot.checked_add(1)
.expect("animation overlay slot identity space exhausted")
});
}
- fn inherited_group_swap_eligible(&self, index: usize) -> bool {
- self.flags
- .get(index)
- .is_some_and(|flags| flags & Self::INHERITED_GROUP_SWAP_ELIGIBLE != 0)
- }
-
- fn answer_is_incomplete(&self, index: usize) -> bool {
- self.flags
- .get(index)
- .is_some_and(|flags| flags & Self::INCOMPLETE_ANSWER != 0)
- }
-
- fn set_answer_incomplete(&mut self, index: usize, incomplete: bool) {
- self.ensure(index);
- if incomplete {
- self.flags[index] |= Self::INCOMPLETE_ANSWER;
- } else {
- self.flags[index] &= !Self::INCOMPLETE_ANSWER;
- }
- }
-
- fn cascade_state(&self, index: usize) -> Option<(u64, CascadeStateID)> {
- self.flags
- .get(index)
- .is_some_and(|flags| flags & Self::HAS_CASCADE_STATE != 0)
- .then(|| (self.cascade_versions[index], CascadeStateID(self.cascade_states[index])))
- }
-
- fn replace_cascade_state(
- &mut self,
- index: usize,
- state: Option<(u64, CascadeStateID)>,
- ) -> Option<(u64, CascadeStateID)> {
- let previous = self.cascade_state(index);
- if let Some((version, state)) = state {
- self.cascade_versions[index] = version;
- self.cascade_states[index] = state.0;
- self.flags[index] |= Self::HAS_CASCADE_STATE;
- } else if let Some(flags) = self.flags.get_mut(index) {
- *flags &= !Self::HAS_CASCADE_STATE;
- }
- previous
- }
-
- fn publish(&mut self, index: usize, inputs: PublishedComputedInputs, inherited_group_swap_eligible: bool) {
- self.ensure(index);
- self.groups[index] = inputs.groups.0;
- self.inherited_groups[index] = inputs.inherited_groups.0;
- self.custom_properties[index] = inputs.custom_properties.0;
- self.fixed_metadata[index] = inputs.fixed_metadata.0;
- self.set_animation_overlay_slot(index, inputs.animation_overlay_slot);
- self.flags[index] = (self.flags[index]
- & (Self::HAS_CASCADE_STATE | Self::INCOMPLETE_ANSWER | Self::HAS_PSEUDO_STYLE_MASK))
- | Self::ASSIGNED
- | if inherited_group_swap_eligible {
- Self::INHERITED_GROUP_SWAP_ELIGIBLE
- } else {
- 0
- };
- }
-
- /// Drop the record at `index`, keeping what the host and the node's match answer published
- /// for it: its element facts, the pseudo-element it backs and the answer's flags.
- fn unassign(&mut self, index: usize) -> Option<u32> {
- let overlay = self.animation_overlay_slot(index);
- if let Some(flags) = self.flags.get_mut(index) {
- *flags &= Self::ANSWER_FLAGS;
- self.animation_overlay_slots[index] = 0;
- }
- overlay
- }
-
- fn remove(&mut self, index: usize) -> Option<u32> {
- let overlay = self.unassign(index);
- if let Some(flags) = self.flags.get_mut(index) {
- *flags = 0;
- // The index may be handed to a shadow root or the document next, which publish no facts
- // of their own, so a retired element's facts must not stay behind for them.
- self.adjustment_facts[index] = 0;
- self.construction_facts[index] = 0;
- self.box_kinds[index] = ElementBoxKind::default();
- self.associated_pseudo_kinds[index] = 0;
+ /// Takes the slot at `index`, leaving none.
+ fn take(&mut self, index: usize) -> Option<u32> {
+ let slot = self.get(index);
+ if slot.is_some() {
+ self.0[index] = 0;
}
- overlay
- }
-}
-
-struct ComputedReachability {
- groups: Vec<bool>,
- sets: Vec<bool>,
- inherited_sets: Vec<bool>,
- custom_property_environments: Vec<bool>,
- fixed_metadata: Vec<bool>,
- longhand_tables: Vec<bool>,
- style_records: Vec<bool>,
-}
-
-impl ComputedReachability {
- fn mark<Identity: InternIdentity>(marks: &mut [bool], identity: Identity) {
- marks[identity.index()] = true;
+ slot
}
}
-#[derive(Clone, Copy)]
-pub(super) struct ComputedGroupRetention {
- pub retained: usize,
- pub reachable: usize,
-}
-
impl PseudoComputedRow {
- const PUBLISHED: u8 = 1;
- const CURRENT_CASCADE: usize = 0;
- const RETAINED_CASCADE: usize = 1;
- const PENDING_CASCADE: usize = 2;
-
fn new(kind: u8) -> Self {
Self {
kind,
- flags: 0,
- assignment: None,
- cascade_versions: [0; 3],
- cascade_states: [CascadeStateID(0); 3],
- }
- }
-
- fn is_published(&self) -> bool {
- self.flags & Self::PUBLISHED != 0
- }
-
- fn set_published(&mut self, published: bool) {
- self.flags = (self.flags & !Self::PUBLISHED) | if published { Self::PUBLISHED } else { 0 };
- }
-
- fn cascade_state(&self, index: usize) -> Option<(u64, CascadeStateID)> {
- (self.flags & (1 << (index + 1)) != 0).then_some((self.cascade_versions[index], self.cascade_states[index]))
- }
-
- fn replace_cascade_state(
- &mut self,
- index: usize,
- state: Option<(u64, CascadeStateID)>,
- ) -> Option<(u64, CascadeStateID)> {
- let previous = self.cascade_state(index);
- if let Some((version, state)) = state {
- self.cascade_versions[index] = version;
- self.cascade_states[index] = state;
- self.flags |= 1 << (index + 1);
- } else {
- self.flags &= !(1 << (index + 1));
+ published: false,
+ installed: None,
+ installed_overlay_slot: None,
}
- previous
}
fn is_empty(&self) -> bool {
- self.flags == 0 && self.assignment.is_none()
+ !self.published && self.installed.is_none()
}
}
-
-pub struct ComputedGroupPublication {
- pub previous_style_record_identity: Option<FinalStyleRecordID>,
- pub style_record_identity: FinalStyleRecordID,
- pub new_groups: usize,
- pub canonical_output_groups_reused: usize,
- pub new_group_set: bool,
- pub new_inherited_group_set: bool,
- pub new_custom_property_environment: bool,
- pub new_computed_fixed_metadata: bool,
- pub new_style_record: bool,
- pub node_handle_changed: bool,
- pub inherited_node_handle_changed: bool,
- pub custom_property_environment_node_handle_changed: bool,
- pub computed_fixed_metadata_node_handle_changed: bool,
- pub style_record_node_handle_changed: bool,
- pub animation_overlay_slot_allocated: bool,
- pub animation_overlay_slot_released: bool,
- pub animation_overlay_record_updated: bool,
- pub live_animation_overlay_records: usize,
- pub is_pseudo: bool,
- /// Which of the references the caller handed over the catalog took: the caller releases the
- /// rest itself.
- pub transferred: PendingRecordOwnership,
-}
-
#[derive(Clone, Copy)]
struct AnimationOverlayPublication {
slot: Option<u32>,
@@ -865,89 +712,167 @@ impl ComputedStyleTarget {
pub fn is_pseudo(self) -> bool {
self.pseudo_kind != u8::MAX
}
+}
- #[must_use]
- #[cfg(test)]
- pub(super) fn pseudo_element_target(self) -> Option<PseudoElementTarget> {
- self.is_pseudo()
- .then(|| PseudoElementTarget::new(PseudoElementKind(u16::from(self.pseudo_kind))))
+/// The record an element or a pseudo-element is assigned beneath the composition of its animations:
+/// the installed record, and the record the engine computed that it installs. The installed record's
+/// identity is the element's FinalStyleRecordID where no animation overlay is composed over it.
+#[derive(Clone)]
+pub(crate) struct InstalledStyle {
+ pub(super) id: InstalledRecordID,
+ pub(super) record: std::sync::Arc<super::pipeline::Record>,
+}
+
+impl InstalledStyle {
+ /// The final style record the installed record is, beneath any composition.
+ pub(crate) fn final_style_record(&self) -> FinalStyleRecordID {
+ FinalStyleRecordID::installed(self.id)
+ }
+}
+
+impl PartialEq for InstalledStyle {
+ fn eq(&self, other: &Self) -> bool {
+ self.id == other.id && std::sync::Arc::ptr_eq(&self.record, &other.record)
+ }
+}
+
+/// A pseudo-element's [`InstalledStyle`], with its kind.
+#[derive(Clone, PartialEq)]
+pub(crate) struct InstalledPseudoStyle {
+ pub(super) kind: u8,
+ pub(super) style: InstalledStyle,
+}
+
+/// How many elements a chunk of the installed style columns holds.
+const INSTALLED_STYLE_CHUNK: usize = 64;
+
+/// The styles installed for the elements and their pseudo-elements, by element slot, as one
+/// installation left them: a published generation of the sets' columns, which later
+/// installations do not change. Publishing one costs a reference count however many elements
+/// there are, and a reader holding it keeps the records it names alive.
+#[derive(Clone, Default)]
+pub(crate) struct InstalledStyles {
+ elements: crate::cow_column::ColumnSnapshot<Option<InstalledStyle>, INSTALLED_STYLE_CHUNK>,
+ pseudo_elements:
+ crate::cow_column::ColumnSnapshot<Option<std::sync::Arc<Box<[InstalledPseudoStyle]>>>, INSTALLED_STYLE_CHUNK>,
+}
+
+impl InstalledStyles {
+ /// The style installed for the element `node`, if any.
+ pub(crate) fn element(&self, node: StyleNodeID) -> Option<&InstalledStyle> {
+ self.elements.get(node.element_index()? as usize)?.as_ref()
+ }
+
+ /// The styles installed for the pseudo-elements of `node`, by kind, in no particular order.
+ pub(crate) fn pseudo_elements(&self, node: StyleNodeID) -> &[InstalledPseudoStyle] {
+ node.element_index()
+ .and_then(|index| {
+ self.pseudo_elements
+ .get(index as usize)?
+ .as_deref()
+ .map(|styles| &**styles)
+ })
+ .unwrap_or(&[])
+ }
+
+ /// The style installed for the pseudo-element of `kind` of `node`, if any.
+ pub(crate) fn pseudo_element(&self, node: StyleNodeID, kind: u8) -> Option<&InstalledStyle> {
+ self.pseudo_elements(node)
+ .iter()
+ .find(|pseudo| pseudo.kind == kind)
+ .map(|pseudo| &pseudo.style)
}
}
+/// A copy of the sets holds its own reference to every record and overlay payload, and shares the
+/// leases on its records.
+#[derive(Clone)]
pub struct ComputedGroupSets {
- /// How many identities each catalog has minted. A mint is a content the run had not seen
- /// before; which publication performs it is an execution-order decision, so the reuse
- /// counters credit an order while these count the partition.
- identity_mints: IdentityMints,
- groups: InternTable<ComputedGroupID, ComputedGroup>,
- /// The same groups indexed by payload *content*, so that two equal payloads built by
- /// different records are one identity. `groups` stays indexed by payload address, which is
- /// the fast path: a payload that is already interned keeps its identity without hashing its
- /// content again.
- groups_by_content: InternTable<ComputedGroupID, ()>,
- sets: InternTable<ComputedGroupSetID, ComputedGroupSet>,
- inherited_sets: InternTable<InheritedGroupSetID, Box<[ComputedGroupID]>>,
- custom_property_environments: InternTable<CustomPropertyEnvironmentID, u64>,
- computed_fixed_metadata: InternTable<ComputedFixedMetadataID, ComputedFixedMetadata>,
- computed_longhand_tables: InternTable<ComputedLonghandTableID, RetainedLonghandTable>,
- style_records: InternTable<StyleRecordID, StyleRecord>,
- style_record_liveness: BitColumn,
- style_record_generations: Vec<u32>,
- style_record_column: Vec<Option<StyleRecordID>>,
- base_style_record_pins: HashMap<StyleRecordID, u64>,
- /// Long-lived immutable readers pin only the base records they actually read. Expired readers leave weak entries
+ /// The records the engine installed.
+ installed: InstalledRecords,
+ /// The installed record each element is assigned, by element index.
+ installed_column: crate::cow_column::CowColumn<Option<InstalledStyle>, INSTALLED_STYLE_CHUNK>,
+ /// The installed records of each element's pseudo-elements, as the pseudo rows held them when
+ /// the column was last published, by element index. A row is one thin pointer: most elements
+ /// have none.
+ installed_pseudo_column:
+ crate::cow_column::CowColumn<Option<std::sync::Arc<Box<[InstalledPseudoStyle]>>>, INSTALLED_STYLE_CHUNK>,
+ /// The elements whose pseudo rows moved since the pseudo column was last published.
+ pseudo_rows_moved: Vec<StyleNodeID>,
+ /// Long-lived immutable readers pin only the records they actually read. Expired readers leave weak entries
/// that the next lease removes, so they neither block reclamation nor need to call back into the owner.
selected_style_record_leases: std::sync::Arc<std::sync::Mutex<Vec<std::sync::Weak<[u64]>>>>,
- columns: PublishedComputedColumns,
- // Recyclable animation overlays are deliberately separate from the permanent base records
- // above. Dense element assignments and sparse pseudo assignments pin at most one slot each.
+ // Recyclable animation overlays are deliberately separate from the installed records above.
+ // Dense element assignments and sparse pseudo assignments pin at most one slot each.
+ animation_overlay_column: AnimationOverlayColumn,
animation_overlay_slots: animation_overlay_slots::AnimationOverlaySlots,
animation_overlay_slots_by_record: HashMap<FinalStyleRecordID, u32>,
+ /// The slots of overlay records nothing assigns or pins but something else holds, such as the host for the element
+ /// it last applied the record to, which go once nothing does.
+ held_animation_overlay_slots: Vec<u32>,
released_animation_overlay_records: ReleasedAnimationOverlayRecords,
/// How many leases are held, shared with every copy of the sets: a copy holds no lease of its own.
+ // NB: Either copy may be the host's, whose published frames hold their leases here.
leases: std::sync::Arc<std::sync::atomic::AtomicUsize>,
live_animation_overlay_assignments: usize,
next_animation_overlay_generation: u64,
- pending_cascade_states: HashMap<StyleNodeID, (u64, CascadeStateID)>,
pseudo_rows_by_node: crate::fork::ForkShared<HashMap<StyleNodeID, Box<[PseudoComputedRow]>>>,
- style_records_interned_since_reclamation: usize,
+ /// How many installed records were freed since what they named was last reclaimed.
+ records_freed_since_reclamation: usize,
next_reclamation_after: usize,
}
impl Default for ComputedGroupSets {
fn default() -> Self {
Self {
- identity_mints: IdentityMints::default(),
- groups: InternTable::default(),
- groups_by_content: InternTable::default(),
- sets: InternTable::default(),
- inherited_sets: InternTable::default(),
- custom_property_environments: InternTable::default(),
- computed_fixed_metadata: InternTable::default(),
- computed_longhand_tables: InternTable::default(),
- style_records: InternTable::default(),
- style_record_liveness: BitColumn::default(),
- style_record_generations: Vec::new(),
- style_record_column: Vec::new(),
- base_style_record_pins: HashMap::default(),
+ installed: InstalledRecords::default(),
+ installed_column: Default::default(),
+ installed_pseudo_column: Default::default(),
+ pseudo_rows_moved: Vec::new(),
selected_style_record_leases: std::sync::Arc::default(),
- columns: PublishedComputedColumns::default(),
+ animation_overlay_column: AnimationOverlayColumn::default(),
animation_overlay_slots: animation_overlay_slots::AnimationOverlaySlots::default(),
animation_overlay_slots_by_record: HashMap::default(),
+ held_animation_overlay_slots: Vec::new(),
released_animation_overlay_records: ReleasedAnimationOverlayRecords::default(),
leases: std::sync::Arc::default(),
live_animation_overlay_assignments: 0,
next_animation_overlay_generation: 0,
- pending_cascade_states: HashMap::default(),
pseudo_rows_by_node: Default::default(),
-
- style_records_interned_since_reclamation: 0,
+ records_freed_since_reclamation: 0,
next_reclamation_after: 1024,
}
}
}
impl ComputedGroupSets {
+ /// Counts the installed records and the columns naming them toward the installed records,
+ /// and the records by owner.
+ pub(super) fn report_memory(&self, report: &mut super::memory_report::MemoryReport) {
+ use crate::heap_size::{map_bytes, vec_bytes};
+ self.installed.report_memory(report);
+ for record in self.animation_overlay_slots.records() {
+ super::pipeline::Record::report_memory(record, report);
+ }
+ let pseudo_rows = &*self.pseudo_rows_by_node;
+ report.add(
+ super::memory_report::MemoryOwner::Installed,
+ self.installed_column.len() * size_of::<Option<InstalledStyle>>()
+ + self.installed_pseudo_column.len() * size_of::<Option<std::sync::Arc<Box<[InstalledPseudoStyle]>>>>()
+ + vec_bytes(&self.pseudo_rows_moved)
+ + vec_bytes(&self.animation_overlay_column.0)
+ + self.animation_overlay_slots.heap_size()
+ + map_bytes(&self.animation_overlay_slots_by_record)
+ + vec_bytes(&self.held_animation_overlay_slots)
+ + vec_bytes(&self.released_animation_overlay_records.records)
+ + map_bytes(pseudo_rows)
+ + pseudo_rows
+ .values()
+ .map(|rows| size_of_val::<[PseudoComputedRow]>(rows))
+ .sum::<usize>(),
+ );
+ }
+
pub(crate) fn lease_style_records(&self) -> StyleRecordLease {
self.leases.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
StyleRecordLease {
@@ -955,41 +880,19 @@ impl ComputedGroupSets {
}
}
- /// Copies only the numeric selection values needed by an immutable hover, without retaining whole records.
- pub(crate) fn hover_user_select_values(&self) -> Vec<Option<u8>> {
- let values: Vec<_> = self
- .style_records
- .iter()
- .enumerate()
- .map(|(index, record)| {
- if !self.style_record_liveness.contains(index) {
- return None;
- }
- let payloads = &self.sets[record.groups].payloads;
- Some(
- crate::css::computed_value_views::ComputedValuesView::new(
- crate::css::host_shared::SharedPayload::as_pointer_slice(payloads),
- )
- .misc_reset()
- .user_select,
- )
- })
- .collect();
- self.style_record_column
- .iter()
- .map(|record| record.and_then(|record| values[record.index()]))
- .collect()
+ /// A version of the records the elements are assigned, which every write of them moves.
+ pub(crate) fn installed_column_version(&self) -> u64 {
+ self.installed_column.version()
}
/// Leases `records` to an immutable hover frame, or answers none where one of them is an animation overlay record,
/// whose payloads such a lease does not keep.
pub(crate) fn lease_selected_style_records(&self, records: Vec<u64>) -> Option<std::sync::Arc<[u64]>> {
for &raw_record in &records {
- let record = FinalStyleRecordID(raw_record);
// NB: A row can name an overlay record no element is assigned anymore, such as the row of a removed
// element, which pins its record until the rebuild of its parent frees it.
- let base = record.base_record()?;
- assert!(self.style_record_generation_is_live(base, record.base_generation()));
+ let installed = FinalStyleRecordID(raw_record).installed_record()?;
+ assert!(self.installed.get(installed).is_some());
}
let records: std::sync::Arc<[u64]> = records.into();
let mut leases = self
@@ -1026,10 +929,6 @@ impl ComputedGroupSets {
std::mem::take(&mut self.released_animation_overlay_records)
}
- fn group_identities(&self, set: ComputedGroupSetID) -> impl Iterator<Item = ComputedGroupID> {
- self.sets[set].groups.iter().copied()
- }
-
fn pseudo_rows(&self, node: StyleNodeID) -> &[PseudoComputedRow] {
self.pseudo_rows_by_node.get(&node).map_or(&[], Box::as_ref)
}
@@ -1039,12 +938,14 @@ impl ComputedGroupSets {
}
fn pseudo_row_mut(&mut self, node: StyleNodeID, kind: u8) -> Option<&mut PseudoComputedRow> {
+ self.pseudo_rows_moved.push(node);
self.pseudo_rows_by_node
.get_mut(&node)
.and_then(|rows| rows.iter_mut().find(|row| row.kind == kind))
}
fn ensure_pseudo_row(&mut self, node: StyleNodeID, kind: u8) -> &mut PseudoComputedRow {
+ self.pseudo_rows_moved.push(node);
let rows = self.pseudo_rows_by_node.entry(node).or_default();
let row_index = rows.iter().position(|row| row.kind == kind).unwrap_or_else(|| {
let mut extended = std::mem::take(rows).into_vec();
@@ -1058,6 +959,7 @@ impl ComputedGroupSets {
}
fn remove_empty_pseudo_row(&mut self, node: StyleNodeID, kind: u8) {
+ self.pseudo_rows_moved.push(node);
let std::collections::hash_map::Entry::Occupied(mut entry) = self.pseudo_rows_by_node.entry(node) else {
return;
};
@@ -1074,46 +976,178 @@ impl ComputedGroupSets {
}
}
+ /// The installed record `record` names, while it is live.
+ fn installed(&self, record: FinalStyleRecordID) -> Option<&InstalledRecord> {
+ self.installed.get(record.installed_record()?)
+ }
+
+ /// Take a slot for a record the engine computed, or answer the one it holds already.
+ /// `dependency_flags` says what the view of a record in a new slot depends on.
+ pub(super) fn install_record(
+ &mut self,
+ record: &std::sync::Arc<super::pipeline::Record>,
+ dependency_flags: impl FnOnce() -> u8,
+ ) -> FinalStyleRecordID {
+ FinalStyleRecordID::installed(self.installed.install(record, dependency_flags))
+ }
+
+ /// The identity `record` holds already, if it holds one.
+ pub(super) fn installed_record_named_by(
+ &self,
+ record: &std::sync::Arc<super::pipeline::Record>,
+ ) -> Option<FinalStyleRecordID> {
+ self.installed.named_by(record).map(FinalStyleRecordID::installed)
+ }
+
+ /// An installed record holding the style `record` does, which an element computing `record`
+ /// holds in its place.
+ pub(super) fn installed_record_holding_the_same_style_as(
+ &self,
+ record: &super::pipeline::Record,
+ ) -> Option<&std::sync::Arc<super::pipeline::Record>> {
+ self.installed.holding_the_same_style_as(record)
+ }
+
+ /// The record the engine computed that the installed `record` installs, where it is one.
+ pub(super) fn installed_record(
+ &self,
+ record: FinalStyleRecordID,
+ ) -> Option<&std::sync::Arc<super::pipeline::Record>> {
+ Some(self.installed.get(record.installed_record()?)?.record())
+ }
+
+ /// The record the engine computed that `record` installs or composes animations over, where it
+ /// is one.
+ pub(super) fn installed_base_record(
+ &self,
+ record: FinalStyleRecordID,
+ ) -> Option<&std::sync::Arc<super::pipeline::Record>> {
+ let installed = match record.installed_record() {
+ Some(installed) => installed,
+ None => self.overlay_base(record)?,
+ };
+ Some(self.installed.get(installed)?.record())
+ }
+
+ /// Assign `node` the installed `record` in place of what it held, which it lets go of.
+ pub(super) fn assign_installed_record(&mut self, node: StyleNodeID, record: FinalStyleRecordID) {
+ let installed = record.installed_record().expect("an installed record");
+ let index = node.element_index().expect("only elements are assigned records") as usize;
+ self.installed.hold(installed);
+ if let Some(slot) = self.animation_overlay_column.take(index) {
+ self.release_animation_overlay_assignment(slot);
+ }
+ self.installed_column.grow_to(index + 1);
+ let record = self
+ .installed
+ .get(installed)
+ .expect("an assigned record is installed")
+ .record()
+ .clone();
+ let previous = self
+ .installed_column
+ .replace(index, Some(InstalledStyle { id: installed, record }))
+ .expect("the column holds the element");
+ if let Some(previous) = previous {
+ self.installed.release(previous.id);
+ }
+ }
+
+ /// Assign `node`'s pseudo-element of `pseudo_kind` the installed `record` in place of what it
+ /// held.
+ pub(super) fn assign_installed_pseudo_record(
+ &mut self,
+ node: StyleNodeID,
+ pseudo_kind: u8,
+ record: FinalStyleRecordID,
+ ) {
+ let installed = record.installed_record().expect("an installed record");
+ self.installed.hold(installed);
+ let row = self.ensure_pseudo_row(node, pseudo_kind);
+ row.published = true;
+ let previous = row.installed.replace(installed);
+ let overlay = row.installed_overlay_slot.take();
+ if let Some(previous) = previous {
+ self.installed.release(previous);
+ }
+ if let Some(slot) = overlay {
+ self.release_animation_overlay_assignment(slot);
+ }
+ }
+
+ /// The styles installed for every element and pseudo-element now, as a generation later
+ /// installations leave as it is.
+ pub(crate) fn publish_installed_styles(&mut self) -> InstalledStyles {
+ let mut moved = std::mem::take(&mut self.pseudo_rows_moved);
+ moved.sort_unstable();
+ moved.dedup();
+ for &node in &moved {
+ let Some(index) = node.element_index().map(|index| index as usize) else {
+ continue;
+ };
+ let styles: Vec<InstalledPseudoStyle> = self
+ .pseudo_rows(node)
+ .iter()
+ .filter_map(|row| {
+ let id = row.installed?;
+ Some(InstalledPseudoStyle {
+ kind: row.kind,
+ style: InstalledStyle {
+ id,
+ record: self.installed.get(id)?.record().clone(),
+ },
+ })
+ })
+ .collect();
+ let styles = (!styles.is_empty()).then(|| std::sync::Arc::new(styles.into_boxed_slice()));
+ if styles.is_some() {
+ self.installed_pseudo_column.grow_to(index + 1);
+ }
+ let _ = self.installed_pseudo_column.set(index, styles);
+ }
+ moved.clear();
+ self.pseudo_rows_moved = moved;
+ InstalledStyles {
+ elements: self.installed_column.publish(),
+ pseudo_elements: self.installed_pseudo_column.publish(),
+ }
+ }
+
pub(super) fn assigned_style_record(&self, node: StyleNodeID) -> Option<FinalStyleRecordID> {
let index = node.element_index()? as usize;
- let style_record = *self.style_record_column.get(index)?.as_ref()?;
- Some(self.final_style_record(style_record, self.columns.animation_overlay_slot(index)))
+ let installed = self.installed_column.get(index)?.as_ref()?.id;
+ Some(self.final_style_record(installed, self.animation_overlay_column.get(index)))
}
-
pub(super) fn assigned_final_style_record(&self, target: ComputedStyleTarget) -> Option<FinalStyleRecordID> {
if !target.is_pseudo() {
return self.assigned_style_record(target.node);
}
- let assignment = self.pseudo_row(target.node, target.pseudo_kind)?.assignment?;
- Some(self.final_style_record(assignment.style_record, assignment.animation_overlay_slot))
- }
-
- /// The nodes whose element or pseudo-element style depends on viewport metrics, by its own
- /// values or by the raw custom-property environment it holds, as `environment_reads_viewport`
- /// says.
- pub(super) fn viewport_dependent_nodes(&self, environment_reads_viewport: impl Fn(u64) -> bool) -> Vec<u32> {
- let depends_on_viewport = |fixed_metadata: ComputedFixedMetadataID,
- environment: CustomPropertyEnvironmentID| {
- self.computed_fixed_metadata.get(fixed_metadata).dependency_flags & DEPENDS_ON_VIEWPORT_METRICS != 0
- || environment_reads_viewport(self.custom_property_environments[environment])
+ self.pseudo_style_record(target.node, target.pseudo_kind)
+ }
+
+ /// The nodes whose element or pseudo-element style depends on viewport metrics.
+ pub(super) fn viewport_dependent_nodes(&self) -> Vec<u32> {
+ let installed_depends_on_viewport = |installed: InstalledRecordID| {
+ self.installed
+ .get(installed)
+ .is_some_and(|installed| installed.dependency_flags() & DEPENDS_ON_VIEWPORT_METRICS != 0)
};
let mut nodes = Vec::new();
- for index in 1..self.columns.flags.len() {
+ for index in 0..self.installed_column.len() {
if self
- .columns
- .fixed_metadata(index)
- .zip(self.columns.custom_properties(index))
- .is_some_and(|(fixed_metadata, environment)| depends_on_viewport(fixed_metadata, environment))
+ .installed_column
+ .get(index)
+ .and_then(Option::as_ref)
+ .is_some_and(|installed| installed_depends_on_viewport(installed.id))
{
nodes.push(u32::try_from(index).expect("computed style node identity exceeds u32"));
}
}
for (&node, rows) in self.pseudo_rows_by_node.iter() {
- if rows.iter().any(|row| {
- row.assignment.is_some_and(|assignment| {
- depends_on_viewport(assignment.fixed_metadata, assignment.custom_properties)
- })
- }) {
+ if rows
+ .iter()
+ .any(|row| row.installed.is_some_and(installed_depends_on_viewport))
+ {
nodes.push(node.raw());
}
}
@@ -1122,982 +1156,214 @@ impl ComputedGroupSets {
nodes
}
- /// Interns one group payload. `owned` says the caller holds a reference it is handing over: a
- /// payload published here takes that reference instead of retaining a second one, and a
- /// payload that deduplicates leaves it with the caller, who releases it as before. The second
- /// element of the answer says which of the two happened.
- fn intern_group_owned(&mut self, index: usize, payload: SharedPayload, owned: bool) -> (ComputedGroupID, bool) {
- let address_hash = content_hash((index, payload.addr()));
- if let Some(identity) = self.groups.find(address_hash, |_identity, group| {
- group.index == index && group.payload == payload
- }) {
- return (identity, false);
- }
- // A payload nobody has interned yet is asked for its content, which is what decides its
- // identity: an equal payload built by another record is the same group, however the two
- // builds were ordered.
- // SAFETY: Published style-group payloads stay live while their records do.
- let payload_content_hash = unsafe { style_group_payloads_hash(index, payload.as_ptr()) };
- let groups = &self.groups;
- if let Some(identity) = self.groups_by_content.find(payload_content_hash, |identity, ()| {
- let group = &groups[identity];
- // SAFETY: Published style-group payloads stay live while their records do.
- group.index == index
- && unsafe { style_group_payloads_equal(index, group.payload.as_ptr(), payload.as_ptr()) }
- }) {
- return (identity, false);
- }
- if !owned {
- retain_group_payload(index, payload.as_ptr());
- }
- let identity = self.groups.take_free_identity().unwrap_or_else(|| {
- ComputedGroupID(u32::try_from(self.groups.len()).expect("computed group identity space exhausted"))
- });
- self.groups.insert(
- address_hash,
- identity,
- ComputedGroup {
- index,
- payload,
- content_hash: payload_content_hash,
- },
- );
- self.groups_by_content.insert_identity(payload_content_hash, identity);
- self.identity_mints.groups += 1;
-
- (identity, true)
- }
-
- fn intern_group_set(&mut self, groups: &[ComputedGroupID]) -> (ComputedGroupSetID, bool) {
- let hash = content_hash(groups);
- if let Some(identity) = self.sets.find(hash, |_identity, set| set.groups.as_ref() == groups) {
- return (identity, false);
- }
- let identity = self.sets.take_free_identity().unwrap_or_else(|| {
- ComputedGroupSetID(u32::try_from(self.sets.len()).expect("computed group-set identity space exhausted"))
- });
- let payloads = groups
- .iter()
- .map(|identity| self.groups[*identity].payload)
- .collect::<Box<[_]>>();
-
- self.identity_mints.group_sets += 1;
- self.sets.insert(
- hash,
- identity,
- ComputedGroupSet {
- identity_hash: hash,
- payloads: payloads.into(),
- groups: groups.into(),
- canonical_longhand_table: None,
- },
- );
- (identity, true)
- }
-
- fn intern_inherited_group_set(&mut self, groups: &[ComputedGroupID]) -> (InheritedGroupSetID, bool) {
- let hash = content_hash(groups);
- if let Some(identity) = self
- .inherited_sets
- .find(hash, |_identity, candidate| candidate.as_ref() == groups)
- {
- return (identity, false);
- }
- let identity = self.inherited_sets.take_free_identity().unwrap_or_else(|| {
- InheritedGroupSetID(
- u32::try_from(self.inherited_sets.len()).expect("inherited group-set identity space exhausted"),
- )
- });
- let groups: Box<[ComputedGroupID]> = groups.into();
-
- self.identity_mints.inherited_group_sets += 1;
- self.inherited_sets.insert(hash, identity, groups);
- (identity, true)
- }
-
- fn intern_style_record(&mut self, record: StyleRecord) -> (StyleRecordID, bool) {
- let hash = content_hash(record);
- if let Some(identity) = self
- .style_records
- .find(hash, |_identity, candidate| *candidate == record)
- {
- return (identity, false);
- }
- let identity = self.style_records.take_free_identity().unwrap_or_else(|| {
- let raw = u32::try_from(
- self.style_records
- .len()
- .checked_add(1)
- .expect("base style-record identity space exhausted"),
- )
- .expect("base style-record identity space exhausted");
- StyleRecordID(NonZeroU32::new(raw).expect("base style-record identities are nonzero"))
- });
- if identity.index() == self.style_record_generations.len() {
- self.style_record_generations.push(0);
- } else {
- let generation = &mut self.style_record_generations[identity.index()];
- *generation = generation
- .checked_add(1)
- .filter(|&generation| generation <= FinalStyleRecordID::MAX_BASE_GENERATION)
- .expect("base style-record generation space exhausted");
- }
- self.identity_mints.style_records += 1;
- self.style_records.insert(hash, identity, record);
- let (changed, _) = self.style_record_liveness.set(identity.index(), true);
- assert!(changed, "new base style-record identity must not already be live");
- self.style_records_interned_since_reclamation = self
- .style_records_interned_since_reclamation
- .checked_add(1)
- .expect("style-record reclamation growth count overflow");
- (identity, true)
- }
-
- fn style_record_is_live(&self, identity: StyleRecordID) -> bool {
- self.style_record_liveness.contains(identity.index())
- }
-
- fn style_record_generation_is_live(&self, identity: StyleRecordID, generation: u32) -> bool {
- self.style_record_is_live(identity) && self.style_record_generations.get(identity.index()) == Some(&generation)
- }
-
- fn final_base_style_record(&self, identity: StyleRecordID) -> FinalStyleRecordID {
- FinalStyleRecordID::base(identity, self.style_record_generations[identity.index()])
- }
-
- /// The record a composition is laid over: the base record an animation overlay record composes
- /// over, or the record itself where it composes nothing.
+ /// The record a composition is laid over: the installed record an animation overlay record
+ /// composes over, or the record itself where it composes nothing.
pub(crate) fn underlying_style_record(&self, record: FinalStyleRecordID) -> Option<FinalStyleRecordID> {
- if record.base_record().is_some() {
+ if record.installed_record().is_some() {
return Some(record);
}
- Some(self.final_base_style_record(self.overlay_base_style_record(record)?))
+ Some(FinalStyleRecordID::installed(self.overlay_base(record)?))
}
- /// The base record an animation overlay record composes over.
- fn overlay_base_style_record(&self, overlay: FinalStyleRecordID) -> Option<StyleRecordID> {
+ /// The installed record an animation overlay record composes over.
+ fn overlay_base(&self, overlay: FinalStyleRecordID) -> Option<InstalledRecordID> {
let slot = *self.animation_overlay_slots_by_record.get(&overlay)?;
- Some(self.animation_overlay_slots.get(slot)?.base_style_record)
+ Some(self.animation_overlay_slots.get(slot)?.base)
}
- /// The record a target holds beneath its composition, and the composition's slot.
- fn assigned_record_and_overlay_slot(&self, target: ComputedStyleTarget) -> Option<(StyleRecordID, Option<u32>)> {
+ /// The installed record a target holds beneath its composition, and the composition's slot.
+ fn assigned_record_and_overlay_slot(
+ &self,
+ target: ComputedStyleTarget,
+ ) -> Option<(InstalledRecordID, Option<u32>)> {
if target.is_pseudo() {
- let assignment = self.pseudo_row(target.node, target.pseudo_kind)?.assignment?;
- return Some((assignment.style_record, assignment.animation_overlay_slot));
+ let row = self.pseudo_row(target.node, target.pseudo_kind)?;
+ return Some((row.installed?, row.installed_overlay_slot));
}
let index = target.node.element_index()? as usize;
Some((
- (*self.style_record_column.get(index)?)?,
- self.columns.animation_overlay_slot(index),
+ self.installed_column.get(index)?.as_ref()?.id,
+ self.animation_overlay_column.get(index),
))
}
- fn set_animation_overlay_slot_of(&mut self, target: ComputedStyleTarget, slot: Option<u32>) {
- if target.is_pseudo() {
- if let Some(assignment) = self
- .pseudo_row_mut(target.node, target.pseudo_kind)
- .and_then(|row| row.assignment.as_mut())
- {
- assignment.animation_overlay_slot = slot;
- }
- } else if let Some(index) = target.node.element_index() {
- self.columns.set_animation_overlay_slot(index as usize, slot);
- }
- }
-
- /// Stop composing a target's animations over the record its winners decided, so that a record
- /// derived beneath the composition can take that record's place. The composition stays live,
- /// pinned, for whoever still holds it, until the caller puts it back with
- /// `reattach_composition` or lets it go with `release_detached_composition`. `None` where the
- /// target composes nothing.
- pub(super) fn detach_composition(&mut self, node: StyleNodeID) -> Option<DetachedComposition> {
- self.detach_composition_of(ComputedStyleTarget::new(node, u8::MAX))
- }
-
- /// What `detach_composition` does for an element, for any target.
- pub(super) fn detach_composition_of(&mut self, target: ComputedStyleTarget) -> Option<DetachedComposition> {
- let (_, slot) = self.assigned_record_and_overlay_slot(target)?;
- let detached = self.detach_animation_overlay_slot(slot?)?;
- self.set_animation_overlay_slot_of(target, None);
- Some(detached)
+ /// Whether a target holds a record beneath its composition.
+ pub(crate) fn holds_an_installed_record(&self, target: ComputedStyleTarget) -> bool {
+ self.assigned_record_and_overlay_slot(target).is_some()
}
- fn detach_animation_overlay_slot(&mut self, slot: u32) -> Option<DetachedComposition> {
- let overlay = self.animation_overlay_slots.get(slot)?;
- let detached = DetachedComposition {
- record: overlay.final_style_record,
- base: self.final_base_style_record(overlay.base_style_record),
- forked: false,
+ /// Whether an element holds `record`, a record the engine computed for it, beneath the
+ /// composition of its animations: the record installed for it, or one installed that holds
+ /// the same. An element holding no record yet has had nothing installed in place of what style
+ /// the engine computed for it.
+ pub(super) fn holds_record(&self, node: StyleNodeID, record: &std::sync::Arc<super::pipeline::Record>) -> bool {
+ let Some(index) = node.element_index() else {
+ return false;
};
- self.pin_style_record(detached.record.raw());
- self.release_animation_overlay_assignment(slot);
- Some(detached)
- }
-
- /// Compose a target's animations over its record again as they were before
- /// `detach_composition`, whose pin this takes over: the record derived beneath the composition
- /// was not installed. A composition laid over a record the target no longer holds stays
- /// detached.
- pub(super) fn reattach_composition(&mut self, node: StyleNodeID, detached: DetachedComposition) {
- self.reattach_composition_of(ComputedStyleTarget::new(node, u8::MAX), detached);
- }
-
- /// What `reattach_composition` does for an element, for any target.
- pub(super) fn reattach_composition_of(&mut self, target: ComputedStyleTarget, detached: DetachedComposition) {
- let base = detached.base;
- let record = detached.into_pinned_record();
- let slot = self.animation_overlay_slots_by_record.get(&record).copied();
- if let Some(slot) = slot
- && self
- .assigned_record_and_overlay_slot(target)
- .is_some_and(|(assigned, current)| current.is_none() && Some(assigned) == base.base_record())
- && let Some(overlay) = self.animation_overlay_slots.get_mut(slot)
- {
- overlay.is_assigned = true;
- self.live_animation_overlay_assignments += 1;
- self.set_animation_overlay_slot_of(target, Some(slot));
- }
- self.unpin_style_record(record.raw());
- }
-
- /// Let go of a composition `detach_composition` kept: the record derived beneath it took its place.
- pub(super) fn release_detached_composition(&mut self, detached: DetachedComposition) {
- self.unpin_style_record(detached.into_pinned_record().raw());
+ let Some(installed) = self.installed_column.get(index as usize).and_then(Option::as_ref) else {
+ return true;
+ };
+ std::sync::Arc::ptr_eq(&installed.record, record) || installed.record.holds_the_same_style_as(record)
+ }
+
+ /// The record the engine installed that an element holds beneath the composition of its
+ /// animations, if any.
+ pub(super) fn held_record(&self, node: StyleNodeID) -> Option<&std::sync::Arc<super::pipeline::Record>> {
+ Some(
+ &self
+ .installed_column
+ .get(node.element_index()? as usize)?
+ .as_ref()?
+ .record,
+ )
}
- /// Interns one frozen computed longhand table. Values and publication
- /// metadata participate in identity; the per-drive provenance sidecar
- /// does not. A candidate found equal by comparison is reused before the
- /// table's hash is asked for, so a table that starts empty and computes
- /// to a published state never hashes its values.
- fn find_longhand_table(
+ /// The view of the composition of an element's animations over `record`, a record the engine
+ /// computed for it, where the element holds that record beneath the composition.
+ pub(super) fn composition_over_record(
&self,
- table: &ComputedLonghandTable,
- previous: Option<ComputedLonghandTableID>,
- canonical: Option<ComputedLonghandTableID>,
- ) -> Result<ComputedLonghandTableID, u64> {
- debug_assert!(table.is_frozen(), "only frozen longhand tables are published");
- for candidate in [previous, canonical].into_iter().flatten() {
- if self.computed_longhand_tables[candidate]
- .table()
- .publication_equals(table)
- {
- return Ok(candidate);
- }
- }
- let hash = longhand_table_hash(table);
- if let Some(identity) = self
- .computed_longhand_tables
- .find(hash, |_identity, candidate| candidate.table().publication_equals(table))
- {
- return Ok(identity);
+ node: StyleNodeID,
+ record: &std::sync::Arc<super::pipeline::Record>,
+ ) -> Option<StyleRecordView<'_>> {
+ let slot = self.animation_overlay_column.get(node.element_index()? as usize)?;
+ if !self.holds_record(node, record) {
+ return None;
}
- Err(hash)
- }
-
- /// Interns one longhand table. `owned` says the caller holds the reference behind `table` and
- /// hands it over; the returned flag says whether interning took it.
- fn intern_longhand_table_owned(
- &mut self,
- table: &ComputedLonghandTable,
- previous: Option<ComputedLonghandTableID>,
- canonical: Option<ComputedLonghandTableID>,
- owned: bool,
- ) -> (ComputedLonghandTableID, bool) {
- let hash = match self.find_longhand_table(table, previous, canonical) {
- Ok(identity) => return (identity, false),
- Err(hash) => hash,
- };
- let retained = if owned {
- std::ptr::from_ref(table)
- } else {
- unsafe { crate::css::computed_longhand_table::rust_computed_longhand_table_retain(table) }
- };
- (self.insert_longhand_table(retained, hash), owned)
+ let overlay = self.animation_overlay_slots.get(slot)?;
+ self.style_record_view(overlay.final_style_record().raw())
}
- fn intern_owned_longhand_table(
- &mut self,
- table: ComputedLonghandTable,
- previous: Option<ComputedLonghandTableID>,
- canonical: Option<ComputedLonghandTableID>,
- ) -> ComputedLonghandTableID {
- let hash = match self.find_longhand_table(&table, previous, canonical) {
- Ok(identity) => return identity,
- Err(hash) => hash,
- };
- // NB: Only a new unique result materializes; ownership transfers to the catalog.
- self.insert_longhand_table(table.into_raw_shared(), hash)
+ fn set_animation_overlay_slot_of(&mut self, target: ComputedStyleTarget, slot: Option<u32>) {
+ if target.is_pseudo() {
+ let Some(row) = self.pseudo_row_mut(target.node, target.pseudo_kind) else {
+ return;
+ };
+ if row.installed.is_some() {
+ row.installed_overlay_slot = slot;
+ }
+ } else if let Some(index) = target.node.element_index().map(|index| index as usize) {
+ self.animation_overlay_column.set(index, slot);
+ }
}
-
- fn insert_longhand_table(&mut self, retained: *const ComputedLonghandTable, hash: u64) -> ComputedLonghandTableID {
- let identity = self.computed_longhand_tables.take_free_identity().unwrap_or_else(|| {
- ComputedLonghandTableID(
- u32::try_from(self.computed_longhand_tables.len())
- .expect("computed longhand-table identity space exhausted"),
- )
- });
-
- self.computed_longhand_tables.insert(
- hash,
- identity,
- RetainedLonghandTable {
- table: HostShared::new(retained),
- },
- );
- identity
+ fn next_animation_overlay_record(&mut self) -> FinalStyleRecordID {
+ self.next_animation_overlay_generation = self
+ .next_animation_overlay_generation
+ .checked_add(1)
+ .expect("animation-overlay generation space exhausted");
+ FinalStyleRecordID::animation_overlay(self.next_animation_overlay_generation)
}
- /// Replace a fully inheriting element's engine-resolvable inherited groups with its flat-tree
- /// parent's groups and publish the resulting base style record without rebuilding computed values.
- pub(super) fn replace_engine_resolvable_inherited_groups(
+ fn make_animation_overlay_record(
&mut self,
- node: StyleNodeID,
- parent: StyleNodeID,
- inherited_style_groups: u8,
- cache: &mut HashMap<(FinalStyleRecordID, FinalStyleRecordID, u8), FinalStyleRecordID>,
- ) -> Option<(FinalStyleRecordID, FinalStyleRecordID, bool)> {
- const STATIC_INHERITED_GROUPS: u8 = (1 << 0) | (1 << 1) | (1 << 3);
- const INHERITED_UI_GROUP: u8 = 1 << 2;
- const INHERITED_TEXT_GROUP: u8 = 1 << 4;
- const FONT_GROUP: u8 = 1 << 6;
- const ENGINE_RESOLVABLE_INHERITED_GROUPS: u8 =
- STATIC_INHERITED_GROUPS | INHERITED_UI_GROUP | INHERITED_TEXT_GROUP | FONT_GROUP;
- const INHERITED_GROUP_COUNT: usize = 7;
- const INHERITED_GROUP_MASK: u32 = (1 << INHERITED_GROUP_COUNT) - 1;
- const CURRENT_COLOR_REBUILDABLE_GROUPS: u32 = (1
- << crate::css::computed_value_types::STYLE_GROUP_INDEX_SVG_RESET)
- | (1 << crate::css::computed_value_types::STYLE_GROUP_INDEX_EFFECTS)
- | (1 << crate::css::computed_value_types::STYLE_GROUP_INDEX_TEXT_RESET)
- | (1 << crate::css::computed_value_types::STYLE_GROUP_INDEX_BACKGROUND)
- | (1 << crate::css::computed_value_types::STYLE_GROUP_INDEX_BORDER)
- | (1 << crate::css::computed_value_types::STYLE_GROUP_INDEX_MISC_RESET);
- if inherited_style_groups == 0 || inherited_style_groups & !ENGINE_RESOLVABLE_INHERITED_GROUPS != 0 {
- return None;
+ base: InstalledRecordID,
+ source_identity: u64,
+ animated_overlay: Box<crate::css::animated_overlay::AnimatedOverlay>,
+ payloads: &crate::css::computed_values::StyleGroups,
+ in_display_none_subtree: Option<bool>,
+ ) -> AnimationOverlayRecord {
+ let final_style_record = self.next_animation_overlay_record();
+ let installed = self.installed.get(base).expect("installed style record is live");
+ let mut dependency_flags = installed.dependency_flags();
+ // SAFETY: Published style-group payloads stay live while their records do.
+ if unsafe { style_group_payloads_hold_image_values(&payloads.pointers()) } {
+ dependency_flags |= HOLDS_IMAGE_VALUES;
}
- let index = node.element_index()? as usize;
- let parent_index = parent.element_index()? as usize;
- // A child inherits the parent's animated values, which C++ composes over the record.
- if !self.columns.inherited_group_swap_eligible(index)
- || self.columns.animation_overlay_slot(index).is_some()
- || self.node_has_animation_overlay(parent)
- || self.adjustment_facts(parent) & super::bridge::element_adjustment_fact::HAS_ANIMATIONS != 0
- || self.assigned_pseudo_kinds(node).next().is_some()
- || self.adjustment_facts(node)
- & (super::bridge::element_adjustment_fact::HAS_ANIMATIONS
- | super::bridge::element_adjustment_fact::IS_SHADOW_HOST_PSEUDO_ELEMENT)
- != 0
- {
- return None;
+ if let Some(in_display_none_subtree) = in_display_none_subtree {
+ dependency_flags = (dependency_flags & !IN_DISPLAY_NONE_SUBTREE)
+ | (u8::from(in_display_none_subtree) * IN_DISPLAY_NONE_SUBTREE);
+ }
+ let record = std::sync::Arc::new(super::pipeline::Record::sample(
+ installed.record(),
+ payloads,
+ std::sync::Arc::from(animated_overlay),
+ dependency_flags,
+ final_style_record,
+ ));
+ AnimationOverlayRecord {
+ base,
+ source_identity,
+ record,
+ pin_count: 0,
+ is_assigned: true,
}
+ }
- let old_style_record = *self.style_record_column.get(index)?.as_ref()?;
- let old_record = *self.style_records.get_index(old_style_record.index())?;
- // OPTIMIZATION: Node-local eligibility is checked above. Everything else the swap reads belongs to these
- // immutable records, so equal inputs can share the table and rebuilt currentColor groups.
- let cache_key = (
- self.final_base_style_record(old_style_record),
- self.final_base_style_record(self.style_record_column.get(parent_index).copied().flatten()?),
- inherited_style_groups,
+ fn allocate_animation_overlay(
+ &mut self,
+ base: InstalledRecordID,
+ source_identity: u64,
+ animated_overlay: Option<&crate::css::animated_overlay::AnimatedOverlay>,
+ payloads: &crate::css::computed_values::StyleGroups,
+ in_display_none_subtree: Option<bool>,
+ ) -> (u32, FinalStyleRecordID, bool) {
+ let record = self.make_animation_overlay_record(
+ base,
+ source_identity,
+ Box::new(
+ animated_overlay
+ .expect("animation overlay properties are missing")
+ .clone(),
+ ),
+ payloads,
+ in_display_none_subtree,
);
- if let Some(&cached) = cache.get(&cache_key)
- && let Some(record) = cached.base_record()
- && self.style_record_generation_is_live(record, cached.base_generation())
- {
- let result = self.style_records[record];
- self.columns.groups[index] = result.groups.0;
- self.columns.inherited_groups[index] = result.inherited_groups.0;
- self.style_record_column[index] = Some(record);
- return Some((cache_key.0, cached, true));
- }
- let target = ComputedStyleTarget::new(node, u8::MAX);
- let current_color_dependencies = if inherited_style_groups & INHERITED_TEXT_GROUP != 0 {
- self.current_color_dependency_mask(target)?
- } else {
- 0
- };
- if current_color_dependencies & (1 << crate::css::computed_value_types::STYLE_GROUP_INDEX_SVG_RESET) != 0 {
- return None;
- }
- if current_color_dependencies & !(INHERITED_GROUP_MASK | CURRENT_COLOR_REBUILDABLE_GROUPS) != 0 {
- return None;
- }
- if inherited_style_groups & INHERITED_UI_GROUP != 0
- && self
- .color_scheme_dependency_mask(target)
- .is_none_or(|dependencies| dependencies & !INHERITED_GROUP_MASK != 0)
- {
- return None;
- }
- if inherited_style_groups & FONT_GROUP != 0
- && self
- .font_dependency_mask(target)
- .is_none_or(|dependencies| dependencies & !INHERITED_GROUP_MASK != 0)
- {
- return None;
- }
+ let final_style_record = record.final_style_record();
+ let (slot, slot_allocated) = self.animation_overlay_slots.fill(record);
+ self.animation_overlay_slots_by_record.insert(final_style_record, slot);
+ self.live_animation_overlay_assignments += 1;
+ (slot, final_style_record, slot_allocated)
+ }
- // An element animating, or declaring transitions a moved inherited value may start,
- // composes its style in C++.
- if old_record
- .longhand_table
- .and_then(|table| self.computed_longhand_tables.get_index(table.index()))
- .is_none_or(|retained| crate::css::style_compute::has_active_transition_properties(retained.table()))
- {
- return None;
- }
- let old_group_set = self.sets.get_index(old_record.groups.0 as usize)?;
- let parent_inherited = self.columns.inherited_groups(parent_index)?;
- let parent_groups = self.inherited_sets.get_index(parent_inherited.0 as usize)?.as_ref();
- if parent_groups.len() != INHERITED_GROUP_COUNT || old_group_set.payloads.len() < INHERITED_GROUP_COUNT {
- return None;
+ /// Reclaims `slot`, which nothing assigns or pins, unless something else holds its record: then it goes once nothing
+ /// does.
+ fn reclaim_animation_overlay_slot_unless_held(&mut self, slot: u32) {
+ let record = self
+ .animation_overlay_slots
+ .get(slot)
+ .expect("animation-overlay slot is live");
+ if record.is_held_elsewhere() {
+ self.held_animation_overlay_slots.push(slot);
+ return;
}
+ self.reclaim_animation_overlay_slot(slot);
+ }
- if current_color_dependencies & !INHERITED_GROUP_MASK != 0 {
- let inherited_box = unsafe {
- old_group_set.payloads[crate::css::computed_value_types::STYLE_GROUP_INDEX_INHERITED_BOX]
- .cast::<crate::css::computed_values::InheritedBoxValues>()
- .deref()
+ /// Reclaims the slots of the overlay records nothing assigns, pins or holds anymore.
+ fn sweep_held_animation_overlays(&mut self) {
+ if self.held_animation_overlay_slots.is_empty() {
+ return;
+ }
+ let mut slots = std::mem::take(&mut self.held_animation_overlay_slots);
+ slots.sort_unstable();
+ slots.dedup();
+ for slot in slots {
+ // NB: A slot a pin took again goes back on the list when its last pin goes.
+ let Some(record) = self.animation_overlay_slots.get(slot) else {
+ continue;
};
- let dependencies = self.current_color_dependency_properties(target)?;
- for property in crate::css::property_metadata::FIRST_LONGHAND_PROPERTY_ID
- ..=crate::css::property_metadata::LAST_LONGHAND_PROPERTY_ID
- {
- let slot = usize::from(property - crate::css::property_metadata::FIRST_LONGHAND_PROPERTY_ID);
- if dependencies[slot / 64] & (1 << (slot % 64)) == 0
- || crate::css::property_metadata::property_is_inherited(property)
- {
- continue;
- }
- let physical_property = if crate::css::property_metadata::longhand_is_logical_alias(property) {
- crate::css::style_compute::map_logical_alias_to_physical(
- property,
- inherited_box.writing_mode,
- inherited_box.direction,
- )
- } else {
- property
- };
- if !matches!(
- physical_property,
- crate::css::property_metadata::property_id::BACKDROP_FILTER
- | crate::css::property_metadata::property_id::BACKGROUND_COLOR
- | crate::css::property_metadata::property_id::BORDER_BOTTOM_COLOR
- | crate::css::property_metadata::property_id::BORDER_LEFT_COLOR
- | crate::css::property_metadata::property_id::BORDER_RIGHT_COLOR
- | crate::css::property_metadata::property_id::BORDER_TOP_COLOR
- | crate::css::property_metadata::property_id::BOX_SHADOW
- | crate::css::property_metadata::property_id::COLUMN_RULE_COLOR
- | crate::css::property_metadata::property_id::FILTER
- | crate::css::property_metadata::property_id::FLOOD_COLOR
- | crate::css::property_metadata::property_id::OUTLINE_COLOR
- | crate::css::property_metadata::property_id::STOP_COLOR
- | crate::css::property_metadata::property_id::TEXT_DECORATION_COLOR
- ) {
- return None;
- }
+ if record.is_assigned || record.pin_count != 0 {
+ continue;
+ }
+ if record.is_held_elsewhere() {
+ self.held_animation_overlay_slots.push(slot);
+ } else {
+ self.reclaim_animation_overlay_slot(slot);
}
}
+ }
- let parent_style_record = self.style_record_column.get(parent_index).copied().flatten();
- let parent_table = parent_style_record
- .and_then(|record| self.style_records.get_index(record.index()))
- .and_then(|record| record.longhand_table);
- if parent_table.is_some_and(|table| {
- crate::css::style_compute::has_active_transition_properties(self.computed_longhand_tables[table].table())
- }) {
- return None;
- }
-
- let swapped_table = match (old_record.longhand_table, parent_table) {
- (Some(old_table), Some(parent_table)) => Some(
- self.computed_longhand_tables[old_table]
- .table()
- .with_inherited_values_from(self.computed_longhand_tables[parent_table].table()),
- ),
- (None, _) if current_color_dependencies & !INHERITED_GROUP_MASK == 0 => None,
- _ => return None,
- };
-
- let mut groups: SmallVec<[_; crate::css::table_group_builder::group_index::COUNT]> = parent_groups
- .iter()
- .copied()
- .chain(old_group_set.groups.iter().copied().skip(INHERITED_GROUP_COUNT))
- .collect();
- if let Some(table) = &swapped_table
- && current_color_dependencies & !INHERITED_GROUP_MASK != 0
- {
- let inherited_text = unsafe {
- self.groups[parent_groups[crate::css::computed_value_types::STYLE_GROUP_INDEX_INHERITED_TEXT]]
- .payload
- .cast::<crate::css::computed_value_types::InheritedTextValues>()
- .deref()
- };
- let inherited_ui = unsafe {
- self.groups[parent_groups[crate::css::computed_value_types::STYLE_GROUP_INDEX_INHERITED_UI]]
- .payload
- .cast::<crate::css::computed_value_types::InheritedUIValues>()
- .deref()
- };
- for (group, group_identity) in groups.iter_mut().enumerate().skip(INHERITED_GROUP_COUNT) {
- if current_color_dependencies & (1 << group) == 0 {
- continue;
- }
- let old_payload = self.groups[*group_identity].payload;
- let payload = SharedPayload::new(
- unsafe {
- crate::css::table_group_builder::rebuild_group_for_inherited_current_color(
- table,
- group,
- crate::css::computed_values::GroupPayloadRef::new(group, old_payload.as_ptr()),
- inherited_text.color,
- inherited_ui.color_scheme,
- )
- }
- .expect("a supported currentcolor group rebuilds from its computed table"),
- );
- // A rebuilt payload's reference moves into the catalog when it is published,
- // and stays with the swap to be released when an equal one is already there.
- let identity = if payload == old_payload {
- release_group_payload(group, payload.as_ptr());
- *group_identity
- } else {
- let (identity, inserted) = self.intern_group_owned(group, payload, true);
- if !inserted {
- release_group_payload(group, payload.as_ptr());
- }
- identity
- };
- *group_identity = identity;
- }
- }
- let group_set = self.intern_group_set(&groups).0;
- // The swap is only taken for a fully inheriting element, so every
- // inherited-by-default longhand's value is the parent's; the swapped
- // table keeps the record a complete inheritance source for a child.
- let longhand_table =
- swapped_table.map(|table| self.intern_owned_longhand_table(table, old_record.longhand_table, None));
- let new_record = StyleRecord {
- groups: group_set,
- inherited_groups: parent_inherited,
- custom_properties: old_record.custom_properties,
- fixed_metadata: old_record.fixed_metadata,
- longhand_table,
- };
- let new_style_record = self.intern_style_record(new_record).0;
- self.columns.groups[index] = group_set.0;
- self.columns.inherited_groups[index] = parent_inherited.0;
- self.style_record_column[index] = Some(new_style_record);
- let new_style_record = self.final_base_style_record(new_style_record);
- cache.insert(cache_key, new_style_record);
- Some((cache_key.0, new_style_record, false))
- }
-
- /// Assemble a new base record for `node` from a longhand table the engine drove itself. The
- /// table began as a copy of `base_style_record`, so its hash adjusts slot by slot; the
- /// groups `groups_to_rebuild` names are rebuilt from it, and the record's fixed metadata
- /// follows the table's dependency flags. The font group is never rebuilt here: it needs
- /// platform font resources the table does not hold.
- ///
- /// The node's assigned record is the base the table was driven from; the table it held, if
- /// any, only seeds the new table's identity. Its pseudo-elements' records are untouched: they
- /// inherit from the element, and the caller has proven that nothing they inherit moved. The
- /// record names `counter_style_environment_identity` as its counter-style registry, or the
- /// one its base names when that is `None`.
- #[allow(clippy::arc_with_non_send_sync, clippy::too_many_arguments)]
- pub(super) fn replace_engine_computed_table(
- &mut self,
- node: StyleNodeID,
- base_style_record: FinalStyleRecordID,
- previous_style_record: FinalStyleRecordID,
- mut table: ComputedLonghandTable,
- groups_to_rebuild: u32,
- length: &crate::css::style_compute::FfiLengthResolutionContext,
- font: Option<&crate::css::table_group_builder::FfiFontGroupBuildInputs>,
- parent_in_display_none_subtree: bool,
- environment: Option<u64>,
- counter_style_environment_identity: Option<u64>,
- ) -> Option<EngineComputedAssembly> {
- // The caller drove the table from an element's live base record; a row that is not
- // assembles nothing.
- let base = node
- .element_index()
- .zip(base_style_record.base_record())
- .filter(|&(_, base)| self.style_record_generation_is_live(base, base_style_record.base_generation()));
- let Some((index, base_style_record_identity)) = base else {
- debug_assert!(false, "a table is driven from an element's live base record");
- return None;
- };
- let index = index as usize;
- debug_assert!(
- self.columns.animation_overlay_slot(index).is_none(),
- "a record composing animations is not driven"
- );
- let old_record = *self.style_records.get_index(base_style_record_identity.index())?;
- let old_table = old_record.longhand_table;
- debug_assert_eq!(
- self.sets
- .get_index(old_record.groups.0 as usize)
- .map(|set| set.payloads.len()),
- Some(crate::css::table_group_builder::group_index::COUNT),
- "an element's record holds every style group"
- );
- // The builders take the element's own color from the caller, so it is resolved from the
- // driven table before any group reads it.
- let color_inputs = crate::css::table_group_builder::assembly_color_inputs(&table, length);
- let (used_color_scheme, current_color) = color_inputs;
- for property in [
- crate::css::property_metadata::property_id::STOP_COLOR,
- crate::css::property_metadata::property_id::FLOOD_COLOR,
- ] {
- let specified = table
- .retained_inheritance_dependent_values()
- .find(|(candidate, value)| *candidate == property && retained_value_depends_on_current_color(value))
- .map(|(_, value)| value);
- let Some(specified) = specified else {
- continue;
- };
- let input = crate::css::color_resolution::ColorResolutionInput {
- scheme: Some(used_color_scheme),
- current_color: Some(crate::css::color_resolution::Rgba {
- r: (current_color >> 16) as u8,
- g: (current_color >> 8) as u8,
- b: current_color as u8,
- a: (current_color >> 24) as u8,
- }),
- current_color_value: None,
- length: Some(length),
- channels: None,
- };
- // A value that does not resolve keeps what the drive computed for it.
- let Some(resolved) = crate::css::color_resolution::to_color(specified.data(), &input) else {
- debug_assert!(false, "a currentcolor-relative color does not resolve");
- continue;
- };
- let resolved = RetainedStyleValueData::from_arc(std::sync::Arc::new(
- crate::css::color_resolution::resolved_srgb_style_value(resolved),
- ));
- let source_slot = table.source_slot(property).map_or(-1, i64::from);
- table.set(property, resolved, source_slot);
- }
- // The flag is the parent's and the driven display's, the way a fresh computation sets
- // it, not what the old table held.
- let display_is_none = crate::css::style_compute::effective_display(&table, None).is_none();
- table.set_in_display_none_subtree(parent_in_display_none_subtree || display_is_none);
- table.finish_delta();
-
- let mut groups: SmallVec<[_; crate::css::table_group_builder::group_index::COUNT]> =
- self.group_identities(old_record.groups).collect();
- let mut canonicalized_groups = 0_u32;
- for (group, group_identity) in groups.iter_mut().enumerate() {
- if groups_to_rebuild & (1 << group) == 0 {
- continue;
- }
- let old_payload = self.groups[*group_identity].payload;
- let payload = SharedPayload::new(unsafe {
- crate::css::table_group_builder::assemble_group_from_table(
- &table,
- group,
- font,
- crate::css::computed_values::GroupPayloadRef::new(group, old_payload.as_ptr()),
- color_inputs,
- length,
- )
- });
- // An equal payload keeps the old identity, as a C++ build adopts its parent's and
- // predecessor's identical payloads.
- let identity = if payload == old_payload
- // SAFETY: Published style-group payloads stay live while their records do.
- || unsafe { style_group_payloads_equal(group, old_payload.as_ptr(), payload.as_ptr()) }
- {
- canonicalized_groups += 1;
- release_group_payload(group, payload.as_ptr());
- *group_identity
- } else {
- // The rebuild's reference moves into the catalog when it publishes the payload.
- let (identity, inserted) = self.intern_group_owned(group, payload, true);
- if !inserted {
- release_group_payload(group, payload.as_ptr());
- }
- identity
- };
- *group_identity = identity;
- }
- let group_set = self.intern_group_set(&groups).0;
- let holds_image_values = self
- .sets
- .get_index(group_set.0 as usize)
- // SAFETY: Published style-group payloads stay live while their records do.
- .is_some_and(|set| unsafe {
- style_group_payloads_hold_image_values(SharedPayload::as_pointer_slice(&set.payloads))
- });
- let old_metadata = self.computed_fixed_metadata[old_record.fixed_metadata];
- let counter_style_environment_identity =
- counter_style_environment_identity.unwrap_or(old_metadata.counter_style_environment_identity);
- let swap_eligible = table_inherited_group_swap_eligible(&table);
- let dependency_flags =
- table.publication_dependency_flags() | (u8::from(holds_image_values) * HOLDS_IMAGE_VALUES);
- let fixed_metadata = if dependency_flags == old_metadata.dependency_flags
- && counter_style_environment_identity == old_metadata.counter_style_environment_identity
- {
- old_record.fixed_metadata
- } else {
- self.intern_fixed_metadata(ComputedFixedMetadata {
- dependency_flags,
- counter_style_environment_identity,
- ..old_metadata
- })
- .0
- };
- let longhand_table = self.intern_owned_longhand_table(table, old_table, None);
- // The environment moves with the record when the node's custom declarations resolved to
- // another; a record keeps its environment otherwise.
- let custom_properties = match environment {
- Some(environment) => self.intern_custom_property_environment(environment).0,
- None => old_record.custom_properties,
- };
- let inherited_identity = self
- .intern_inherited_group_set(&groups[..ENGINE_INHERITED_GROUP_COUNT])
- .0;
- let new_record = StyleRecord {
- groups: group_set,
- inherited_groups: inherited_identity,
- custom_properties,
- fixed_metadata,
- longhand_table: Some(longhand_table),
- };
- let new_style_record = self.intern_style_record(new_record).0;
- let replaced = self.replaced_columns(node);
- // Descendant swaps read the node's inherited groups from their own column.
- self.columns.publish(
- index,
- PublishedComputedInputs {
- groups: group_set,
- inherited_groups: inherited_identity,
- custom_properties,
- fixed_metadata,
- style_record: new_style_record,
- animation_overlay_slot: None,
- },
- swap_eligible,
- );
- if self.style_record_column.len() <= index {
- self.style_record_column.resize(index + 1, None);
- }
- self.style_record_column[index] = Some(new_style_record);
- Some(EngineComputedAssembly {
- delta: (previous_style_record, self.final_base_style_record(new_style_record)),
- canonicalized_groups,
- group_set_unchanged: group_set == old_record.groups,
- replaced,
- })
- }
-
- /// What `node`'s columns hold now, for an engine derivation about to replace its record.
- pub(super) fn replaced_columns(&self, node: StyleNodeID) -> ReplacedColumns {
- let index = node.element_index().map(|index| index as usize);
- let inputs = index.and_then(|index| {
- Some(PublishedComputedInputs {
- groups: self.columns.groups(index)?,
- inherited_groups: self.columns.inherited_groups(index)?,
- custom_properties: self.columns.custom_properties(index)?,
- fixed_metadata: self.columns.fixed_metadata(index)?,
- style_record: (*self.style_record_column.get(index)?)?,
- animation_overlay_slot: None,
- })
- });
- ReplacedColumns {
- inputs,
- inherited_group_swap_eligible: index.is_some_and(|index| self.columns.inherited_group_swap_eligible(index)),
- }
- }
-
- /// Put a node back on what its columns held before an engine derivation C++ never installed,
- /// `replaced`, unless a publication has moved it on since.
- pub(super) fn revert_engine_computed_record(
- &mut self,
- node: StyleNodeID,
- derived_style_record: FinalStyleRecordID,
- replaced: ReplacedColumns,
- ) {
- let Some(index) = node.element_index().map(|index| index as usize) else {
- return;
- };
- let Some(current) = self.style_record_column.get(index).copied().flatten() else {
- return;
- };
- if self.final_style_record(current, self.columns.animation_overlay_slot(index)) != derived_style_record {
- return;
- }
- // A first record never installed leaves the node the way it was: unassigned, with what
- // the host and its match answer published for it, which the layout tree and the next
- // derivation read.
- let Some(inputs) = replaced.inputs else {
- self.unassign(node);
- return;
- };
- self.columns
- .publish(index, inputs, replaced.inherited_group_swap_eligible);
- self.style_record_column[index] = Some(inputs.style_record);
- }
-
- fn intern_fixed_metadata(&mut self, metadata: ComputedFixedMetadata) -> (ComputedFixedMetadataID, bool) {
- let hash = content_hash(metadata);
- if let Some(identity) = self
- .computed_fixed_metadata
- .find(hash, |_identity, candidate| *candidate == metadata)
- {
- return (identity, false);
- }
- let identity = self.computed_fixed_metadata.take_free_identity().unwrap_or_else(|| {
- ComputedFixedMetadataID(
- u32::try_from(self.computed_fixed_metadata.len())
- .expect("computed fixed-metadata identity space exhausted"),
- )
- });
- self.computed_fixed_metadata.insert(hash, identity, metadata);
- (identity, true)
- }
-
- /// Assign a node the record another node of its cohort already derived this flush: the same
- /// old record moved to the same new winner state produces the same new record, so only the
- /// node's columns move. An `old_style_record` of `NONE` assigns a node that holds no record.
- /// Answers what the record took the place of, for reverting it.
- pub(super) fn assign_engine_computed_record(
- &mut self,
- node: StyleNodeID,
- old_style_record: FinalStyleRecordID,
- new_style_record: FinalStyleRecordID,
- ) -> Option<ReplacedColumns> {
- let index = node.element_index()? as usize;
- if self.columns.animation_overlay_slot(index).is_some() {
- return None;
- }
- let current = self.style_record_column.get(index).copied().flatten();
- if current.map_or(FinalStyleRecordID::NONE, |current| {
- self.final_base_style_record(current)
- }) != old_style_record
- {
- return None;
- }
- let new_base_record = new_style_record.base_record()?;
- let new_record = *self.style_records.get_index(new_base_record.index())?;
- let swap_eligible = new_record
- .longhand_table
- .and_then(|table| self.computed_longhand_tables.get_index(table.index()))
- .is_some_and(|retained| table_inherited_group_swap_eligible(retained.table()));
- let replaced = self.replaced_columns(node);
- self.columns.publish(
- index,
- PublishedComputedInputs {
- groups: new_record.groups,
- inherited_groups: new_record.inherited_groups,
- custom_properties: new_record.custom_properties,
- fixed_metadata: new_record.fixed_metadata,
- style_record: new_base_record,
- animation_overlay_slot: None,
- },
- swap_eligible,
- );
- if self.style_record_column.len() <= index {
- self.style_record_column.resize(index + 1, None);
- }
- self.style_record_column[index] = Some(new_base_record);
- Some(replaced)
- }
-
- /// The identity of a record's inherited groups, the way a node assigned it would hold them.
- pub(super) fn style_record_inherited_groups_identity(&self, style_record: FinalStyleRecordID) -> Option<u32> {
- let base_record = style_record.base_record()?;
- let record = *self.style_records.get_index(base_record.index())?;
- Some(record.inherited_groups.0)
- }
-
- fn next_animation_overlay_record(&mut self) -> FinalStyleRecordID {
- self.next_animation_overlay_generation = self
- .next_animation_overlay_generation
- .checked_add(1)
- .expect("animation-overlay generation space exhausted");
- FinalStyleRecordID::animation_overlay(self.next_animation_overlay_generation)
- }
-
- fn make_animation_overlay_record(
- &mut self,
- base_style_record: StyleRecordID,
- source_identity: u64,
- animated_overlay: Box<crate::css::animated_overlay::AnimatedOverlay>,
- payloads: &[SharedPayload],
- in_display_none_subtree: Option<bool>,
- ) -> AnimationOverlayRecord {
- assert!(payloads.iter().all(|payload| !payload.is_null()));
- for (index, &payload) in payloads.iter().enumerate() {
- retain_group_payload(index, payload.as_ptr());
- }
- let base = self
- .style_records
- .get_index(base_style_record.index())
- .expect("base style-record is live");
- let mut dependency_flags = self.computed_fixed_metadata.get(base.fixed_metadata).dependency_flags;
- // SAFETY: Published style-group payloads stay live while their records do.
- if unsafe { style_group_payloads_hold_image_values(SharedPayload::as_pointer_slice(payloads)) } {
- dependency_flags |= HOLDS_IMAGE_VALUES;
- }
- if let Some(in_display_none_subtree) = in_display_none_subtree {
- dependency_flags = (dependency_flags & !IN_DISPLAY_NONE_SUBTREE)
- | (u8::from(in_display_none_subtree) * IN_DISPLAY_NONE_SUBTREE);
- }
- AnimationOverlayRecord {
- base_style_record,
- source_identity,
- final_style_record: self.next_animation_overlay_record(),
- animated_overlay: animated_overlay.into(),
- dependency_flags,
- payloads: payloads.into(),
- pin_count: 0,
- is_assigned: true,
- }
- }
-
- fn allocate_animation_overlay(
- &mut self,
- base_style_record: StyleRecordID,
- source_identity: u64,
- animated_overlay: Option<&crate::css::animated_overlay::AnimatedOverlay>,
- payloads: &[SharedPayload],
- in_display_none_subtree: Option<bool>,
- ) -> (u32, FinalStyleRecordID, bool) {
- let record = self.make_animation_overlay_record(
- base_style_record,
- source_identity,
- Box::new(
- animated_overlay
- .expect("animation overlay properties are missing")
- .clone(),
- ),
- payloads,
- in_display_none_subtree,
- );
-
- let final_style_record = record.final_style_record;
- let (slot, slot_allocated) = self.animation_overlay_slots.fill(record);
- self.animation_overlay_slots_by_record.insert(final_style_record, slot);
- self.live_animation_overlay_assignments += 1;
- (slot, final_style_record, slot_allocated)
- }
-
- fn reclaim_animation_overlay_slot(&mut self, slot: u32) {
- let record = self
- .animation_overlay_slots
- .get(slot)
- .expect("animation-overlay slot is live");
- assert!(!record.is_assigned && record.pin_count == 0);
- let final_style_record = self.animation_overlay_slots.retire(slot);
- self.animation_overlay_slots_by_record.remove(&final_style_record);
- self.released_animation_overlay_records.add(final_style_record);
- self.free_retired_animation_overlays();
- }
+ fn reclaim_animation_overlay_slot(&mut self, slot: u32) {
+ let record = self
+ .animation_overlay_slots
+ .get(slot)
+ .expect("animation-overlay slot is live");
+ assert!(!record.is_assigned && record.pin_count == 0 && !record.is_held_elsewhere());
+ let final_style_record = self.animation_overlay_slots.retire(slot);
+ self.animation_overlay_slots_by_record.remove(&final_style_record);
+ self.released_animation_overlay_records.add(final_style_record);
+ self.free_retired_animation_overlays();
+ }
fn release_animation_overlay_assignment(&mut self, slot: u32) {
let record = self
@@ -2108,17 +1374,17 @@ impl ComputedGroupSets {
record.is_assigned = false;
self.live_animation_overlay_assignments -= 1;
if record.pin_count == 0 {
- self.reclaim_animation_overlay_slot(slot);
+ self.reclaim_animation_overlay_slot_unless_held(slot);
}
}
fn update_animation_overlay(
&mut self,
current_slot: Option<u32>,
- base_style_record: StyleRecordID,
+ base: InstalledRecordID,
source_identity: u64,
animated_overlay: Option<&crate::css::animated_overlay::AnimatedOverlay>,
- payloads: &[SharedPayload],
+ payloads: Option<&crate::css::computed_values::StyleGroups>,
in_display_none_subtree: Option<bool>,
) -> AnimationOverlayPublication {
if source_identity == 0 {
@@ -2127,33 +1393,34 @@ impl ComputedGroupSets {
}
return AnimationOverlayPublication {
slot: None,
- final_style_record: self.final_base_style_record(base_style_record),
+ final_style_record: FinalStyleRecordID::installed(base),
slot_allocated: false,
slot_released: current_slot.is_some(),
record_updated: false,
};
}
+ let payloads = payloads.expect("an animation overlay composes groups over its record");
if let Some(slot) = current_slot {
let current = self
.animation_overlay_slots
.get(slot)
.expect("animation-overlay slot is live");
- if current.base_style_record == base_style_record
+ if current.base == base
&& current.source_identity == source_identity
- && current.payloads.as_ref() == payloads
+ && current.record.payloads.holds_the_same_groups_as(payloads)
{
return AnimationOverlayPublication {
slot: Some(slot),
- final_style_record: current.final_style_record,
+ final_style_record: current.final_style_record(),
slot_allocated: false,
slot_released: false,
record_updated: false,
};
}
- if current.pin_count == 0 {
+ if current.pin_count == 0 && !current.is_held_elsewhere() {
let record = self.make_animation_overlay_record(
- base_style_record,
+ base,
source_identity,
Box::new(
animated_overlay
@@ -2164,7 +1431,7 @@ impl ComputedGroupSets {
in_display_none_subtree,
);
- let final_style_record = record.final_style_record;
+ let final_style_record = record.final_style_record();
let retired = self.animation_overlay_slots.replace(slot, record);
self.animation_overlay_slots_by_record.remove(&retired);
self.released_animation_overlay_records.add(retired);
@@ -2182,7 +1449,7 @@ impl ComputedGroupSets {
}
let (slot, final_style_record, slot_allocated) = self.allocate_animation_overlay(
- base_style_record,
+ base,
source_identity,
animated_overlay,
payloads,
@@ -2197,18 +1464,14 @@ impl ComputedGroupSets {
}
}
- fn final_style_record(
- &self,
- base_style_record: StyleRecordID,
- animation_overlay_slot: Option<u32>,
- ) -> FinalStyleRecordID {
+ fn final_style_record(&self, base: InstalledRecordID, animation_overlay_slot: Option<u32>) -> FinalStyleRecordID {
animation_overlay_slot.map_or_else(
- || self.final_base_style_record(base_style_record),
+ || FinalStyleRecordID::installed(base),
|slot| {
self.animation_overlay_slots
.get(slot)
.expect("animation-overlay slot is live")
- .final_style_record
+ .final_style_record()
},
)
}
@@ -2218,34 +1481,23 @@ impl ComputedGroupSets {
target: ComputedStyleTarget,
source_identity: u64,
animated_overlay: HostShared<crate::css::animated_overlay::AnimatedOverlay>,
- payloads: &[SharedPayload],
+ payloads: Option<&crate::css::computed_values::StyleGroups>,
parent_in_display_none_subtree: bool,
) -> Option<AnimationOverlayUpdate> {
- let (base_style_record, current_slot) = self.assigned_record_and_overlay_slot(target)?;
- let previous_style_record = self.final_style_record(base_style_record, current_slot);
+ let (base, current_slot) = self.assigned_record_and_overlay_slot(target)?;
+ let previous_style_record = self.final_style_record(base, current_slot);
let animated_overlay = unsafe { animated_overlay.as_ref() };
- let in_display_none_subtree = self.animation_overlay_in_display_none_subtree(
- base_style_record,
- animated_overlay,
- parent_in_display_none_subtree,
- );
+ let in_display_none_subtree =
+ self.animation_overlay_in_display_none_subtree(base, animated_overlay, parent_in_display_none_subtree);
let publication = self.update_animation_overlay(
current_slot,
- base_style_record,
+ base,
source_identity,
animated_overlay,
payloads,
in_display_none_subtree,
);
- if target.is_pseudo() {
- self.ensure_pseudo_row(target.node, target.pseudo_kind)
- .assignment
- .as_mut()?
- .animation_overlay_slot = publication.slot;
- } else {
- self.columns
- .set_animation_overlay_slot(target.node.element_index()? as usize, publication.slot);
- }
+ self.set_animation_overlay_slot_of(target, publication.slot);
Some(AnimationOverlayUpdate {
previous_style_record,
style_record: publication.final_style_record,
@@ -2256,776 +1508,51 @@ impl ComputedGroupSets {
})
}
- pub(super) fn assigned_underlying_style_record(&self, target: ComputedStyleTarget) -> Option<FinalStyleRecordID> {
- let (base_style_record, _) = self.assigned_record_and_overlay_slot(target)?;
- Some(self.final_base_style_record(base_style_record))
- }
-
- pub(super) fn compose_detached_animation_overlay(
- &mut self,
- installed_style_record: FinalStyleRecordID,
- source_identity: u64,
- animated_overlay: HostShared<crate::css::animated_overlay::AnimatedOverlay>,
- payloads: &[SharedPayload],
- parent_in_display_none_subtree: bool,
- ) -> Option<(AnimationOverlayUpdate, Option<DetachedComposition>)> {
- let base = self.underlying_style_record(installed_style_record)?;
- let base_style_record = base.base_record()?;
- let live_records = self.live_animation_overlay_assignments;
- let unchanged = |style_record| AnimationOverlayUpdate {
- previous_style_record: installed_style_record,
- style_record,
- slot_allocated: false,
- slot_released: false,
- record_updated: false,
- live_records,
- };
- if source_identity == 0 {
- return Some((unchanged(base), None));
- }
- if let Some(&slot) = self.animation_overlay_slots_by_record.get(&installed_style_record)
- && let Some(installed) = self.animation_overlay_slots.get(slot)
- && installed.source_identity == source_identity
- && installed.payloads.as_ref() == payloads
- {
- return Some((unchanged(installed_style_record), None));
- }
- let animated_overlay = unsafe { animated_overlay.as_ref() };
- let in_display_none_subtree = self.animation_overlay_in_display_none_subtree(
- base_style_record,
- animated_overlay,
- parent_in_display_none_subtree,
- );
- let (slot, final_style_record, slot_allocated) = self.allocate_animation_overlay(
- base_style_record,
- source_identity,
- animated_overlay,
- payloads,
- in_display_none_subtree,
- );
- let composition = self.detach_animation_overlay_slot(slot);
- Some((
- AnimationOverlayUpdate {
- previous_style_record: installed_style_record,
- style_record: final_style_record,
- slot_allocated,
- slot_released: false,
- record_updated: true,
- live_records,
- },
- composition,
- ))
- }
-
fn animation_overlay_in_display_none_subtree(
&self,
- base_style_record: StyleRecordID,
+ base: InstalledRecordID,
animated_overlay: Option<&crate::css::animated_overlay::AnimatedOverlay>,
parent_in_display_none_subtree: bool,
) -> Option<bool> {
// The base computed its flag from its own display, which the sampled display overrides.
- self.style_records
- .get_index(base_style_record.index())
- .and_then(|record| record.longhand_table)
- .and_then(|identity| self.computed_longhand_tables.get_index(identity.0 as usize))
- .map(|table| {
- parent_in_display_none_subtree
- || crate::css::style_compute::effective_display(table.table(), animated_overlay).is_none()
- })
+ let longhands = ViewLonghands::of_record(self.installed.get(base)?.record());
+ Some(parent_in_display_none_subtree || longhands.effective_display(animated_overlay).is_none())
}
- #[cfg(test)]
- fn publish_unowned(
- &mut self,
- target: Option<ComputedStyleTarget>,
- payloads: &[SharedPayload],
- inherited_group_count: usize,
- custom_property_environment: u64,
- metadata_input: ComputedMetadataInput<'_>,
- ) -> ComputedGroupPublication {
- self.publish(
- target,
- payloads,
- inherited_group_count,
- custom_property_environment,
- metadata_input,
- PendingRecordOwnership::default(),
- )
+ pub fn pseudo_style_record(&self, node: StyleNodeID, pseudo_kind: u8) -> Option<FinalStyleRecordID> {
+ let row = self.pseudo_row(node, pseudo_kind)?;
+ Some(self.final_style_record(row.installed?, row.installed_overlay_slot))
}
- /// Publishes one record's components. `owned` says which of `payloads`, and whether the
- /// table, the caller hands over; `ComputedGroupPublication::transferred` says which of those
- /// references the catalog took, and the caller releases the rest.
- pub fn publish(
- &mut self,
- target: Option<ComputedStyleTarget>,
- payloads: &[SharedPayload],
- inherited_group_count: usize,
- custom_property_environment: u64,
- metadata_input: ComputedMetadataInput<'_>,
- owned: PendingRecordOwnership,
- ) -> ComputedGroupPublication {
- let ComputedMetadataInput {
- pseudo_element_styles,
- dependency_flags,
- counter_style_environment_identity,
- animation_overlay_identity,
- animated_overlay,
- animation_overlay_payloads,
- longhand_table,
- } = metadata_input;
- let animated_overlay = unsafe { animated_overlay.as_ref() };
- let longhand_table = unsafe { longhand_table.as_ref() };
- let inherited_group_swap_eligible = dependency_flags & INHERITED_GROUP_SWAP_ELIGIBLE != 0;
- let dependency_flags = (dependency_flags & COMPUTED_VALUE_DEPENDENCY_FLAGS)
- | longhand_table.map_or(0, ComputedLonghandTable::dependency_flags);
- assert!(inherited_group_count <= payloads.len());
- let previous_group_set = target.and_then(|target| {
- let ComputedStyleTarget { node, pseudo_kind } = target;
- if target.is_pseudo() {
- self.pseudo_row(node, pseudo_kind)
- .and_then(|row| row.assignment)
- .map(|inputs| inputs.groups)
- } else {
- node.element_index()
- .and_then(|index| self.columns.groups(index as usize))
- }
- });
- let mut new_groups = 0;
- let mut canonical_output_groups_reused = 0;
- let mut transferred = PendingRecordOwnership::default();
- let mut groups = Vec::with_capacity(payloads.len());
- for (index, &payload) in payloads.iter().enumerate() {
- assert!(!payload.is_null(), "computed group payload is null");
- let previous_identity = previous_group_set.and_then(|set| self.sets[set].groups.get(index).copied());
- let previous_equal_identity = previous_identity.filter(|identity| {
- // SAFETY: Published style-group payloads stay live while their records do.
- unsafe { style_group_payloads_equal(index, payload.as_ptr(), self.groups[*identity].payload.as_ptr()) }
- });
- let identity = match previous_equal_identity {
- Some(identity) => {
- if self.groups[identity].payload != payload {
- canonical_output_groups_reused += 1;
- }
- identity
- }
- None => {
- // A new payload's reference moves into the catalog when the caller owns one;
- // a payload that deduplicates leaves it with the caller.
- let owned = owned.groups & (1 << index) != 0;
- let (identity, inserted) = self.intern_group_owned(index, payload, owned);
- if inserted && owned {
- transferred.groups |= 1 << index;
- }
- new_groups += usize::from(inserted);
- identity
- }
- };
- groups.push(identity);
- }
-
- let (identity, new_group_set) = self.intern_group_set(&groups);
-
- let (inherited_identity, new_inherited_group_set) =
- self.intern_inherited_group_set(&groups[..inherited_group_count]);
-
- let (custom_property_environment_identity, new_custom_property_environment) =
- self.intern_custom_property_environment(custom_property_environment);
-
- let (computed_fixed_metadata_identity, new_computed_fixed_metadata) =
- self.intern_fixed_metadata(ComputedFixedMetadata {
- pseudo_element_styles,
- dependency_flags,
- counter_style_environment_identity,
- });
-
- // NB: A recompute allocates fresh value data for many longhands even when nothing changed,
- // so interning by pointer content alone would mint a new table identity - and a new
- // style record - on every recompute. The target's previous table is offered as a
- // canonical candidate and reused when every slot holds an equal value, mirroring how
- // output group payloads canonicalize against the previous group set above.
- let previous_longhand_table = target.and_then(|target| {
- let ComputedStyleTarget { node, pseudo_kind } = target;
- let style_record = if target.is_pseudo() {
- self.pseudo_row(node, pseudo_kind)
- .and_then(|row| row.assignment)
- .map(|inputs| inputs.style_record)
- } else {
- node.element_index()
- .and_then(|index| self.style_record_column.get(index as usize))
- .copied()
- .flatten()
- }?;
- self.style_records.get_index(style_record.index())?.longhand_table
- });
- let canonical_longhand_table = self.sets[identity].canonical_longhand_table;
- let longhand_table_identity = longhand_table.map(|table| {
- let (identity, moved) =
- self.intern_longhand_table_owned(table, previous_longhand_table, canonical_longhand_table, owned.table);
- transferred.table = moved;
- identity
- });
- if self.sets[identity].canonical_longhand_table.is_none() {
- self.sets[identity].canonical_longhand_table = longhand_table_identity;
- }
-
- let style_record = StyleRecord {
- groups: identity,
- inherited_groups: inherited_identity,
- custom_properties: custom_property_environment_identity,
- fixed_metadata: computed_fixed_metadata_identity,
- longhand_table: longhand_table_identity,
- };
- let (style_record_identity, new_style_record) = self.intern_style_record(style_record);
-
- let is_pseudo = target.is_some_and(ComputedStyleTarget::is_pseudo);
- let (
- node_handle_changed,
- inherited_node_handle_changed,
- custom_property_environment_node_handle_changed,
- computed_fixed_metadata_node_handle_changed,
- previous_style_record_identity,
- animation_overlay_publication,
- ) = if let Some(ComputedStyleTarget { node, pseudo_kind }) = target.filter(|target| target.is_pseudo()) {
- let previous = self.pseudo_row(node, pseudo_kind).and_then(|row| row.assignment);
- let previous_style_record_identity = previous
- .map(|previous| self.final_style_record(previous.style_record, previous.animation_overlay_slot));
- let animation_overlay_publication = self.update_animation_overlay(
- previous.and_then(|previous| previous.animation_overlay_slot),
- style_record_identity,
- animation_overlay_identity,
- animated_overlay,
- animation_overlay_payloads,
- None,
- );
- let row = self.ensure_pseudo_row(node, pseudo_kind);
- row.set_published(true);
- row.assignment = Some(PublishedComputedInputs {
- groups: identity,
- inherited_groups: inherited_identity,
- custom_properties: custom_property_environment_identity,
- fixed_metadata: computed_fixed_metadata_identity,
- style_record: style_record_identity,
- animation_overlay_slot: animation_overlay_publication.slot,
- });
- (
- previous.is_none_or(|previous| previous.groups != identity),
- previous.is_none_or(|previous| previous.inherited_groups != inherited_identity),
- previous.is_none_or(|previous| previous.custom_properties != custom_property_environment_identity),
- previous.is_none_or(|previous| previous.fixed_metadata != computed_fixed_metadata_identity),
- previous_style_record_identity,
- animation_overlay_publication,
- )
- } else if let Some(ComputedStyleTarget { node, .. }) = target {
- let index = node.element_index().expect("only elements publish computed groups") as usize;
- self.columns.ensure(index);
- if self.style_record_column.len() <= index {
- self.style_record_column.resize(index + 1, None);
- }
- let previous_style_record_identity = self.style_record_column[index]
- .map(|style_record| self.final_style_record(style_record, self.columns.animation_overlay_slot(index)));
- let animation_overlay_publication = self.update_animation_overlay(
- self.columns.animation_overlay_slot(index),
- style_record_identity,
- animation_overlay_identity,
- animated_overlay,
- animation_overlay_payloads,
- None,
- );
- let changed = (
- self.columns.groups(index) != Some(identity),
- self.columns.inherited_groups(index) != Some(inherited_identity),
- self.columns.custom_properties(index) != Some(custom_property_environment_identity),
- self.columns.fixed_metadata(index) != Some(computed_fixed_metadata_identity),
- previous_style_record_identity,
- animation_overlay_publication,
- );
- self.columns.publish(
- index,
- PublishedComputedInputs {
- groups: identity,
- inherited_groups: inherited_identity,
- custom_properties: custom_property_environment_identity,
- fixed_metadata: computed_fixed_metadata_identity,
- style_record: style_record_identity,
- animation_overlay_slot: animation_overlay_publication.slot,
- },
- inherited_group_swap_eligible,
- );
- self.style_record_column[index] = Some(style_record_identity);
- changed
- } else {
- assert_eq!(
- animation_overlay_identity, 0,
- "unassigned style records cannot own animation overlays"
- );
- (
- false,
- false,
- false,
- false,
- None,
- AnimationOverlayPublication {
- slot: None,
- final_style_record: self.final_base_style_record(style_record_identity),
- slot_allocated: false,
- slot_released: false,
- record_updated: false,
- },
- )
- };
- let final_style_record_identity = animation_overlay_publication.final_style_record;
- let style_record_node_handle_changed =
- target.is_some() && previous_style_record_identity != Some(final_style_record_identity);
- ComputedGroupPublication {
- previous_style_record_identity,
- style_record_identity: final_style_record_identity,
- new_groups,
- canonical_output_groups_reused,
- new_group_set,
- new_inherited_group_set,
- new_custom_property_environment,
- new_computed_fixed_metadata,
- new_style_record,
- node_handle_changed,
- inherited_node_handle_changed,
- custom_property_environment_node_handle_changed,
- computed_fixed_metadata_node_handle_changed,
- style_record_node_handle_changed,
- animation_overlay_slot_allocated: animation_overlay_publication.slot_allocated,
- animation_overlay_slot_released: animation_overlay_publication.slot_released,
- animation_overlay_record_updated: animation_overlay_publication.record_updated,
- live_animation_overlay_records: self.live_animation_overlay_assignments,
- is_pseudo,
- transferred,
- }
+ /// Each record a pseudo-element holds, with the node it belongs to.
+ pub(super) fn pseudo_style_records(&self) -> impl Iterator<Item = (StyleNodeID, FinalStyleRecordID)> + '_ {
+ self.pseudo_rows_by_node.iter().flat_map(move |(&node, rows)| {
+ rows.iter().filter_map(move |row| {
+ Some((
+ node,
+ self.final_style_record(row.installed?, row.installed_overlay_slot),
+ ))
+ })
+ })
}
-
- pub(super) fn style_record_for_shared_assignment(
- &self,
- target: ComputedStyleTarget,
- raw_style_record: u64,
- ) -> Option<FinalStyleRecordID> {
- let final_style_record = FinalStyleRecordID(raw_style_record);
- let requested_style_record_identity = final_style_record.base_record()?;
- assert!(
- self.style_record_generation_is_live(requested_style_record_identity, final_style_record.base_generation()),
- "base style-record is not live"
- );
- let previous_base_style_record_identity = if target.is_pseudo() {
- self.pseudo_row(target.node, target.pseudo_kind)
- .and_then(|row| row.assignment)
- .map(|assignment| assignment.style_record)
- } else {
- target
- .node
- .element_index()
- .and_then(|index| self.style_record_column.get(index as usize))
- .copied()
- .flatten()
- };
- // A regular publication canonicalizes every freshly produced group and longhand table
- // against the target's previous record. A shared record was canonicalized against its
- // donor instead, so preserve the target's identity when both records carry equal values.
- // This keeps a no-op recompute from looking like a layout-affecting style change.
- let style_record_identity = previous_base_style_record_identity
- .filter(|&previous| self.style_records_equal_by_value(previous, requested_style_record_identity))
- .unwrap_or(requested_style_record_identity);
- Some(self.final_base_style_record(style_record_identity))
+ /// The pseudo-element kinds this node holds published computed styles for.
+ pub fn assigned_pseudo_kinds(&self, node: StyleNodeID) -> impl Iterator<Item = u8> + '_ {
+ self.pseudo_rows(node)
+ .iter()
+ .filter_map(|row| row.published.then_some(row.kind))
}
- pub fn assign_shared_style_record(
- &mut self,
- target: ComputedStyleTarget,
- raw_style_record: u64,
- inherited_group_count: usize,
- inherited_group_swap_eligible: bool,
- ) -> Option<ComputedGroupPublication> {
- let style_record_identity = self
- .style_record_for_shared_assignment(target, raw_style_record)?
- .base_record()
- .expect("a shared style record must be a base record");
- let record = *self.style_records.get_index(style_record_identity.index())?;
- // The inherited subset is immutable along with the complete style record. Sharing a
- // record must not reconstruct its group identities and intern the same subset again.
- let inherited_identity = record.inherited_groups;
- assert_eq!(self.inherited_sets[inherited_identity].len(), inherited_group_count);
-
- let is_pseudo = target.is_pseudo();
- let (
- node_handle_changed,
- inherited_node_handle_changed,
- custom_property_environment_node_handle_changed,
- computed_fixed_metadata_node_handle_changed,
- previous_style_record_identity,
- animation_overlay_publication,
- ) = if target.is_pseudo() {
- let previous = self
- .pseudo_row(target.node, target.pseudo_kind)
- .and_then(|row| row.assignment);
- let previous_style_record_identity = previous
- .map(|previous| self.final_style_record(previous.style_record, previous.animation_overlay_slot));
- let animation_overlay_publication = self.update_animation_overlay(
- previous.and_then(|previous| previous.animation_overlay_slot),
- style_record_identity,
- 0,
- None,
- &[],
- None,
- );
- let row = self.ensure_pseudo_row(target.node, target.pseudo_kind);
- row.set_published(true);
- row.assignment = Some(PublishedComputedInputs {
- groups: record.groups,
- inherited_groups: inherited_identity,
- custom_properties: record.custom_properties,
- fixed_metadata: record.fixed_metadata,
- style_record: style_record_identity,
- animation_overlay_slot: None,
- });
- (
- previous.is_none_or(|previous| previous.groups != record.groups),
- previous.is_none_or(|previous| previous.inherited_groups != inherited_identity),
- previous.is_none_or(|previous| previous.custom_properties != record.custom_properties),
- previous.is_none_or(|previous| previous.fixed_metadata != record.fixed_metadata),
- previous_style_record_identity,
- animation_overlay_publication,
- )
- } else {
- let index = target
- .node
- .element_index()
- .expect("only elements publish computed groups") as usize;
- self.columns.ensure(index);
- if self.style_record_column.len() <= index {
- self.style_record_column.resize(index + 1, None);
- }
- let previous_style_record_identity = self.style_record_column[index]
- .map(|style_record| self.final_style_record(style_record, self.columns.animation_overlay_slot(index)));
- let animation_overlay_publication = self.update_animation_overlay(
- self.columns.animation_overlay_slot(index),
- style_record_identity,
- 0,
- None,
- &[],
- None,
- );
- let changed = (
- self.columns.groups(index) != Some(record.groups),
- self.columns.inherited_groups(index) != Some(inherited_identity),
- self.columns.custom_properties(index) != Some(record.custom_properties),
- self.columns.fixed_metadata(index) != Some(record.fixed_metadata),
- previous_style_record_identity,
- animation_overlay_publication,
- );
- self.columns.publish(
- index,
- PublishedComputedInputs {
- groups: record.groups,
- inherited_groups: inherited_identity,
- custom_properties: record.custom_properties,
- fixed_metadata: record.fixed_metadata,
- style_record: style_record_identity,
- animation_overlay_slot: None,
- },
- inherited_group_swap_eligible,
- );
- self.style_record_column[index] = Some(style_record_identity);
- changed
- };
-
- Some(ComputedGroupPublication {
- previous_style_record_identity,
- style_record_identity: animation_overlay_publication.final_style_record,
- new_groups: 0,
- canonical_output_groups_reused: 0,
- new_group_set: false,
- new_inherited_group_set: false,
- new_custom_property_environment: false,
- new_computed_fixed_metadata: false,
- new_style_record: false,
- node_handle_changed,
- inherited_node_handle_changed,
- custom_property_environment_node_handle_changed,
- computed_fixed_metadata_node_handle_changed,
- style_record_node_handle_changed: previous_style_record_identity
- != Some(animation_overlay_publication.final_style_record),
- animation_overlay_slot_allocated: false,
- animation_overlay_slot_released: animation_overlay_publication.slot_released,
- animation_overlay_record_updated: false,
- live_animation_overlay_records: self.live_animation_overlay_assignments,
- is_pseudo,
- transferred: PendingRecordOwnership::default(),
- })
+ fn longhands_for_target(&self, target: ComputedStyleTarget) -> Option<ViewLonghands<'_>> {
+ let installed = self.installed(self.assigned_final_style_record(target)?)?;
+ Some(ViewLonghands::of_record(installed.record()))
}
-
- fn style_records_equal_by_value(&self, first: StyleRecordID, second: StyleRecordID) -> bool {
- if first == second {
- return true;
- }
- let Some(first) = self.style_records.get_index(first.index()) else {
- return false;
- };
- let Some(second) = self.style_records.get_index(second.index()) else {
- return false;
- };
- if first.custom_properties != second.custom_properties
- || first.fixed_metadata != second.fixed_metadata
- || self.inherited_sets[first.inherited_groups].len() != self.inherited_sets[second.inherited_groups].len()
- {
- return false;
- }
- if first.groups != second.groups {
- let first_groups = &self.sets[first.groups].payloads;
- let second_groups = &self.sets[second.groups].payloads;
- if first_groups.len() != second_groups.len()
- || first_groups
- .iter()
- .zip(second_groups.iter())
- .enumerate()
- .any(|(index, (&first, &second))| {
- // SAFETY: Published style-group payloads stay live while their records do.
- first != second
- && !unsafe { style_group_payloads_equal(index, first.as_ptr(), second.as_ptr()) }
- })
- {
- return false;
- }
- }
- match (first.longhand_table, second.longhand_table) {
- (None, None) => true,
- (Some(first), Some(second)) if first == second => true,
- (Some(first), Some(second)) => self.computed_longhand_tables[first]
- .table()
- .publication_equals(self.computed_longhand_tables[second].table()),
- _ => false,
- }
- }
-
- pub fn set_pending_cascade_state(&mut self, target: ComputedStyleTarget, state: (u64, CascadeStateID)) {
- if !target.is_pseudo() {
- self.pending_cascade_states.insert(target.node, state);
- return;
- }
- self.ensure_pseudo_row(target.node, target.pseudo_kind)
- .replace_cascade_state(PseudoComputedRow::PENDING_CASCADE, Some(state));
- }
-
- pub fn take_pending_cascade_state(&mut self, target: ComputedStyleTarget) -> Option<(u64, CascadeStateID)> {
- if !target.is_pseudo() {
- return self.pending_cascade_states.remove(&target.node);
- }
- let state = self
- .pseudo_row_mut(target.node, target.pseudo_kind)
- .and_then(|row| row.replace_cascade_state(PseudoComputedRow::PENDING_CASCADE, None));
- self.remove_empty_pseudo_row(target.node, target.pseudo_kind);
- state
- }
-
- #[must_use]
- pub fn cascade_state(&self, target: ComputedStyleTarget) -> Option<(u64, CascadeStateID)> {
- if target.is_pseudo() {
- return self
- .pseudo_row(target.node, target.pseudo_kind)?
- .cascade_state(PseudoComputedRow::CURRENT_CASCADE);
- }
- target
- .node
- .element_index()
- .and_then(|index| self.columns.cascade_state(index as usize))
- }
-
- /// The cascade state of the record a target is being installed with: the pending one until
- /// the host acknowledges the record, the current one after.
- pub fn installing_cascade_state(&self, target: ComputedStyleTarget) -> Option<(u64, CascadeStateID)> {
- if target.is_pseudo() {
- let row = self.pseudo_row(target.node, target.pseudo_kind)?;
- return row
- .cascade_state(PseudoComputedRow::PENDING_CASCADE)
- .or_else(|| row.cascade_state(PseudoComputedRow::CURRENT_CASCADE));
- }
- self.pending_cascade_states
- .get(&target.node)
- .copied()
- .or_else(|| self.cascade_state(target))
- }
-
- pub fn pseudo_retained_cascade_states(
- &self,
- node: StyleNodeID,
- ) -> impl Iterator<Item = (u8, (u64, CascadeStateID))> + '_ {
- self.pseudo_rows(node).iter().filter_map(|row| {
- row.cascade_state(PseudoComputedRow::RETAINED_CASCADE)
- .map(|state| (row.kind, state))
- })
- }
-
- #[must_use]
- pub fn pseudo_retained_cascade_state(&self, node: StyleNodeID, pseudo_kind: u8) -> Option<(u64, CascadeStateID)> {
- self.pseudo_row(node, pseudo_kind)?
- .cascade_state(PseudoComputedRow::RETAINED_CASCADE)
- }
-
- /// Whether every inherited group the node holds is the parent's very group: the record was
- /// computed against this parent's inherited style, and nothing under the parent's change is
- /// left to inherit.
- #[must_use]
- pub fn inherited_groups_follow_parent(&self, node: StyleNodeID, parent: StyleNodeID) -> Option<bool> {
- let node_set = self.columns.groups(node.element_index()? as usize)?;
- let parent_set = self.columns.groups(parent.element_index()? as usize)?;
- if node_set == parent_set {
- return Some(true);
- }
- let node_groups = &self.sets[node_set].payloads;
- let parent_groups = &self.sets[parent_set].payloads;
- // C++ and Rust can intern equal payloads under different group identities. Inheritance
- // follows the parent's value in that case just as it does after group reclamation.
- Some((0..ENGINE_INHERITED_GROUP_COUNT).all(|group| {
- let node_payload = node_groups[group];
- let parent_payload = parent_groups[group];
- node_payload == parent_payload
- // SAFETY: Published style-group payloads stay live while their records do.
- || unsafe { crate::css::computed_values::style_group_payloads_equal(
- group,
- node_payload.as_ptr(),
- parent_payload.as_ptr(),
- ) }
- }))
- }
-
- /// Whether what a record gives its element's pseudo-elements to inherit is the inherited groups
- /// of its base record: always for a base record, and for an animation overlay whose sampled
- /// values left those groups as they were.
- #[must_use]
- pub(super) fn record_inherits_as_its_base(&self, record: FinalStyleRecordID) -> bool {
- if record.base_record().is_some() {
- return true;
- }
- let Some(overlay) = self
- .animation_overlay_slots_by_record
- .get(&record)
- .and_then(|&slot| self.animation_overlay_slots.get(slot))
- else {
- return false;
- };
- let Some(base) = self.style_records.get_index(overlay.base_style_record.index()) else {
- return false;
- };
- let base_groups = &self.sets[base.groups].payloads;
- (0..ENGINE_INHERITED_GROUP_COUNT).all(|group| {
- let sampled = overlay.payloads[group];
- sampled == base_groups[group]
- // SAFETY: Published style-group payloads stay live while their records do.
- || unsafe { crate::css::computed_values::style_group_payloads_equal(
- group,
- sampled.as_ptr(),
- base_groups[group].as_ptr(),
- ) }
- })
- }
-
- /// Whether a record's inherited groups, past the ones in `own_groups` that its own
- /// declarations rebuild, are the node's own inherited groups: what a record derived under the
- /// node as its parent must hold, whatever identities the two were keyed by when the record
- /// was derived.
- #[must_use]
- pub fn style_record_inherits_from_node(&self, raw_style_record: u64, node: StyleNodeID, own_groups: u32) -> bool {
- let Some(record) = FinalStyleRecordID(raw_style_record)
- .base_record()
- .and_then(|base| self.style_records.get_index(base.index()).copied())
- else {
- return false;
- };
- let Some(node_set) = node
- .element_index()
- .and_then(|index| self.columns.groups(index as usize))
- else {
- return false;
- };
- if record.groups == node_set {
- return true;
- }
- // Reclamation interns an equal payload under a new identity, so the groups compare by
- // content past their identities.
- let record_groups = &self.sets[record.groups].payloads;
- let node_groups = &self.sets[node_set].payloads;
- (0..ENGINE_INHERITED_GROUP_COUNT).all(|group| {
- if own_groups & (1 << group) != 0 {
- return true;
- }
- let record_payload = record_groups[group];
- let node_payload = node_groups[group];
- record_payload == node_payload
- // SAFETY: Published style-group payloads stay live while their records do.
- || unsafe { crate::css::computed_values::style_group_payloads_equal(
- group,
- record_payload.as_ptr(),
- node_payload.as_ptr(),
- ) }
- })
- }
-
- /// The record a pseudo-element of the node holds, with its animation overlay if any.
- #[must_use]
- /// Whether the node holds a row for any of its pseudo-elements, a record or the state one was
- /// computed from.
- pub(super) fn has_pseudo_rows(&self, node: StyleNodeID) -> bool {
- !self.pseudo_rows(node).is_empty()
- }
-
- pub fn pseudo_style_record(&self, node: StyleNodeID, pseudo_kind: u8) -> Option<FinalStyleRecordID> {
- let assignment = self.pseudo_row(node, pseudo_kind)?.assignment.as_ref()?;
- Some(self.final_style_record(assignment.style_record, assignment.animation_overlay_slot))
- }
-
- /// Each record a pseudo-element holds, with the node it belongs to.
- pub(super) fn pseudo_style_records(&self) -> impl Iterator<Item = (StyleNodeID, FinalStyleRecordID)> + '_ {
- self.pseudo_rows_by_node.iter().flat_map(move |(&node, rows)| {
- rows.iter().filter_map(move |row| {
- let assignment = row.assignment.as_ref()?;
- Some((
- node,
- self.final_style_record(assignment.style_record, assignment.animation_overlay_slot),
- ))
- })
- })
- }
-
- /// The pseudo-element kinds this node holds published computed styles for.
- pub fn assigned_pseudo_kinds(&self, node: StyleNodeID) -> impl Iterator<Item = u8> + '_ {
- self.pseudo_rows(node)
- .iter()
- .filter_map(|row| row.is_published().then_some(row.kind))
- }
-
- #[cfg(test)]
- pub fn record_pseudo_kind_for_test(&mut self, node: StyleNodeID, pseudo_kind: u8) {
- self.ensure_pseudo_row(node, pseudo_kind).set_published(true);
- }
-
- fn longhand_table_for_target(&self, target: ComputedStyleTarget) -> Option<&ComputedLonghandTable> {
- let style_record = if target.is_pseudo() {
- self.pseudo_row(target.node, target.pseudo_kind)
- .and_then(|row| row.assignment)
- .map(|assignment| assignment.style_record)
- } else {
- target
- .node
- .element_index()
- .and_then(|index| self.style_record_column.get(index as usize))
- .copied()
- .flatten()
- }?;
- let table = self.style_records.get_index(style_record.index())?.longhand_table?;
- Some(self.computed_longhand_tables[table].table())
- }
-
- fn specified_value_dependency_mask(
- table: &ComputedLonghandTable,
+ /// The groups whose values read, from `values`, the recorded specified values of the longhands
+ /// whose computed values depend on what the element inherits, one that `depends_on_input`.
+ pub(super) fn specified_value_dependency_mask_of<'a>(
+ values: impl Iterator<Item = (u16, &'a RetainedStyleValueData)>,
depends_on_input: impl Fn(&RetainedStyleValueData) -> bool,
) -> u32 {
- table
- .retained_inheritance_dependent_values()
+ values
.filter(|(_, value)| depends_on_input(value))
// Logical aliases retain their specified values but own no output payload. Their
// resolved physical longhands are recorded separately and name the actual group.
@@ -3033,741 +1560,184 @@ impl ComputedGroupSets {
.fold(0, |mask, groups| mask | groups)
}
- fn specified_value_dependency_properties(
- table: &ComputedLonghandTable,
- depends_on_input: impl Fn(&RetainedStyleValueData) -> bool,
- ) -> Option<[u64; crate::css::property_metadata::LONGHAND_WORD_COUNT]> {
- let mut properties = [0u64; crate::css::property_metadata::LONGHAND_WORD_COUNT];
- for (property, value) in table.retained_inheritance_dependent_values() {
- if !depends_on_input(value) {
- continue;
- }
- let index = usize::from(property.checked_sub(crate::css::property_metadata::FIRST_LONGHAND_PROPERTY_ID)?);
- if index >= crate::css::property_metadata::NUMBER_OF_LONGHAND_PROPERTIES {
- return None;
- }
- properties[index / 64] |= 1 << (index % 64);
- }
- Some(properties)
- }
-
/// The groups whose previous specified values actually read `currentColor` while computing.
/// Missing dependency coverage stays typed so a color winner change can widen safely.
#[must_use]
pub fn current_color_dependency_mask(&self, target: ComputedStyleTarget) -> Option<u32> {
- Some(Self::specified_value_dependency_mask(
- self.longhand_table_for_target(target)?,
- retained_value_depends_on_current_color,
- ))
- }
-
- /// The longhands whose previous specified values actually read `currentColor`.
- #[must_use]
- pub fn current_color_dependency_properties(
- &self,
- target: ComputedStyleTarget,
- ) -> Option<[u64; crate::css::property_metadata::LONGHAND_WORD_COUNT]> {
- Self::specified_value_dependency_properties(
- self.longhand_table_for_target(target)?,
- retained_value_depends_on_current_color,
- )
- }
-
- /// Read dependencies from a retained record even if its original node has been restyled.
- pub(crate) fn record_current_color_dependencies(
- &self,
- record: FinalStyleRecordID,
- ) -> Option<(u32, [u64; crate::css::property_metadata::LONGHAND_WORD_COUNT])> {
- let view = self.style_record_view(record.raw())?;
- let table = view.longhand_table?;
- Some((
- Self::specified_value_dependency_mask(table, retained_value_depends_on_current_color),
- Self::specified_value_dependency_properties(table, retained_value_depends_on_current_color)?,
- ))
- }
-
- /// The groups whose previous specified values read the effective color scheme.
- #[must_use]
- pub fn color_scheme_dependency_mask(&self, target: ComputedStyleTarget) -> Option<u32> {
- Some(Self::specified_value_dependency_mask(
- self.longhand_table_for_target(target)?,
- retained_value_depends_on_color_scheme,
- ))
- }
-
- /// The groups whose previous specified values may read font metrics.
- #[must_use]
- pub fn font_dependency_mask(&self, target: ComputedStyleTarget) -> Option<u32> {
- Some(Self::specified_value_dependency_mask(
- self.longhand_table_for_target(target)?,
- retained_value_may_depend_on_font_metrics,
- ))
- }
-
- /// Whether a raw final record identity still names a live base record.
- pub fn final_style_record_is_live(&self, raw_style_record: u64) -> bool {
- let final_style_record = FinalStyleRecordID(raw_style_record);
- final_style_record
- .base_record()
- .is_some_and(|record| self.style_record_generation_is_live(record, final_style_record.base_generation()))
- }
-
- /// The raw custom-property environment identity behind a node's record.
- pub fn custom_property_environment_identity(&self, node: StyleNodeID) -> Option<u64> {
- let index = node.element_index()? as usize;
- let identity = self.columns.custom_properties(index)?;
- Some(self.custom_property_environments[identity])
- }
-
- /// The dense identity of a raw custom-property environment identity, and whether it is new.
- fn intern_custom_property_environment(
- &mut self,
- custom_property_environment: u64,
- ) -> (CustomPropertyEnvironmentID, bool) {
- let custom_property_environment_hash = content_hash(custom_property_environment);
- match self
- .custom_property_environments
- .find(custom_property_environment_hash, |_identity, candidate| {
- *candidate == custom_property_environment
- }) {
- Some(identity) => (identity, false),
- None => {
- let identity = self
- .custom_property_environments
- .take_free_identity()
- .unwrap_or_else(|| {
- CustomPropertyEnvironmentID(
- u32::try_from(self.custom_property_environments.len())
- .expect("custom-property environment identity space exhausted"),
- )
- });
- self.custom_property_environments.insert(
- custom_property_environment_hash,
- identity,
- custom_property_environment,
- );
- (identity, true)
- }
- }
- }
-
- /// Move a node's engine-computed record to another custom-property environment, keeping
- /// everything else it holds: the record a warm delta publishes when only the environment
- /// its custom declarations resolve to moved.
- pub(super) fn republish_engine_record_with_environment(
- &mut self,
- node: StyleNodeID,
- environment: u64,
- ) -> Option<(FinalStyleRecordID, FinalStyleRecordID)> {
- let old_style_record = self.assigned_style_record(node)?;
- let new_style_record = self.republish_style_record_with_environment(node, old_style_record, environment)?;
- Some((old_style_record, new_style_record))
- }
-
- /// Move `style_record`, a record of `node`'s, to another custom-property environment, keeping
- /// everything else it holds; one its animations compose has no base record to move. The node's
- /// assignment moves with it where it is `style_record`: a newer one, which a row the host has
- /// yet to apply installs, is that row's.
- pub(super) fn republish_style_record_with_environment(
- &mut self,
- node: StyleNodeID,
- style_record: FinalStyleRecordID,
- environment: u64,
- ) -> Option<FinalStyleRecordID> {
- let index = node.element_index()? as usize;
- let old_record = *self.style_records.get_index(style_record.base_record()?.index())?;
- let custom_properties = self.intern_custom_property_environment(environment).0;
- if custom_properties == old_record.custom_properties {
- return Some(style_record);
- }
- let new_record = StyleRecord {
- custom_properties,
- ..old_record
- };
- let new_style_record = self.intern_style_record(new_record).0;
- if self.assigned_style_record(node) == Some(style_record) {
- self.columns.custom_properties[index] = custom_properties.0;
- self.style_record_column[index] = Some(new_style_record);
- }
- Some(self.final_base_style_record(new_style_record))
- }
-
- /// Every raw custom-property environment identity a live record was published with.
- pub fn live_custom_property_environments(&self) -> impl Iterator<Item = u64> + '_ {
- self.custom_property_environments
- .live_identities()
- .map(|identity| *self.custom_property_environments.get(identity))
- }
-
- /// The raw custom-property environment identity a record was published with. An animation overlay record animates
- /// no custom property, and holds the environment of the base record it composes over.
- pub fn style_record_custom_property_environment(&self, raw_style_record: u64) -> Option<u64> {
- let record = FinalStyleRecordID(raw_style_record);
- let base = record
- .base_record()
- .or_else(|| self.overlay_base_style_record(record))?;
- let record = self.style_records.get_index(base.index())?;
- Some(self.custom_property_environments[record.custom_properties])
- }
-
- pub fn set_adjustment_facts(&mut self, node: StyleNodeID, facts: u32) {
- let Some(index) = node.element_index().map(|index| index as usize) else {
- return;
- };
- self.columns.ensure(index);
- self.columns.adjustment_facts[index] = facts;
- }
-
- pub fn set_construction_facts(&mut self, node: StyleNodeID, facts: u32) {
- let Some(index) = node.element_index().map(|index| index as usize) else {
- return;
- };
- self.columns.ensure(index);
- self.columns.construction_facts[index] = facts;
- }
-
- /// The identity of the inherited groups a node's published style carries.
- pub(super) fn node_inherited_groups_identity(&self, node: StyleNodeID) -> Option<u32> {
- let index = node.element_index()? as usize;
- self.columns.inherited_groups(index).map(|identity| identity.0)
- }
-
- /// Whether the node's assignment may take an inherited-group swap.
- /// Whether the node's last published match answer declared past its winners (custom
- /// properties, `all`): a record computed from it is no function of a winner state.
- pub(super) fn node_answer_is_incomplete(&self, node: StyleNodeID) -> bool {
- node.element_index()
- .is_some_and(|index| self.columns.answer_is_incomplete(index as usize))
- }
-
- pub(super) fn set_node_answer_incomplete(&mut self, node: StyleNodeID, incomplete: bool) {
- if let Some(index) = node.element_index() {
- self.columns.set_answer_incomplete(index as usize, incomplete);
- }
- }
-
- /// Record the element-backed pseudo-element kind the element stands for, one plus the kind,
- /// or zero for none.
- pub fn set_associated_pseudo_kind(&mut self, node: StyleNodeID, pseudo_kind_plus_one: u8) {
- let Some(index) = node.element_index().map(|index| index as usize) else {
- return;
- };
- self.columns.ensure(index);
- self.columns.associated_pseudo_kinds[index] = pseudo_kind_plus_one;
- }
-
- /// The element-backed pseudo-element kind the element stands for.
- pub(super) fn associated_pseudo_kind(&self, node: StyleNodeID) -> Option<u8> {
- node.element_index()
- .and_then(|index| self.columns.associated_pseudo_kinds.get(index as usize))
- .copied()
- .and_then(|kind| kind.checked_sub(1))
- }
-
- /// The synthetic pseudo-elements the node's last published match answer has rules for.
- pub(super) fn node_pseudo_style_mask(&self, node: StyleNodeID) -> Option<u64> {
- let index = node.element_index()? as usize;
- let flags = *self.columns.flags.get(index)?;
- (flags & PublishedComputedColumns::HAS_PSEUDO_STYLE_MASK != 0).then(|| self.columns.pseudo_style_masks[index])
- }
-
- /// Keep the mask of the answer just published for the node; `None` when that answer cannot
- /// say, so no earlier answer's mask stands in for it.
- pub(super) fn set_node_pseudo_style_mask(&mut self, node: StyleNodeID, mask: Option<u64>) {
- let Some(index) = node.element_index().map(|index| index as usize) else {
- return;
- };
- if let Some(mask) = mask {
- self.columns.ensure(index);
- self.columns.pseudo_style_masks[index] = mask;
- self.columns.flags[index] |= PublishedComputedColumns::HAS_PSEUDO_STYLE_MASK;
- } else if let Some(flags) = self.columns.flags.get_mut(index) {
- *flags &= !PublishedComputedColumns::HAS_PSEUDO_STYLE_MASK;
- }
- }
-
- pub(super) fn node_has_animation_overlay(&self, node: StyleNodeID) -> bool {
- let Some(index) = node.element_index().map(|index| index as usize) else {
- return false;
- };
- self.columns.animation_overlay_slot(index).is_some()
- || self
- .assigned_style_record(node)
- .and_then(|record| self.style_record_view(record.raw()))
- .is_some_and(|view| view.animated_overlay.is_some())
- }
-
- pub(super) fn node_inherited_group_swap_eligible(&self, node: StyleNodeID) -> bool {
- node.element_index()
- .is_some_and(|index| self.columns.inherited_group_swap_eligible(index as usize))
- }
-
- pub fn adjustment_facts(&self, node: StyleNodeID) -> u32 {
- node.element_index()
- .and_then(|index| self.columns.adjustment_facts.get(index as usize))
- .copied()
- .unwrap_or(0)
- }
-
- pub fn construction_facts(&self, node: StyleNodeID) -> u32 {
- node.element_index()
- .and_then(|index| self.columns.construction_facts.get(index as usize))
- .copied()
- .unwrap_or(0)
- }
-
- pub fn set_box_kind(&mut self, node: StyleNodeID, box_kind: ElementBoxKind) {
- let Some(index) = node.element_index().map(|index| index as usize) else {
- return;
- };
- self.columns.ensure(index);
- self.columns.box_kinds[index] = box_kind;
- }
-
- pub fn box_kind(&self, node: StyleNodeID) -> ElementBoxKind {
- node.element_index()
- .and_then(|index| self.columns.box_kinds.get(index as usize))
- .copied()
- .unwrap_or_default()
- }
-
- pub fn bind_cascade_state(
- &mut self,
- target: ComputedStyleTarget,
- cascade_state: (u64, CascadeStateID),
- ) -> Option<(u64, CascadeStateID)> {
- if target.is_pseudo() {
- let row = self.ensure_pseudo_row(target.node, target.pseudo_kind);
- assert!(
- row.assignment.is_some(),
- "a pseudo style must be published before its cascade state is bound"
- );
- return row.replace_cascade_state(PseudoComputedRow::CURRENT_CASCADE, Some(cascade_state));
- }
- let index = target
- .node
- .element_index()
- .expect("only elements publish computed groups") as usize;
- debug_assert!(index < self.columns.flags.len());
- self.columns.replace_cascade_state(index, Some(cascade_state))
- }
-
- /// Forget the exact cascade state behind a style published through a path that did not run the
- /// cascade, so a later comparison cannot use the state behind an older publication.
- pub fn clear_cascade_state(&mut self, target: ComputedStyleTarget) {
- if target.is_pseudo() {
- if let Some(row) = self.pseudo_row_mut(target.node, target.pseudo_kind) {
- row.replace_cascade_state(PseudoComputedRow::CURRENT_CASCADE, None);
- row.replace_cascade_state(PseudoComputedRow::RETAINED_CASCADE, None);
- }
- self.remove_empty_pseudo_row(target.node, target.pseudo_kind);
- return;
- }
- let Some(index) = target.node.element_index().map(|index| index as usize) else {
- return;
- };
- self.columns.replace_cascade_state(index, None);
- }
-
- pub fn remove(&mut self, node: StyleNodeID) {
- self.remove_assignments(node, PublishedComputedColumns::remove);
- }
-
- /// Drop everything assigned to the node, keeping what the host and its match answer published
- /// for it.
- fn unassign(&mut self, node: StyleNodeID) {
- self.remove_assignments(node, PublishedComputedColumns::unassign);
- }
-
- fn remove_assignments(
- &mut self,
- node: StyleNodeID,
- clear_columns: fn(&mut PublishedComputedColumns, usize) -> Option<u32>,
- ) {
- let Some(index) = node.element_index().map(|index| index as usize) else {
- return;
- };
- if let Some(slot) = self.style_record_column.get_mut(index) {
- *slot = None;
- }
- if let Some(slot) = clear_columns(&mut self.columns, index) {
- self.release_animation_overlay_assignment(slot);
- }
- self.pending_cascade_states.remove(&node);
- if let Some(rows) = self.pseudo_rows_by_node.remove(&node) {
- for row in rows.into_vec() {
- if let Some(slot) = row.assignment.and_then(|assignment| assignment.animation_overlay_slot) {
- self.release_animation_overlay_assignment(slot);
- }
- }
- }
- }
-
- pub fn remove_pseudo(&mut self, node: StyleNodeID, pseudo_kind: u8) -> Option<FinalStyleRecordID> {
- let row = self.pseudo_row_mut(node, pseudo_kind)?;
- let removed = row.assignment.take()?;
- row.set_published(false);
- row.replace_cascade_state(PseudoComputedRow::PENDING_CASCADE, None);
- let final_style_record = self.final_style_record(removed.style_record, removed.animation_overlay_slot);
- if let Some(slot) = removed.animation_overlay_slot {
- self.release_animation_overlay_assignment(slot);
- }
- self.remove_empty_pseudo_row(node, pseudo_kind);
- Some(final_style_record)
- }
-
- pub fn observe_absent_pseudo_cascade_state(&mut self, target: ComputedStyleTarget, state: (u64, CascadeStateID)) {
- debug_assert!(target.is_pseudo());
- self.ensure_pseudo_row(target.node, target.pseudo_kind)
- .replace_cascade_state(PseudoComputedRow::CURRENT_CASCADE, Some(state));
- }
-
- pub fn observe_pseudo_retained_cascade_state(
- &mut self,
- target: ComputedStyleTarget,
- state: Option<(u64, CascadeStateID)>,
- ) {
- debug_assert!(target.is_pseudo());
- self.ensure_pseudo_row(target.node, target.pseudo_kind)
- .replace_cascade_state(PseudoComputedRow::RETAINED_CASCADE, state);
- self.remove_empty_pseudo_row(target.node, target.pseudo_kind);
- }
-
- #[must_use]
- pub fn live_animation_overlay_records(&self) -> usize {
- self.live_animation_overlay_assignments
- }
-
- fn reachability(&self) -> ComputedReachability {
- let mut reachable = ComputedReachability {
- groups: vec![false; self.groups.len()],
- sets: vec![false; self.sets.len()],
- inherited_sets: vec![false; self.inherited_sets.len()],
- custom_property_environments: vec![false; self.custom_property_environments.len()],
- fixed_metadata: vec![false; self.computed_fixed_metadata.len()],
- longhand_tables: vec![false; self.computed_longhand_tables.len()],
- style_records: vec![false; self.style_records.len()],
- };
-
- {
- let mut mark_style_record = |identity: StyleRecordID| {
- ComputedReachability::mark(&mut reachable.style_records, identity);
- let record = self.style_records.get(identity);
- ComputedReachability::mark(&mut reachable.sets, record.groups);
- ComputedReachability::mark(&mut reachable.inherited_sets, record.inherited_groups);
- ComputedReachability::mark(&mut reachable.custom_property_environments, record.custom_properties);
- ComputedReachability::mark(&mut reachable.fixed_metadata, record.fixed_metadata);
- if let Some(longhand_table) = record.longhand_table {
- ComputedReachability::mark(&mut reachable.longhand_tables, longhand_table);
- }
- };
- for &identity in self.style_record_column.iter().flatten() {
- mark_style_record(identity);
- }
- for rows in self.pseudo_rows_by_node.values() {
- for assignment in rows.iter().filter_map(|row| row.assignment) {
- mark_style_record(assignment.style_record);
- }
- }
- for overlay in self.animation_overlay_slots.iter() {
- mark_style_record(overlay.base_style_record);
- }
- for &identity in self.base_style_record_pins.keys() {
- mark_style_record(identity);
- }
- let leases = self
- .selected_style_record_leases
- .lock()
- .expect("selected style-record leases");
- for records in leases.iter().filter_map(std::sync::Weak::upgrade) {
- for &raw_record in records.iter() {
- let record = FinalStyleRecordID(raw_record);
- let identity = record
- .base_record()
- .expect("an immutable hover frame reads only base records");
- // NB: A fork can share a reader published later by the host. It pins a record in this catalog only
- // where that generation exists here too.
- if self.style_record_generation_is_live(identity, record.base_generation()) {
- mark_style_record(identity);
- }
- }
- }
- }
-
- for index in 0..self.columns.flags.len() {
- if !self.columns.is_assigned(index) {
- continue;
- }
- ComputedReachability::mark(&mut reachable.sets, self.columns.groups(index).unwrap());
- ComputedReachability::mark(
- &mut reachable.inherited_sets,
- self.columns.inherited_groups(index).unwrap(),
- );
- ComputedReachability::mark(
- &mut reachable.custom_property_environments,
- self.columns.custom_properties(index).unwrap(),
- );
- ComputedReachability::mark(
- &mut reachable.fixed_metadata,
- self.columns.fixed_metadata(index).unwrap(),
- );
- }
- for rows in self.pseudo_rows_by_node.values() {
- for assignment in rows.iter().filter_map(|row| row.assignment) {
- ComputedReachability::mark(&mut reachable.sets, assignment.groups);
- ComputedReachability::mark(&mut reachable.inherited_sets, assignment.inherited_groups);
- ComputedReachability::mark(
- &mut reachable.custom_property_environments,
- assignment.custom_properties,
- );
- ComputedReachability::mark(&mut reachable.fixed_metadata, assignment.fixed_metadata);
- }
- }
- for (index, is_reachable) in reachable.sets.iter().copied().enumerate() {
- if !is_reachable {
- continue;
- }
- for &group in &self.sets[index].groups {
- ComputedReachability::mark(&mut reachable.groups, group);
- }
- }
- for (index, is_reachable) in reachable.inherited_sets.iter().copied().enumerate() {
- if !is_reachable {
- continue;
- }
- for &group in &self.inherited_sets[index] {
- ComputedReachability::mark(&mut reachable.groups, group);
- }
- }
- reachable
+ let longhands = self.longhands_for_target(target)?;
+ Some(
+ Self::specified_value_dependency_mask_of(
+ longhands.inheritance_dependent_values(),
+ retained_value_depends_on_current_color,
+ ) | crate::css::table_group_builder::groups_reading_current_color_through_inherited_values(|property| {
+ longhands.value(property)
+ }),
+ )
}
- pub(super) fn reclaim_unreachable(&mut self) -> ComputedGroupRetention {
- assert!(!self.style_records_are_leased(), "style records are leased");
- let reachable = self.reachability();
- let retention = ComputedGroupRetention {
- retained: self.groups.live_identities().len(),
- reachable: reachable.groups.iter().filter(|&&reachable| reachable).count(),
+ /// Whether a raw final record identity still names a live installed record.
+ pub fn final_style_record_is_live(&self, raw_style_record: u64) -> bool {
+ FinalStyleRecordID(raw_style_record)
+ .installed_record()
+ .is_some_and(|installed| self.installed.get(installed).is_some())
+ }
+
+ /// The raw custom-property environment identity behind a node's record.
+ pub fn custom_property_environment_identity(&self, node: StyleNodeID) -> Option<u64> {
+ let installed = self.installed_column.get(node.element_index()? as usize)?.as_ref()?.id;
+ Some(self.installed.get(installed)?.custom_property_environment())
+ }
+
+ /// Every raw custom-property environment identity a live record was installed with.
+ pub fn live_custom_property_environments(&self) -> impl Iterator<Item = u64> + '_ {
+ self.installed.iter().map(InstalledRecord::custom_property_environment)
+ }
+
+ /// The raw custom-property environment identity a record was installed with. An animation overlay record animates
+ /// no custom property, and holds the environment of the record it composes over.
+ pub fn style_record_custom_property_environment(&self, raw_style_record: u64) -> Option<u64> {
+ let record = FinalStyleRecordID(raw_style_record);
+ let installed = match record.installed_record() {
+ Some(installed) => installed,
+ None => self.overlay_base(record)?,
};
- let mut unreachable_style_records = self
- .style_records
- .live_identities()
- .filter(|identity| !reachable.style_records[identity.index()])
- .collect::<Vec<_>>();
- unreachable_style_records.sort_unstable_by_key(|identity| std::cmp::Reverse(identity.index()));
- for identity in unreachable_style_records {
- let record = *self.style_records.get(identity);
- if self.style_record_generations[identity.index()] == FinalStyleRecordID::MAX_BASE_GENERATION {
- self.style_records.remove_identity(content_hash(record), identity);
- } else {
- self.style_records.retire_identity(content_hash(record), identity);
- }
- let (changed, _) = self.style_record_liveness.set(identity.index(), false);
- assert!(changed, "retired base style-record identity must be live");
+ Some(self.installed.get(installed)?.custom_property_environment())
+ }
+
+ pub fn remove(&mut self, node: StyleNodeID) {
+ let Some(index) = node.element_index().map(|index| index as usize) else {
+ return;
+ };
+ if let Some(installed) = self.installed_column.replace(index, None).flatten() {
+ self.installed.release(installed.id);
+ }
+ if let Some(slot) = self.animation_overlay_column.take(index) {
+ self.release_animation_overlay_assignment(slot);
}
- for identity in self.sets.live_identities().collect::<Vec<_>>() {
- if reachable.sets[identity.index()] {
- if let Some(longhand_table) = self.sets[identity].canonical_longhand_table
- && !reachable.longhand_tables[longhand_table.index()]
- {
- self.sets[identity].canonical_longhand_table = None;
+ self.pseudo_rows_moved.push(node);
+ if let Some(rows) = self.pseudo_rows_by_node.remove(&node) {
+ for row in rows.into_vec() {
+ if let Some(installed) = row.installed {
+ self.installed.release(installed);
+ }
+ if let Some(slot) = row.installed_overlay_slot {
+ self.release_animation_overlay_assignment(slot);
}
- continue;
}
- let set = std::mem::replace(
- self.sets.get_mut(identity),
- ComputedGroupSet {
- identity_hash: 0,
- payloads: std::sync::Arc::default(),
- groups: Box::default(),
- canonical_longhand_table: None,
- },
- );
-
- self.sets.retire_identity(set.identity_hash, identity);
}
- for identity in self
- .inherited_sets
- .live_identities()
- .filter(|identity| !reachable.inherited_sets[identity.index()])
- .collect::<Vec<_>>()
- {
- let groups = std::mem::take(self.inherited_sets.get_mut(identity));
+ }
- self.inherited_sets.retire_identity(content_hash(&groups), identity);
- }
- for identity in self
- .custom_property_environments
- .live_identities()
- .filter(|identity| !reachable.custom_property_environments[identity.index()])
- .collect::<Vec<_>>()
- {
- let environment = *self.custom_property_environments.get(identity);
- self.custom_property_environments
- .retire_identity(content_hash(environment), identity);
- }
- for identity in self
- .computed_fixed_metadata
- .live_identities()
- .filter(|identity| !reachable.fixed_metadata[identity.index()])
- .collect::<Vec<_>>()
- {
- let metadata = *self.computed_fixed_metadata.get(identity);
- self.computed_fixed_metadata
- .retire_identity(content_hash(metadata), identity);
- }
- for identity in self
- .computed_longhand_tables
- .live_identities()
- .filter(|identity| !reachable.longhand_tables[identity.index()])
- .collect::<Vec<_>>()
- {
- let hash = longhand_table_hash(self.computed_longhand_tables[identity].table());
- drop(std::mem::replace(
- self.computed_longhand_tables.get_mut(identity),
- RetainedLonghandTable {
- table: HostShared::null(),
- },
- ));
- self.computed_longhand_tables.retire_identity(hash, identity);
+ pub fn remove_pseudo(&mut self, node: StyleNodeID, pseudo_kind: u8) -> Option<FinalStyleRecordID> {
+ let row = self.pseudo_row_mut(node, pseudo_kind)?;
+ let installed = row.installed.take()?;
+ let overlay = row.installed_overlay_slot.take();
+ row.published = false;
+ let final_style_record = self.final_style_record(installed, overlay);
+ if let Some(slot) = overlay {
+ self.release_animation_overlay_assignment(slot);
}
- for identity in self
- .groups
- .live_identities()
- .filter(|identity| !reachable.groups[identity.index()])
- .collect::<Vec<_>>()
- {
- let group = std::mem::replace(
- self.groups.get_mut(identity),
- ComputedGroup {
- index: usize::MAX,
- payload: SharedPayload::null(),
- content_hash: 0,
- },
- );
- self.groups_by_content.remove_identity(group.content_hash, identity);
- self.groups
- .retire_identity(content_hash((group.index, group.payload.addr())), identity);
+ self.installed.release(installed);
+ self.remove_empty_pseudo_row(node, pseudo_kind);
+ Some(final_style_record)
+ }
+ #[must_use]
+ pub fn live_animation_overlay_records(&self) -> usize {
+ self.live_animation_overlay_assignments
+ }
- release_group_payload(group.index, group.payload.as_ptr());
+ /// Free the installed records nothing holds, but for those an immutable hover frame reads.
+ fn sweep_installed_records(&mut self) {
+ if self.installed.released_count() == 0 {
+ return;
}
- retention
+ let leases = self
+ .selected_style_record_leases
+ .lock()
+ .expect("selected style-record leases");
+ // NB: An animation overlay keeps the installed record it composes over.
+ let kept: super::fast_hash::FastSet<InstalledRecordID> = leases
+ .iter()
+ .filter_map(std::sync::Weak::upgrade)
+ .flat_map(|records| {
+ records
+ .iter()
+ .filter_map(|&record| FinalStyleRecordID(record).installed_record())
+ .collect::<Vec<_>>()
+ })
+ .chain(self.animation_overlay_slots.iter().map(|overlay| overlay.base))
+ .collect();
+ drop(leases);
+ let freed = self.installed.sweep(&kept);
+ self.records_freed_since_reclamation = self.records_freed_since_reclamation.saturating_add(freed);
}
- pub(super) fn identity_mints(&self) -> IdentityMints {
- self.identity_mints
+ /// Frees the installed records nothing holds or leases.
+ #[cfg(test)]
+ pub(super) fn reclaim_unreachable(&mut self) {
+ assert!(!self.style_records_are_leased(), "style records are leased");
+ self.sweep_held_animation_overlays();
+ self.sweep_installed_records();
}
- pub(super) fn reclaim_unreachable_if_needed(&mut self, records_are_viewed: bool) -> Option<ComputedGroupRetention> {
+ /// Frees the installed records nothing holds, where nothing views or leases them, and answers
+ /// whether enough were freed since the last time it did for what they named to be reclaimed.
+ pub(super) fn reclaim_unreachable_if_needed(&mut self, records_are_viewed: bool) -> bool {
+ self.sweep_held_animation_overlays();
self.free_retired_animation_overlays();
if records_are_viewed || self.style_records_are_leased() {
- return None;
+ return false;
}
- if self.style_records_interned_since_reclamation < self.next_reclamation_after {
- return None;
+ self.sweep_installed_records();
+ if self.records_freed_since_reclamation < self.next_reclamation_after {
+ return false;
}
- self.style_records_interned_since_reclamation = 0;
- let retention = self.reclaim_unreachable();
- self.next_reclamation_after = self.style_records.live_identities().len().max(1024);
- Some(retention)
+ self.records_freed_since_reclamation = 0;
+ self.next_reclamation_after = self.installed.iter().count().max(1024);
+ true
+ }
+ /// The installed record `record` names, which must be live where it names one.
+ fn live_installed(&self, record: FinalStyleRecordID) -> Option<&InstalledRecord> {
+ let installed = record.installed_record()?;
+ Some(
+ self.installed
+ .get(installed)
+ .expect("installed style-record is not live"),
+ )
}
- pub fn style_record_payloads(&self, raw_style_record: u64) -> Option<&[SharedPayload]> {
+ pub fn style_record_payloads(&self, raw_style_record: u64) -> Option<&crate::css::computed_values::StyleGroups> {
let final_style_record = FinalStyleRecordID(raw_style_record);
- if raw_style_record & FinalStyleRecordID::ANIMATION_OVERLAY_TAG != 0 {
- let style_record = final_style_record;
- let slot = *self.animation_overlay_slots_by_record.get(&style_record)?;
- let record = self.animation_overlay_slots.get(slot)?;
- return (!record.payloads.is_empty()).then_some(record.payloads.as_ref());
+ if let Some(installed) = self.live_installed(final_style_record) {
+ return Some(&installed.record().payloads);
}
- let style_record = final_style_record.base_record()?;
- assert!(
- self.style_record_generation_is_live(style_record, final_style_record.base_generation()),
- "base style-record is not live"
- );
- let record = self.style_records.get_index(style_record.index())?;
- Some(&self.sets[record.groups].payloads)
+ let slot = *self.animation_overlay_slots_by_record.get(&final_style_record)?;
+ let overlay = self.animation_overlay_slots.get(slot)?;
+ Some(&overlay.record.payloads)
}
pub fn style_record_dependency_flags(&self, raw_style_record: u64) -> Option<u8> {
- let final_style_record = FinalStyleRecordID(raw_style_record);
- let Some(style_record) = final_style_record.base_record() else {
- let slot = *self.animation_overlay_slots_by_record.get(&final_style_record)?;
- return Some(self.animation_overlay_slots.get(slot)?.dependency_flags);
- };
- assert!(
- self.style_record_generation_is_live(style_record, final_style_record.base_generation()),
- "base style-record is not live"
- );
- let record = self.style_records.get_index(style_record.index())?;
- Some(self.computed_fixed_metadata.get(record.fixed_metadata).dependency_flags)
+ Some(self.style_record_view(raw_style_record)?.dependency_flags)
}
pub(crate) fn style_record_view(&self, raw_style_record: u64) -> Option<StyleRecordView<'_>> {
+ self.host_record(raw_style_record).map(StyleRecordView::of_host_record)
+ }
+
+ /// The record the host holds for an element or pseudo-element assigned the live record
+ /// `raw_style_record`: the installed record, or the sample of the animations over one.
+ pub(crate) fn host_record(&self, raw_style_record: u64) -> Option<&std::sync::Arc<super::pipeline::Record>> {
let final_style_record = FinalStyleRecordID(raw_style_record);
- let (base_style_record, payloads, animation_overlay_identity, animated_overlay, overlay_dependency_flags) =
- if let Some(style_record) = final_style_record.base_record() {
- assert!(
- self.style_record_generation_is_live(style_record, final_style_record.base_generation()),
- "base style-record is not live"
- );
- let record = self.style_records.get_index(style_record.index())?;
- (
- style_record,
- self.sets[record.groups].payloads.as_ref(),
- 0_u64,
- None,
- None,
- )
- } else {
- let slot = *self.animation_overlay_slots_by_record.get(&final_style_record)?;
- let overlay = self.animation_overlay_slots.get(slot)?;
- (
- overlay.base_style_record,
- overlay.payloads.as_ref(),
- overlay.source_identity,
- Some(overlay.animated_overlay.as_ref()),
- Some(overlay.dependency_flags),
- )
- };
- assert!(
- self.style_record_is_live(base_style_record),
- "base style-record is not live"
- );
- let record = self.style_records.get_index(base_style_record.index())?;
- let base_payloads = self.sets[record.groups].payloads.as_ref();
- let fixed_metadata = self
- .computed_fixed_metadata
- .get_index(record.fixed_metadata.0 as usize)?;
- let retained_longhand_table = record
- .longhand_table
- .and_then(|identity| self.computed_longhand_tables.get_index(identity.0 as usize));
- // SAFETY: A retained table holds a reference to its table for as long as the table set
- // holds the entry, which the view borrows.
- let longhand_table = retained_longhand_table.and_then(|table| unsafe { table.table.as_ref() });
- let longhand_values = retained_longhand_table.map_or(&[][..], RetainedLonghandTable::value_view);
- Some(StyleRecordView {
- payloads,
- base_payloads,
- longhand_table,
- longhand_values,
- animated_overlay,
- pseudo_element_styles: fixed_metadata.pseudo_element_styles,
- counter_style_environment_identity: fixed_metadata.counter_style_environment_identity,
- animation_overlay_identity,
- dependency_flags: overlay_dependency_flags.unwrap_or(fixed_metadata.dependency_flags),
- })
+ if let Some(installed) = self.live_installed(final_style_record) {
+ return Some(installed.record());
+ }
+ let slot = *self.animation_overlay_slots_by_record.get(&final_style_record)?;
+ Some(&self.animation_overlay_slots.get(slot)?.record)
}
pub fn pin_style_record(&mut self, raw_style_record: u64) {
let final_style_record = FinalStyleRecordID(raw_style_record);
- if let Some(style_record) = final_style_record.base_record() {
- assert!(
- self.style_record_generation_is_live(style_record, final_style_record.base_generation()),
- "base style-record is not live"
- );
- let pin_count = self.base_style_record_pins.entry(style_record).or_default();
- *pin_count = pin_count.checked_add(1).expect("base style-record pin count overflow");
+ if let Some(installed) = final_style_record.installed_record() {
+ self.installed.hold(installed);
return;
}
let slot = *self
@@ -3786,21 +1756,8 @@ impl ComputedGroupSets {
pub fn unpin_style_record(&mut self, raw_style_record: u64) {
let final_style_record = FinalStyleRecordID(raw_style_record);
- if let Some(style_record) = final_style_record.base_record() {
- assert!(
- self.style_record_generation_is_live(style_record, final_style_record.base_generation()),
- "base style-record is not live"
- );
- let std::collections::hash_map::Entry::Occupied(mut entry) =
- self.base_style_record_pins.entry(style_record)
- else {
- unreachable!("base style-record is pinned");
- };
- let pin_count = entry.get_mut();
- *pin_count = pin_count.checked_sub(1).expect("base style-record is pinned");
- if *pin_count == 0 {
- entry.remove();
- }
+ if let Some(installed) = final_style_record.installed_record() {
+ self.installed.release(installed);
return;
}
let slot = *self
@@ -3816,253 +1773,64 @@ impl ComputedGroupSets {
.checked_sub(1)
.expect("animation-overlay record is pinned");
if !record.is_assigned && record.pin_count == 0 {
- self.reclaim_animation_overlay_slot(slot);
- }
- }
-}
-
-/// A copy of the group sets holds its own reference to every payload, and shares the leases on its records.
-impl Clone for ComputedGroupSets {
- fn clone(&self) -> Self {
- let copy = Self {
- identity_mints: self.identity_mints,
- groups: self.groups.clone(),
- groups_by_content: self.groups_by_content.clone(),
- sets: self.sets.clone(),
- inherited_sets: self.inherited_sets.clone(),
- custom_property_environments: self.custom_property_environments.clone(),
- computed_fixed_metadata: self.computed_fixed_metadata.clone(),
- computed_longhand_tables: self.computed_longhand_tables.clone(),
- style_records: self.style_records.clone(),
- style_record_liveness: self.style_record_liveness.clone(),
- style_record_generations: self.style_record_generations.clone(),
- style_record_column: self.style_record_column.clone(),
- base_style_record_pins: self.base_style_record_pins.clone(),
- selected_style_record_leases: self.selected_style_record_leases.clone(),
- columns: self.columns.clone(),
- animation_overlay_slots: self.animation_overlay_slots.clone(),
- animation_overlay_slots_by_record: self.animation_overlay_slots_by_record.clone(),
- released_animation_overlay_records: self.released_animation_overlay_records.clone(),
- // NB: Either copy may be the host's, whose published frames hold their leases here.
- leases: self.leases.clone(),
- live_animation_overlay_assignments: self.live_animation_overlay_assignments,
- next_animation_overlay_generation: self.next_animation_overlay_generation,
- pending_cascade_states: self.pending_cascade_states.clone(),
- pseudo_rows_by_node: self.pseudo_rows_by_node.clone(),
- style_records_interned_since_reclamation: self.style_records_interned_since_reclamation,
- next_reclamation_after: self.next_reclamation_after,
- };
- for identity in copy.groups.live_identities() {
- let group = copy.groups.get(identity);
- retain_group_payload(group.index, group.payload.as_ptr());
- }
- copy
- }
-}
-
-impl Drop for ComputedGroupSets {
- fn drop(&mut self) {
- for identity in self.groups.live_identities() {
- let group = self.groups.get(identity);
- release_group_payload(group.index, group.payload.as_ptr());
+ self.reclaim_animation_overlay_slot_unless_held(slot);
}
}
}
-fn content_hash(content: impl Hash) -> u64 {
- let mut hasher = fast_hasher();
- content.hash(&mut hasher);
- hasher.finish()
-}
-
-fn longhand_table_hash(table: &ComputedLonghandTable) -> u64 {
- debug_assert_eq!(table.slot_hash_sum(), table.recomputed_slot_hash_sum());
- let mut hasher = fast_hasher();
- table.slot_hash_sum().hash(&mut hasher);
- table.evaluated_bits().hash(&mut hasher);
- table.importance_bits().hash(&mut hasher);
- table.inheritance_bits().hash(&mut hasher);
- table.publication_sidecars().hash(&mut hasher);
- table.publication_dependency_flags().hash(&mut hasher);
- table.pseudo_element_styles().hash(&mut hasher);
- crate::css::style_value::style_value_content_hash(table.raw_cascaded_font_size_value()).hash(&mut hasher);
- // NB: Inheritance-dependent values compare independently of insertion order. Sum the
- // property-mixed hashes, as for longhand slots, without copying and sorting the values.
- let mut inheritance_dependent_hash_sum = 0_u64;
- for (property, value) in table.retained_inheritance_dependent_values() {
- inheritance_dependent_hash_sum = inheritance_dependent_hash_sum
- .wrapping_add(longhand_slot_hash(usize::from(property), value.optional_data()));
- }
- inheritance_dependent_hash_sum.hash(&mut hasher);
- hasher.finish()
-}
-
#[cfg(test)]
mod tests {
use super::*;
- fn metadata(
- pseudo_element_styles: u64,
- dependency_flags: u8,
- counter_style_environment_identity: u64,
- ) -> ComputedMetadataInput<'static> {
- ComputedMetadataInput {
- pseudo_element_styles,
- dependency_flags,
- counter_style_environment_identity,
- animation_overlay_identity: 0,
- animated_overlay: HostShared::null(),
- animation_overlay_payloads: &[],
- longhand_table: HostShared::null(),
- }
- }
-
- /// One owned payload per group, each a fresh clone of the group's default: an allocation the
- /// caller holds the only reference to, which is what a drive hands `publish`.
- fn owned_payloads(group_count: usize) -> Vec<SharedPayload> {
- (0..group_count)
- .map(|index| {
- let default = crate::css::computed_values::default_group_payload(index);
- // SAFETY: The default payload is a live payload of its group.
- SharedPayload::new(
- unsafe { crate::css::computed_values::clone_group_payload(index, default) }.cast_const(),
- )
- })
- .collect()
- }
-
- /// One owned reference to a frozen longhand table, as a drive hands one over.
- fn owned_longhand_table() -> HostShared<ComputedLonghandTable> {
- let mut table = ComputedLonghandTable::new();
- table.freeze();
- HostShared::new(table.into_raw_shared())
- }
-
- fn longhand_table_owners(table: *const ComputedLonghandTable) -> usize {
- // SAFETY: `table` is a live strong reference, and the handle reconstructed to read the
- // count is forgotten rather than dropped, so the count itself is left alone.
- let handle = unsafe { std::sync::Arc::from_raw(table) };
- let owners = std::sync::Arc::strong_count(&handle);
- std::mem::forget(handle);
- owners
+ /// A record of the initial values holding the default payloads.
+ fn initial_record() -> std::sync::Arc<super::super::pipeline::Record> {
+ std::sync::Arc::new(super::super::pipeline::Record::of_test_values(|property| {
+ crate::css::style_compute::initial_value_handle(property).clone()
+ }))
}
- fn release_longhand_table(table: *const ComputedLonghandTable) {
- // SAFETY: `table` is a live strong reference the caller is done with.
- unsafe { crate::css::computed_longhand_table::rust_computed_longhand_table_release(table.cast_mut()) };
+ /// Installs a record of the initial values told apart by `pseudo_element_styles`, whose view
+ /// depends on `dependency_flags`.
+ fn install(sets: &mut ComputedGroupSets, pseudo_element_styles: u64, dependency_flags: u8) -> FinalStyleRecordID {
+ let record = initial_record()
+ .with_pseudo_element_styles(super::super::pipeline::PseudoElementStyles::from_bits(
+ pseudo_element_styles,
+ ))
+ .with_test_dependency_flags(dependency_flags);
+ sets.install_record(&record, || 0)
}
- fn publish_owned(
+ /// Assigns `target` a record installed as [`install`] installs it.
+ fn assign(
sets: &mut ComputedGroupSets,
target: ComputedStyleTarget,
- payloads: &[SharedPayload],
- table: HostShared<ComputedLonghandTable>,
- ) -> ComputedGroupPublication {
- let mut metadata_input = metadata(0, 0, 0);
- metadata_input.longhand_table = table;
- let owned = PendingRecordOwnership {
- groups: (1 << payloads.len()) - 1,
- table: true,
- };
- sets.publish(Some(target), payloads, 1, 0, metadata_input, owned)
- }
-
- #[test]
- fn a_fresh_record_takes_over_every_reference_the_caller_hands_it() {
- let mut sets = ComputedGroupSets::default();
- let target = ComputedStyleTarget::new(StyleNodeID::from_raw(1).unwrap(), u8::MAX);
- let payloads = owned_payloads(2);
- let table = owned_longhand_table();
-
- let publication = publish_owned(&mut sets, target, &payloads, table);
-
- assert_eq!(publication.transferred.groups, 0b11);
- assert!(publication.transferred.table);
- let view = sets.style_record_view(publication.style_record_identity.raw()).unwrap();
- assert_eq!(view.payloads, payloads.as_slice());
- assert_eq!(HostShared::from_option(view.longhand_table), table);
- // Interning took the caller's reference instead of retaining a second one, so each
- // component still has exactly one owner: the catalog.
- for (index, &payload) in payloads.iter().enumerate() {
- assert_eq!(
- crate::css::computed_values::group_payload_refcount(index, payload.as_ptr()),
- 1
- );
- }
- assert_eq!(longhand_table_owners(table.as_ptr()), 1);
- }
-
- #[test]
- fn a_record_that_repeats_its_own_components_transfers_nothing() {
- let mut sets = ComputedGroupSets::default();
- let target = ComputedStyleTarget::new(StyleNodeID::from_raw(1).unwrap(), u8::MAX);
- let payloads = owned_payloads(2);
- let table = owned_longhand_table();
- let published = publish_owned(&mut sets, target, &payloads, table);
-
- // A recompute that reproduces the same components holds a reference of its own to each.
- for (index, &payload) in payloads.iter().enumerate() {
- retain_group_payload(index, payload.as_ptr());
- }
- // SAFETY: The table is a live strong reference to a frozen table.
- let retained_table = HostShared::new(unsafe {
- crate::css::computed_longhand_table::rust_computed_longhand_table_retain(table.as_ptr())
- });
- let republished = publish_owned(&mut sets, target, &payloads, retained_table);
-
- assert_eq!(republished.style_record_identity, published.style_record_identity);
- assert_eq!(republished.transferred.groups, 0);
- assert!(!republished.transferred.table);
- // Deduplication left every reference with the caller, which releases them itself.
- for (index, &payload) in payloads.iter().enumerate() {
- assert_eq!(
- crate::css::computed_values::group_payload_refcount(index, payload.as_ptr()),
- 2
- );
- release_group_payload(index, payload.as_ptr());
- assert_eq!(
- crate::css::computed_values::group_payload_refcount(index, payload.as_ptr()),
- 1
- );
+ pseudo_element_styles: u64,
+ dependency_flags: u8,
+ ) -> FinalStyleRecordID {
+ let record = install(sets, pseudo_element_styles, dependency_flags);
+ match target.is_pseudo() {
+ true => sets.assign_installed_pseudo_record(target.node, target.pseudo_kind, record),
+ false => sets.assign_installed_record(target.node, record),
}
- assert_eq!(longhand_table_owners(table.as_ptr()), 2);
- release_longhand_table(retained_table.as_ptr());
- assert_eq!(longhand_table_owners(table.as_ptr()), 1);
+ record
}
- #[test]
- fn a_record_that_matches_an_unrelated_record_by_content_transfers_nothing() {
- let mut sets = ComputedGroupSets::default();
- let first_target = ComputedStyleTarget::new(StyleNodeID::from_raw(1).unwrap(), u8::MAX);
- let second_target = ComputedStyleTarget::new(StyleNodeID::from_raw(2).unwrap(), u8::MAX);
- let payloads = owned_payloads(2);
- let table = owned_longhand_table();
- let published = publish_owned(&mut sets, first_target, &payloads, table);
-
- // Another element builds equal components of its own, in separate allocations.
- let equal_payloads = owned_payloads(2);
- let equal_table = owned_longhand_table();
- assert_ne!(equal_payloads, payloads);
- assert_ne!(equal_table, table);
- let republished = publish_owned(&mut sets, second_target, &equal_payloads, equal_table);
-
- assert_eq!(republished.style_record_identity, published.style_record_identity);
- assert_eq!(republished.transferred.groups, 0);
- assert!(!republished.transferred.table);
- let view = sets.style_record_view(republished.style_record_identity.raw()).unwrap();
- assert_eq!(view.payloads, payloads.as_slice());
- assert_eq!(HostShared::from_option(view.longhand_table), table);
- assert_eq!(longhand_table_owners(table.as_ptr()), 1);
- // The catalog kept the components it already held, so the caller releases its own.
- for (index, &payload) in equal_payloads.iter().enumerate() {
- assert_eq!(
- crate::css::computed_values::group_payload_refcount(index, payload.as_ptr()),
- 1
- );
- release_group_payload(index, payload.as_ptr());
- }
- assert_eq!(longhand_table_owners(equal_table.as_ptr()), 1);
- release_longhand_table(equal_table.as_ptr());
+ /// Composes an animation overlay of source `identity` over the record `target` holds.
+ fn compose(
+ sets: &mut ComputedGroupSets,
+ defaults: &crate::css::computed_values::DefaultGroups,
+ target: ComputedStyleTarget,
+ animated_overlay: &crate::css::animated_overlay::AnimatedOverlay,
+ identity: u64,
+ ) -> AnimationOverlayUpdate {
+ sets.publish_animation_overlay(
+ target,
+ identity,
+ HostShared::new(std::ptr::from_ref(animated_overlay)),
+ Some(defaults.groups()),
+ false,
+ )
+ .expect("the target holds a record")
}
#[test]
@@ -4073,238 +1841,101 @@ mod tests {
let font_dependent_pseudo = ComputedStyleTarget::new(StyleNodeID::element(3), 1);
let viewport_dependent_pseudo = ComputedStyleTarget::new(StyleNodeID::element(2), 2);
let viewport_dependent_pseudo_only = ComputedStyleTarget::new(StyleNodeID::element(4), 1);
- sets.publish_unowned(Some(independent), &[], 0, 0, metadata(0, 0, 0));
- sets.publish_unowned(Some(viewport_dependent), &[], 0, 0, metadata(0, 1, 0));
- sets.publish_unowned(Some(font_dependent_pseudo), &[], 0, 0, metadata(0, 2, 0));
- sets.publish_unowned(Some(viewport_dependent_pseudo), &[], 0, 0, metadata(0, 1, 0));
- sets.publish_unowned(Some(viewport_dependent_pseudo_only), &[], 0, 0, metadata(0, 1, 0));
-
- assert_eq!(sets.viewport_dependent_nodes(|_| false), vec![2, 4]);
- }
-
- #[test]
- fn equal_longhand_tables_have_equal_hashes() {
- let mut first = ComputedLonghandTable::new();
- let mut second = ComputedLonghandTable::new();
- for table in [&mut first, &mut second] {
- table.set(
- crate::css::property_metadata::property_id::OPACITY,
- crate::css::style_value::RetainedStyleValueData::from_owned(
- crate::css::style_value::StyleValueData::Number { value: 0.5 },
- ),
- -1,
- );
- }
- first.append_drive_inheritance_dependent_value(
- crate::css::property_metadata::property_id::COLOR,
- crate::css::style_value::RetainedStyleValueData::from_owned(
- crate::css::style_value::StyleValueData::Keyword {
- keyword: crate::css::style_compute::keyword::CURRENTCOLOR,
- },
- ),
- );
- first.append_drive_inheritance_dependent_value(
- crate::css::property_metadata::property_id::BACKGROUND_COLOR,
- crate::css::style_value::RetainedStyleValueData::from_owned(
- crate::css::style_value::StyleValueData::Keyword {
- keyword: crate::css::style_compute::keyword::CURRENTCOLOR,
- },
- ),
- );
- second.append_drive_inheritance_dependent_value(
- crate::css::property_metadata::property_id::BACKGROUND_COLOR,
- crate::css::style_value::RetainedStyleValueData::from_owned(
- crate::css::style_value::StyleValueData::Keyword {
- keyword: crate::css::style_compute::keyword::CURRENTCOLOR,
- },
- ),
+ assign(&mut sets, independent, 0, 0);
+ assign(&mut sets, viewport_dependent, 1, DEPENDS_ON_VIEWPORT_METRICS);
+ assign(
+ &mut sets,
+ font_dependent_pseudo,
+ 2,
+ crate::css::computed_longhand_table::FONT_METRICS_DEPEND_ON_VIEWPORT_METRICS,
);
- second.append_drive_inheritance_dependent_value(
- crate::css::property_metadata::property_id::COLOR,
- crate::css::style_value::RetainedStyleValueData::from_owned(
- crate::css::style_value::StyleValueData::Keyword {
- keyword: crate::css::style_compute::keyword::CURRENTCOLOR,
- },
- ),
+ assign(&mut sets, viewport_dependent_pseudo, 1, DEPENDS_ON_VIEWPORT_METRICS);
+ assign(
+ &mut sets,
+ viewport_dependent_pseudo_only,
+ 1,
+ DEPENDS_ON_VIEWPORT_METRICS,
);
- first.finish_drive_inheritance_dependent_values();
- second.finish_drive_inheritance_dependent_values();
- assert!(first.publication_equals(&second));
- assert_eq!(longhand_table_hash(&first), longhand_table_hash(&second));
+ assert_eq!(sets.viewport_dependent_nodes(), vec![2, 4]);
}
#[test]
- fn empty_group_sets_share_one_identity_and_publish_node_handles() {
+ fn records_holding_the_same_in_one_context_share_an_identity() {
let mut sets = ComputedGroupSets::default();
- let first_target = ComputedStyleTarget::new(StyleNodeID::from_raw(1).unwrap(), u8::MAX);
- let second_target = ComputedStyleTarget::new(StyleNodeID::from_raw(65).unwrap(), u8::MAX);
- let first = sets.publish_unowned(Some(first_target), &[], 0, 17, metadata(3, 1, 5));
- let second = sets.publish_unowned(Some(second_target), &[], 0, 17, metadata(3, 1, 5));
- let unchanged = sets.publish_unowned(Some(first_target), &[], 0, 17, metadata(3, 1, 5));
-
- assert_eq!(sets.bind_cascade_state(first_target, (1, CascadeStateID(3))), None);
- assert_eq!(
- sets.bind_cascade_state(first_target, (1, CascadeStateID(4))),
- Some((1, CascadeStateID(3)))
- );
- assert_eq!(sets.cascade_state(first_target), Some((1, CascadeStateID(4))));
- sets.clear_cascade_state(first_target);
- assert_eq!(sets.cascade_state(first_target), None);
-
- assert!(first.new_group_set);
- assert!(!first.is_pseudo);
- assert!(!second.new_group_set);
- assert!(first.node_handle_changed);
- assert!(second.node_handle_changed);
- assert!(!unchanged.node_handle_changed);
- assert!(!unchanged.inherited_node_handle_changed);
- assert!(!unchanged.custom_property_environment_node_handle_changed);
- assert!(!unchanged.computed_fixed_metadata_node_handle_changed);
- assert!(first.new_custom_property_environment);
- assert!(!second.new_custom_property_environment);
- assert!(first.new_computed_fixed_metadata);
- assert!(!second.new_computed_fixed_metadata);
- assert!(first.new_style_record);
- assert_eq!(first.previous_style_record_identity, None);
- assert!(!second.new_style_record);
- assert_eq!(second.previous_style_record_identity, None);
- assert!(!unchanged.new_style_record);
- assert_eq!(
- unchanged.previous_style_record_identity,
- Some(first.style_record_identity)
- );
- assert!(first.style_record_node_handle_changed);
- assert!(second.style_record_node_handle_changed);
- assert!(!unchanged.style_record_node_handle_changed);
- assert_eq!(first.style_record_identity, second.style_record_identity);
- assert_ne!(first.style_record_identity.raw(), 0);
- assert_eq!(first.new_groups + second.new_groups + unchanged.new_groups, 0);
-
- let changed_environment = sets.publish_unowned(Some(first_target), &[], 0, 18, metadata(3, 1, 5));
- assert!(changed_environment.new_custom_property_environment);
- assert!(changed_environment.custom_property_environment_node_handle_changed);
- assert!(changed_environment.new_style_record);
- assert_eq!(
- changed_environment.previous_style_record_identity,
- Some(first.style_record_identity)
- );
- assert!(changed_environment.style_record_node_handle_changed);
- assert!(!changed_environment.node_handle_changed);
-
- let changed_metadata = sets.publish_unowned(Some(first_target), &[], 0, 18, metadata(7, 1, 5));
- assert!(changed_metadata.new_computed_fixed_metadata);
- assert!(changed_metadata.computed_fixed_metadata_node_handle_changed);
- assert!(changed_metadata.new_style_record);
- assert!(changed_metadata.style_record_node_handle_changed);
- assert!(!changed_metadata.node_handle_changed);
-
- let changed_observer_dependency = sets.publish_unowned(Some(first_target), &[], 0, 18, metadata(7, 1, 6));
- assert!(changed_observer_dependency.new_computed_fixed_metadata);
- assert!(changed_observer_dependency.computed_fixed_metadata_node_handle_changed);
- assert!(changed_observer_dependency.style_record_node_handle_changed);
+ let first = ComputedStyleTarget::new(StyleNodeID::element(1), u8::MAX);
+ let second = ComputedStyleTarget::new(StyleNodeID::element(2), u8::MAX);
+ let first_record = assign(&mut sets, first, 3, 0);
+ assert_eq!(assign(&mut sets, second, 3, 0), first_record);
+ assert_ne!(assign(&mut sets, second, 4, 0), first_record);
+ assert_eq!(sets.assigned_style_record(first.node), Some(first_record));
+
+ let pseudo = ComputedStyleTarget::new(StyleNodeID::element(1), 2);
+ let pseudo_record = assign(&mut sets, pseudo, 3, 0);
+ assert_eq!(pseudo_record, first_record);
+ assert_eq!(sets.pseudo_style_record(pseudo.node, 2), Some(pseudo_record));
+ assert_eq!(sets.assigned_pseudo_kinds(pseudo.node).collect::<Vec<_>>(), [2]);
+ assert_eq!(sets.remove_pseudo(pseudo.node, 2), Some(pseudo_record));
+ assert_eq!(sets.remove_pseudo(pseudo.node, 2), None);
+ }
+ #[test]
+ fn an_animation_overlay_composes_over_the_record_it_replaces_and_releases() {
+ let mut sets = ComputedGroupSets::default();
+ let node = StyleNodeID::element(1);
+ let target = ComputedStyleTarget::new(node, u8::MAX);
+ let record = assign(&mut sets, target, 0, 0);
let animated_overlay = crate::css::animated_overlay::AnimatedOverlay::default();
- let mut animated_metadata = metadata(7, 1, 6);
- animated_metadata.animation_overlay_identity = 9;
- animated_metadata.animated_overlay = HostShared::new(std::ptr::from_ref(&animated_overlay));
- let changed_animation_overlay = sets.publish_unowned(Some(first_target), &[], 0, 18, animated_metadata);
- assert!(!changed_animation_overlay.new_computed_fixed_metadata);
- assert!(!changed_animation_overlay.computed_fixed_metadata_node_handle_changed);
- assert!(!changed_animation_overlay.new_style_record);
- assert!(changed_animation_overlay.animation_overlay_slot_allocated);
- assert!(changed_animation_overlay.animation_overlay_record_updated);
- assert!(changed_animation_overlay.style_record_node_handle_changed);
- assert!(!changed_animation_overlay.node_handle_changed);
- let mut updated_animated_metadata = metadata(7, 1, 6);
- updated_animated_metadata.animation_overlay_identity = 10;
- updated_animated_metadata.animated_overlay = HostShared::new(std::ptr::from_ref(&animated_overlay));
- let updated_animation_overlay = sets.publish_unowned(Some(first_target), &[], 0, 18, updated_animated_metadata);
- assert!(!updated_animation_overlay.new_computed_fixed_metadata);
- assert!(!updated_animation_overlay.new_style_record);
- assert!(!updated_animation_overlay.animation_overlay_slot_allocated);
- assert!(updated_animation_overlay.animation_overlay_record_updated);
- assert_ne!(
- updated_animation_overlay.style_record_identity,
- changed_animation_overlay.style_record_identity
- );
- assert_eq!(updated_animation_overlay.live_animation_overlay_records, 1);
- assert_eq!(sets.live_animation_overlay_records(), 1);
-
- let released_animation_overlay = sets.publish_unowned(Some(first_target), &[], 0, 18, metadata(7, 1, 6));
- assert!(released_animation_overlay.animation_overlay_slot_released);
- assert_eq!(released_animation_overlay.live_animation_overlay_records, 0);
- assert_eq!(
- released_animation_overlay.style_record_identity,
- changed_observer_dependency.style_record_identity
- );
+ let defaults = crate::css::computed_values::DefaultGroups::default();
+
+ let composed = compose(&mut sets, &defaults, target, &animated_overlay, 9);
+ assert_eq!(composed.previous_style_record, record);
+ assert!(composed.slot_allocated);
+ assert!(composed.record_updated);
+ assert!(composed.style_record.is_animation_overlay());
+ assert_eq!(sets.assigned_style_record(node), Some(composed.style_record));
+ assert_eq!(sets.underlying_style_record(composed.style_record), Some(record));
+
+ let updated = compose(&mut sets, &defaults, target, &animated_overlay, 10);
+ assert!(!updated.slot_allocated);
+ assert!(updated.record_updated);
+ assert_ne!(updated.style_record, composed.style_record);
+ assert_eq!(updated.live_records, 1);
+
+ let unchanged = compose(&mut sets, &defaults, target, &animated_overlay, 10);
+ assert!(!unchanged.record_updated);
+ assert_eq!(unchanged.style_record, updated.style_record);
+
+ let released = compose(&mut sets, &defaults, target, &animated_overlay, 0);
+ assert!(released.slot_released);
+ assert_eq!(released.style_record, record);
+ assert_eq!(released.live_records, 0);
assert_eq!(sets.live_animation_overlay_records(), 0);
-
- let mut reused_animated_metadata = metadata(7, 1, 6);
- reused_animated_metadata.animation_overlay_identity = 11;
- reused_animated_metadata.animated_overlay = HostShared::new(std::ptr::from_ref(&animated_overlay));
- let reused_animation_overlay = sets.publish_unowned(Some(first_target), &[], 0, 18, reused_animated_metadata);
- assert!(!reused_animation_overlay.animation_overlay_slot_allocated);
- assert_eq!(reused_animation_overlay.live_animation_overlay_records, 1);
-
- let pseudo_target = ComputedStyleTarget::new(StyleNodeID::from_raw(1).unwrap(), 2);
- let pseudo = sets.publish_unowned(Some(pseudo_target), &[], 0, 18, metadata(7, 1, 6));
- let unchanged_pseudo = sets.publish_unowned(Some(pseudo_target), &[], 0, 18, metadata(7, 1, 6));
- assert!(pseudo.is_pseudo);
- assert_eq!(pseudo.previous_style_record_identity, None);
- assert!(pseudo.node_handle_changed);
- assert!(!pseudo.new_style_record);
- assert!(pseudo.style_record_node_handle_changed);
- assert!(!unchanged_pseudo.node_handle_changed);
- assert!(!unchanged_pseudo.style_record_node_handle_changed);
- assert_eq!(
- unchanged_pseudo.previous_style_record_identity,
- Some(pseudo.style_record_identity)
- );
- sets.remove(StyleNodeID::from_raw(1).unwrap());
- let republished_pseudo = sets.publish_unowned(Some(pseudo_target), &[], 0, 18, metadata(7, 1, 6));
- assert!(republished_pseudo.node_handle_changed);
- assert_eq!(
- sets.remove_pseudo(StyleNodeID::from_raw(1).unwrap(), 2),
- Some(republished_pseudo.style_record_identity)
- );
- assert_eq!(sets.remove_pseudo(StyleNodeID::from_raw(1).unwrap(), 2), None);
}
#[test]
fn pinned_animation_overlay_survives_assignment_replacement() {
let mut sets = ComputedGroupSets::default();
- let node = StyleNodeID::from_raw(1).unwrap();
+ let node = StyleNodeID::element(1);
let target = ComputedStyleTarget::new(node, u8::MAX);
let animated_overlay = crate::css::animated_overlay::AnimatedOverlay::default();
- let mut first_metadata = metadata(0, 0, 0);
- first_metadata.animation_overlay_identity = 1;
- first_metadata.animated_overlay = HostShared::new(std::ptr::from_ref(&animated_overlay));
- let first = sets.publish_unowned(Some(target), &[], 0, 0, first_metadata);
-
- sets.pin_style_record(first.style_record_identity.raw());
- let mut second_metadata = metadata(0, 0, 0);
- second_metadata.animation_overlay_identity = 2;
- second_metadata.animated_overlay = HostShared::new(std::ptr::from_ref(&animated_overlay));
- let second = sets.publish_unowned(Some(target), &[], 0, 0, second_metadata);
-
- assert_ne!(first.style_record_identity, second.style_record_identity);
- assert!(
- sets.animation_overlay_slots_by_record
- .contains_key(&first.style_record_identity)
- );
+ let defaults = crate::css::computed_values::DefaultGroups::default();
+ assign(&mut sets, target, 0, 0);
+ let first = compose(&mut sets, &defaults, target, &animated_overlay, 1);
+
+ sets.pin_style_record(first.style_record.raw());
+ let second = compose(&mut sets, &defaults, target, &animated_overlay, 2);
+
+ assert_ne!(first.style_record, second.style_record);
+ assert!(sets.animation_overlay_slots_by_record.contains_key(&first.style_record));
assert!(
sets.animation_overlay_slots_by_record
- .contains_key(&second.style_record_identity)
+ .contains_key(&second.style_record)
);
assert_eq!(sets.live_animation_overlay_records(), 1);
- sets.unpin_style_record(first.style_record_identity.raw());
- assert!(
- !sets
- .animation_overlay_slots_by_record
- .contains_key(&first.style_record_identity)
- );
+ sets.unpin_style_record(first.style_record.raw());
+ assert!(!sets.animation_overlay_slots_by_record.contains_key(&first.style_record));
sets.remove(node);
assert_eq!(sets.live_animation_overlay_records(), 0);
}
@@ -4312,36 +1943,32 @@ mod tests {
#[test]
fn released_animation_overlay_records_name_each_record_the_engine_stops_resolving() {
let mut sets = ComputedGroupSets::default();
- let node = StyleNodeID::from_raw(1).unwrap();
+ let node = StyleNodeID::element(1);
let target = ComputedStyleTarget::new(node, u8::MAX);
let animated_overlay = crate::css::animated_overlay::AnimatedOverlay::default();
- let publish = |sets: &mut ComputedGroupSets, identity| {
- let mut metadata = metadata(0, 0, 0);
- metadata.animation_overlay_identity = identity;
- metadata.animated_overlay = HostShared::new(std::ptr::from_ref(&animated_overlay));
- sets.publish_unowned(Some(target), &[], 0, 0, metadata)
- };
+ let defaults = crate::css::computed_values::DefaultGroups::default();
+ assign(&mut sets, target, 0, 0);
let released = |sets: &mut ComputedGroupSets| {
let released = sets.take_released_animation_overlay_records();
assert!(!released.overflowed());
released.records().collect::<Vec<_>>()
};
- let first = publish(&mut sets, 1);
+ let first = compose(&mut sets, &defaults, target, &animated_overlay, 1);
assert!(!sets.has_released_animation_overlay_records());
- let second = publish(&mut sets, 2);
- assert_eq!(released(&mut sets), [first.style_record_identity.raw()]);
+ let second = compose(&mut sets, &defaults, target, &animated_overlay, 2);
+ assert_eq!(released(&mut sets), [first.style_record.raw()]);
- sets.pin_style_record(second.style_record_identity.raw());
- let third = publish(&mut sets, 3);
- assert_ne!(second.style_record_identity, third.style_record_identity);
+ sets.pin_style_record(second.style_record.raw());
+ let third = compose(&mut sets, &defaults, target, &animated_overlay, 3);
+ assert_ne!(second.style_record, third.style_record);
assert!(!sets.has_released_animation_overlay_records());
- sets.unpin_style_record(second.style_record_identity.raw());
- assert_eq!(released(&mut sets), [second.style_record_identity.raw()]);
+ sets.unpin_style_record(second.style_record.raw());
+ assert_eq!(released(&mut sets), [second.style_record.raw()]);
sets.remove(node);
- assert_eq!(released(&mut sets), [third.style_record_identity.raw()]);
+ assert_eq!(released(&mut sets), [third.style_record.raw()]);
assert!(!sets.has_released_animation_overlay_records());
}
@@ -4365,21 +1992,17 @@ mod tests {
#[test]
fn a_style_record_lease_keeps_a_replaced_animation_overlay_until_it_drops() {
let mut sets = ComputedGroupSets::default();
- let node = StyleNodeID::from_raw(1).unwrap();
+ let node = StyleNodeID::element(1);
let target = ComputedStyleTarget::new(node, u8::MAX);
let animated_overlay = crate::css::animated_overlay::AnimatedOverlay::default();
- let publish = |sets: &mut ComputedGroupSets, identity| {
- let mut metadata = metadata(0, 0, 0);
- metadata.animation_overlay_identity = identity;
- metadata.animated_overlay = HostShared::new(std::ptr::from_ref(&animated_overlay));
- sets.publish_unowned(Some(target), &[], 0, 0, metadata)
- };
- let first = publish(&mut sets, 1);
+ let defaults = crate::css::computed_values::DefaultGroups::default();
+ assign(&mut sets, target, 0, 0);
+ let first = compose(&mut sets, &defaults, target, &animated_overlay, 1);
let lease = sets.lease_style_records();
- let second = publish(&mut sets, 2);
- assert!(!second.animation_overlay_slot_allocated);
- assert_ne!(first.style_record_identity, second.style_record_identity);
+ let second = compose(&mut sets, &defaults, target, &animated_overlay, 2);
+ assert!(!second.slot_allocated);
+ assert_ne!(first.style_record, second.style_record);
assert_eq!(sets.retired_animation_overlay_records(), 1);
sets.remove(node);
assert_eq!(sets.retired_animation_overlay_records(), 2);
@@ -4403,84 +2026,17 @@ mod tests {
assert!(!sets.style_records_are_leased());
}
- #[test]
- fn a_dropped_record_restores_the_metadata_and_swap_eligibility_it_replaced() {
- let mut sets = ComputedGroupSets::default();
- let node = StyleNodeID::element(1);
- let target = Some(ComputedStyleTarget::new(node, u8::MAX));
- let host = sets.publish_unowned(target, &[], 0, 0, metadata(0, 0, 0));
- let index = node.element_index().unwrap() as usize;
- let host_metadata = sets.columns.fixed_metadata(index);
- let replaced = sets.replaced_columns(node);
- let derived = sets.publish_unowned(target, &[], 0, 0, metadata(0, 1 | INHERITED_GROUP_SWAP_ELIGIBLE, 0));
- assert_ne!(sets.columns.fixed_metadata(index), host_metadata);
- assert!(sets.node_inherited_group_swap_eligible(node));
-
- sets.revert_engine_computed_record(node, derived.style_record_identity, replaced);
- assert_eq!(sets.assigned_style_record(node), Some(host.style_record_identity));
- assert_eq!(sets.columns.fixed_metadata(index), host_metadata);
- assert!(!sets.node_inherited_group_swap_eligible(node));
- }
-
- #[test]
- fn a_dropped_first_record_keeps_what_the_host_and_the_answer_published() {
- let mut sets = ComputedGroupSets::default();
- let node = StyleNodeID::element(1);
- sets.set_adjustment_facts(node, 1 << 29);
- sets.set_associated_pseudo_kind(node, 3);
- sets.set_node_answer_incomplete(node, true);
- sets.set_node_pseudo_style_mask(node, Some(1 << 2));
- let replaced = sets.replaced_columns(node);
- let derived = sets.publish_unowned(
- Some(ComputedStyleTarget::new(node, u8::MAX)),
- &[],
- 0,
- 0,
- metadata(0, 0, 0),
- );
-
- sets.revert_engine_computed_record(node, derived.style_record_identity, replaced);
- assert!(sets.assigned_style_record(node).is_none());
- assert_eq!(sets.adjustment_facts(node), 1 << 29);
- assert_eq!(
- node.element_index()
- .map(|index| sets.columns.associated_pseudo_kinds[index as usize]),
- Some(3)
- );
- assert!(sets.node_answer_is_incomplete(node));
- assert_eq!(sets.node_pseudo_style_mask(node), Some(1 << 2));
- // An answer that cannot say which pseudo-elements it styles leaves no earlier mask behind.
- sets.set_node_pseudo_style_mask(node, None);
- assert_eq!(sets.node_pseudo_style_mask(node), None);
- sets.set_node_pseudo_style_mask(node, Some(1 << 2));
-
- sets.remove(node);
- assert_eq!(sets.adjustment_facts(node), 0);
- assert!(!sets.node_answer_is_incomplete(node));
- assert_eq!(sets.node_pseudo_style_mask(node), None);
- }
-
#[test]
fn a_selected_record_lease_declines_the_overlay_record_of_a_removed_element() {
let mut sets = ComputedGroupSets::default();
- let node = StyleNodeID::from_raw(1).unwrap();
+ let node = StyleNodeID::element(1);
+ let target = ComputedStyleTarget::new(node, u8::MAX);
let animated_overlay = crate::css::animated_overlay::AnimatedOverlay::default();
- let mut overlay_metadata = metadata(0, 0, 0);
- overlay_metadata.animation_overlay_identity = 1;
- overlay_metadata.animated_overlay = HostShared::new(std::ptr::from_ref(&animated_overlay));
- let overlay = sets
- .publish_unowned(
- Some(ComputedStyleTarget::new(node, u8::MAX)),
- &[],
- 0,
- 0,
- overlay_metadata,
- )
- .style_record_identity;
- let base = sets
- .publish_unowned(None, &[], 0, 0, metadata(1, 0, 0))
- .style_record_identity;
- // The row of the removed element pins its record until the rebuild of its parent frees the row.
+ let defaults = crate::css::computed_values::DefaultGroups::default();
+ let base = assign(&mut sets, target, 0, 0);
+ let overlay = compose(&mut sets, &defaults, target, &animated_overlay, 1).style_record;
+ // The row of the removed element pins its records until the rebuild of its parent frees the row.
+ sets.pin_style_record(base.raw());
sets.pin_style_record(overlay.raw());
sets.remove(node);
assert_eq!(sets.live_animation_overlay_records(), 0);
@@ -4491,166 +2047,82 @@ mod tests {
);
assert!(sets.lease_selected_style_records(vec![base.raw()]).is_some());
sets.unpin_style_record(overlay.raw());
+ sets.unpin_style_record(base.raw());
}
#[test]
fn a_selected_record_lease_allows_other_records_to_be_reclaimed() {
let mut sets = ComputedGroupSets::default();
- let kept = sets
- .publish_unowned(None, &[], 0, 0, metadata(1, 0, 0))
- .style_record_identity;
- let discarded = sets
- .publish_unowned(None, &[], 0, 0, metadata(2, 0, 0))
- .style_record_identity;
+ let kept = install(&mut sets, 1, 0);
+ let discarded = install(&mut sets, 2, 0);
let lease = sets.lease_selected_style_records(vec![kept.raw()]).unwrap();
- let mut fork = sets.clone();
sets.reclaim_unreachable();
- fork.reclaim_unreachable();
- assert!(sets.style_record_generation_is_live(kept.base_record().unwrap(), kept.base_generation()));
- assert!(!sets.style_record_generation_is_live(discarded.base_record().unwrap(), discarded.base_generation()));
- assert!(fork.style_record_generation_is_live(kept.base_record().unwrap(), kept.base_generation()));
+ assert!(sets.final_style_record_is_live(kept.raw()));
+ assert!(!sets.final_style_record_is_live(discarded.raw()));
+ // A fork shares the lease, and references the records it shares, which keep their slots until it goes.
+ let mut fork = sets.clone();
drop(lease);
- sets.reclaim_unreachable();
fork.reclaim_unreachable();
- assert!(!sets.style_record_generation_is_live(kept.base_record().unwrap(), kept.base_generation()));
- assert!(!fork.style_record_generation_is_live(kept.base_record().unwrap(), kept.base_generation()));
- }
-
- #[test]
- fn base_style_record_pins_are_counted_until_the_last_view_releases() {
- let mut sets = ComputedGroupSets::default();
- let publication = sets.publish_unowned(None, &[], 0, 0, metadata(0, 0, 0));
- let style_record = publication.style_record_identity;
- let base_style_record = style_record.base_record().unwrap();
-
- sets.pin_style_record(style_record.raw());
- sets.pin_style_record(style_record.raw());
- assert_eq!(sets.base_style_record_pins.len(), 1);
- assert_eq!(sets.base_style_record_pins[&base_style_record], 2);
-
- sets.unpin_style_record(style_record.raw());
- assert_eq!(sets.base_style_record_pins[&base_style_record], 1);
- sets.unpin_style_record(style_record.raw());
- assert!(sets.base_style_record_pins.is_empty());
+ assert!(fork.final_style_record_is_live(kept.raw()));
+ drop(fork);
+ sets.reclaim_unreachable();
+ assert!(!sets.final_style_record_is_live(kept.raw()));
}
#[test]
- fn pinned_style_record_retains_its_inherited_group_set_for_sharing() {
+ fn a_pinned_record_outlives_its_assignment_until_the_last_pin_releases() {
let mut sets = ComputedGroupSets::default();
- let donor = sets.publish_unowned(None, &[], 0, 1, metadata(0, 0, 0));
- let record = donor.style_record_identity.raw();
- sets.pin_style_record(record);
- sets.reclaim_unreachable();
- assert_eq!(sets.inherited_sets.live_len(), 1);
-
let node = StyleNodeID::element(1);
- for kind in [u8::MAX, 1, 2] {
- let target = ComputedStyleTarget::new(node, kind);
- let shared = sets.assign_shared_style_record(target, record, 0, false).unwrap();
- assert_eq!(shared.style_record_identity, donor.style_record_identity);
- assert!(!shared.new_inherited_group_set);
- assert!(shared.inherited_node_handle_changed);
- let unchanged = sets.assign_shared_style_record(target, record, 0, false).unwrap();
- assert!(!unchanged.inherited_node_handle_changed);
- }
- sets.unpin_style_record(record);
- sets.reclaim_unreachable();
- assert_eq!(sets.inherited_sets.live_len(), 1);
+ let record = assign(&mut sets, ComputedStyleTarget::new(node, u8::MAX), 0, 0);
+ sets.pin_style_record(record.raw());
+ sets.pin_style_record(record.raw());
sets.remove(node);
sets.reclaim_unreachable();
- assert_eq!(sets.inherited_sets.live_len(), 0);
- }
-
- #[test]
- fn computed_record_reclamation_preserves_roots_while_reusing_record_slots() {
- let mut sets = ComputedGroupSets::default();
- let node = StyleNodeID::element(1);
- let target = ComputedStyleTarget::new(node, u8::MAX);
- let pinned = sets.publish_unowned(Some(target), &[], 0, 1, metadata(0, 0, 0));
- sets.pin_style_record(pinned.style_record_identity.raw());
-
- for environment in 2..128 {
- sets.publish_unowned(Some(target), &[], 0, environment, metadata(0, 0, 0));
- }
- let current = sets.assigned_style_record(node).unwrap().base_record().unwrap();
- let dense_record_count = sets.style_records.len();
- let retention = sets.reclaim_unreachable();
-
- assert_eq!(retention.retained, retention.reachable);
- assert_eq!(sets.style_records.live_len(), 2);
- assert!(sets.style_records.live_identities().any(|identity| identity == current));
- assert!(
- sets.style_records
- .live_identities()
- .any(|identity| identity == pinned.style_record_identity.base_record().unwrap())
- );
-
- for environment in 128..253 {
- sets.publish_unowned(Some(target), &[], 0, environment, metadata(0, 0, 0));
- }
- assert_eq!(sets.style_records.len(), dense_record_count);
+ assert!(sets.final_style_record_is_live(record.raw()));
- sets.unpin_style_record(pinned.style_record_identity.raw());
+ sets.unpin_style_record(record.raw());
sets.reclaim_unreachable();
- assert_eq!(sets.style_records.live_len(), 1);
+ assert!(sets.final_style_record_is_live(record.raw()));
+ sets.unpin_style_record(record.raw());
+ sets.reclaim_unreachable();
+ assert!(!sets.final_style_record_is_live(record.raw()));
}
#[test]
- fn computed_record_reclamation_reuses_the_lowest_identity_first() {
+ #[should_panic(expected = "installed style-record is not live")]
+ fn a_freed_record_cannot_be_viewed() {
let mut sets = ComputedGroupSets::default();
- let first = sets.publish_unowned(None, &[], 0, 1, metadata(0, 0, 0));
- sets.publish_unowned(None, &[], 0, 2, metadata(0, 0, 0));
- sets.publish_unowned(None, &[], 0, 3, metadata(0, 0, 0));
+ let freed = install(&mut sets, 1, 0);
sets.reclaim_unreachable();
-
- let replacement = sets.publish_unowned(None, &[], 0, 4, metadata(0, 0, 0));
+ let replacement = install(&mut sets, 2, 0);
assert_eq!(
- replacement.style_record_identity.base_record(),
- first.style_record_identity.base_record()
+ freed.installed_record().unwrap().slot(),
+ replacement.installed_record().unwrap().slot()
);
+ assert_ne!(freed, replacement);
+ let _ = sets.style_record_view(freed.raw());
}
#[test]
- fn computed_record_reclamation_retires_an_exhausted_identity() {
+ fn a_record_naming_a_slot_of_a_fork_is_not_the_record_held_in_that_slot_here() {
let mut sets = ComputedGroupSets::default();
- let exhausted = sets.publish_unowned(None, &[], 0, 1, metadata(0, 0, 0));
- let exhausted = exhausted.style_record_identity.base_record().unwrap();
- sets.style_record_generations[exhausted.index()] = FinalStyleRecordID::MAX_BASE_GENERATION;
- sets.reclaim_unreachable();
-
- let replacement = sets.publish_unowned(None, &[], 0, 2, metadata(0, 0, 0));
- assert_ne!(replacement.style_record_identity.base_record(), Some(exhausted));
- }
+ let shared = initial_record().with_test_dependency_flags(1);
+ let mut fork = sets.clone();
+ let in_fork = fork.install_record(&shared, || 0);
- #[test]
- #[should_panic(expected = "base style-record is not live")]
- fn a_retired_base_style_record_cannot_be_viewed() {
- let mut sets = ComputedGroupSets::default();
- let publication = sets.publish_unowned(None, &[], 0, 1, metadata(0, 0, 0));
- let retired_final = publication.style_record_identity;
- let retired = retired_final.base_record().unwrap();
- sets.reclaim_unreachable();
- let replacement = sets.publish_unowned(None, &[], 0, 2, metadata(0, 0, 0));
- let replacement_final = replacement.style_record_identity;
- let replacement = replacement_final.base_record().unwrap();
- assert_eq!(retired.index(), replacement.index());
- assert_ne!(retired_final.base_generation(), replacement_final.base_generation());
- let _ = sets.style_record_view(publication.style_record_identity.raw());
+ let node = StyleNodeID::element(1);
+ let held = assign(&mut sets, ComputedStyleTarget::new(node, u8::MAX), 0, 0);
+ assert_eq!(held, in_fork, "both sides take the same free slot");
+ assert!(!sets.holds_record(node, &shared));
}
#[test]
- #[should_panic(expected = "base style-record is not live")]
- fn a_retired_base_style_record_cannot_be_pinned() {
- let mut sets = ComputedGroupSets::default();
- let publication = sets.publish_unowned(None, &[], 0, 1, metadata(0, 0, 0));
- let retired_final = publication.style_record_identity;
- let retired = retired_final.base_record().unwrap();
- sets.reclaim_unreachable();
- let replacement = sets.publish_unowned(None, &[], 0, 2, metadata(0, 0, 0));
- let replacement_final = replacement.style_record_identity;
- let replacement = replacement_final.base_record().unwrap();
- assert_eq!(retired.index(), replacement.index());
- assert_ne!(retired_final.base_generation(), replacement_final.base_generation());
- sets.pin_style_record(publication.style_record_identity.raw());
+ fn an_installed_record_identity_names_its_slot_and_generation_alone() {
+ let installed = InstalledRecordID::from_parts(41, InstalledRecordID::MAX_GENERATION);
+ let record = FinalStyleRecordID::installed(installed);
+ assert_eq!(record.installed_record(), Some(installed));
+ assert!(!record.is_animation_overlay());
+ assert!(record.raw() < 1 << 53);
+ assert_eq!(FinalStyleRecordID::animation_overlay(3).installed_record(), None);
}
}
diff --git a/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs b/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs
index 7cb8ce856c0..c71805d2add 100644
--- a/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs
@@ -14,26 +14,20 @@
//! the environment the element inherits.
use std::ffi::c_void;
-use std::ops::ControlFlow;
use std::sync::Arc;
-use super::publication::{Drive, Unanswered};
use super::*;
use crate::css::cascaded_properties::{
CascadeResolutionContext, parse_substituted_value, resolve_declared_custom_properties,
};
use crate::css::custom_properties::{
CustomFunctionRegistry, CustomFunctionVisibility, CustomPropertyFinalization, CustomPropertyStore,
- FfiSubstitutionFunctionVisibility, NativeVarResolution, PreparedCustomFunction, SubstitutionAttribute,
+ NativeVarResolution, PreparedCustomFunction, SubstitutionAttribute, SubstitutionFunctionVisibility,
VarResolutionInputs, prepare_var_resolution_environment,
};
-use crate::css::parser::component_value::{ComponentKind, ComponentValue};
-use crate::css::parser::value_parser::component_values_from_source;
use crate::css::rule::CompiledFunction;
-use crate::css::style_value::{
- RetainedStyleValueData, StyleValueData, custom_property_references, utf16_equals_ascii_case_insensitive,
-};
-use custom_property_environments::{CascadedCustomProperty, CustomPropertyName};
+use crate::css::style_value::{RetainedStyleValueData, StyleValueData, custom_property_references};
+use custom_property_environments::{CustomPropertyName, retained_store};
static EMPTY_CUSTOM_FUNCTIONS: CustomFunctionRegistry<'static> = CustomFunctionRegistry::empty();
@@ -86,7 +80,7 @@ impl DocumentMediaSnapshot {
}
/// The snapshot as the resolver reads a media environment, borrowing from it.
- fn environment(&self) -> crate::css::parser::query_parser::FfiMediaEnvironment<'_> {
+ pub(super) fn environment(&self) -> crate::css::parser::query_parser::FfiMediaEnvironment<'_> {
crate::css::parser::query_parser::FfiMediaEnvironment::new(&self.values, self.length.as_ref())
}
@@ -104,7 +98,7 @@ pub(super) struct DocumentFunctionSnapshot {
/// Each definition some scope sees, by its identity, with the scope that defines it.
definitions: HashMap<u64, (Arc<CompiledFunction>, usize)>,
/// Which definition each scope's calls name, a name at a time.
- visibilities: Vec<FfiSubstitutionFunctionVisibility>,
+ visibilities: Vec<SubstitutionFunctionVisibility>,
/// The scope of each tree scope that sees a definition.
caller_scopes: HashMap<TreeScopeID, usize>,
/// What a call from each scope reaches, worked out once for the transaction.
@@ -127,7 +121,7 @@ pub(super) struct ScopeFunctions {
struct VisibleFunctions<'a> {
/// Each reachable definition, with the scope that defines it.
definitions: Vec<(&'a CompiledFunction, usize)>,
- visibilities: Vec<FfiSubstitutionFunctionVisibility>,
+ visibilities: Vec<SubstitutionFunctionVisibility>,
}
impl DocumentFunctionSnapshot {
@@ -210,7 +204,7 @@ impl DocumentFunctionSnapshot {
};
(function, scope)
});
- self.visibilities.push(FfiSubstitutionFunctionVisibility {
+ self.visibilities.push(SubstitutionFunctionVisibility {
caller_scope_identity: caller_scope,
function_identity: function.identity,
});
@@ -338,30 +332,20 @@ pub(super) struct PreparedCustomFunctions<'a> {
pub(super) container_effects: Option<super::container_queries::ContainerVerdict>,
}
-/// What a registered custom property's value computes against: the element's lengths as its style
-/// computes them after line-height, and the color scheme its colors resolve with (a
-/// PreferredColorScheme code). The length context lends no output flag.
-#[derive(Clone, Copy, PartialEq)]
-pub(super) struct RegisteredValueContext {
- pub length: crate::css::style_compute::FfiLengthResolutionContext,
- pub color_scheme: u8,
-}
-
/// The resolution context the engine substitutes under: the stores alone, with no callback into
/// C++ - what the engine cannot resolve without one is left to C++ before this is built.
#[expect(
clippy::too_many_arguments,
reason = "the context borrows each resolution input on its own"
)]
-fn engine_resolution_context<'a>(
+pub(super) fn engine_resolution_context<'a>(
parse_context: &'a crate::css::parser::value_parser::ParseContext,
store: Option<&'a CustomPropertyStore>,
inheritance_store: Option<&'a CustomPropertyStore>,
registry: &'a crate::css::custom_properties::CustomPropertyRegistry,
attributes: Option<&'a SubstitutionAttributes<'a>>,
media_environment: &'a crate::css::parser::query_parser::FfiMediaEnvironment<'a>,
- style_query: Option<&'a crate::css::cascaded_properties::FfiStyleQueryInputs>,
- style_query_references: Option<&'a mut Option<Box<crate::css::custom_properties::StyleQueryDependencies>>>,
+ style_query: Option<&'a crate::css::cascaded_properties::StyleQueryInputs>,
functions: Option<&'a PreparedCustomFunctions<'a>>,
) -> CascadeResolutionContext<'a> {
CascadeResolutionContext {
@@ -377,7 +361,7 @@ fn engine_resolution_context<'a>(
},
attributes: attributes.map_or(&[][..], |attributes| attributes.attributes.as_slice()),
custom_functions: functions.map_or(&EMPTY_CUSTOM_FUNCTIONS, |functions| &functions.registry),
- style_query_dependencies: style_query_references,
+ style_query_dependencies: None,
}
}
@@ -387,6 +371,7 @@ fn substituted_tokens(value: &StyleValueData) -> &StyleValueData {
match value {
StyleValueData::PendingSubstitution {
original_shorthand_value,
+ ..
} => substituted_tokens(original_shorthand_value.data()),
value => value,
}
@@ -395,110 +380,54 @@ fn substituted_tokens(value: &StyleValueData) -> &StyleValueData {
/// Custom property names, sorted and without duplicates.
pub(crate) type CustomPropertyNames = Arc<[Arc<[u16]>]>;
-/// What an element's custom declarations resolve over, where its match answer decides them all.
-#[derive(Clone, Copy, PartialEq, Eq, Hash)]
-pub(super) struct EnvironmentByAnswerKey {
- answer: MatchAnswerID,
- tree_scope: TreeScopeID,
- parent_environment: u64,
- registration_generation: u64,
+/// The custom properties the longhands of a style substitute.
+#[derive(Clone, Default, PartialEq)]
+pub(crate) enum LonghandCustomPropertyReads {
+ /// They substitute none.
+ #[default]
+ None,
+ /// They substitute these, by name.
+ Named(CustomPropertyNames),
+ /// They substitute something that may read any of them.
+ Any,
}
-/// The environment such declarations resolved to, and what they read beyond it.
-#[derive(Clone)]
-pub(super) struct EnvironmentByAnswer {
- environment: u64,
- reads: u8,
- custom_property_reads: Option<Option<CustomPropertyNames>>,
-}
-
-/// The custom properties cascaded custom declarations declare or read, by the declarations: the operator, written
-/// value and name of each, the last two of which an entry holds so that neither is handed out again while it does.
-#[derive(Default)]
-pub(super) struct CustomPropertyReadsByDeclarations(HashMap<u64, MemoizedCustomPropertyReads>);
-
-/// A cascaded custom declaration as the memo holds it: its operator, written value and declared name.
-type HeldCustomDeclaration = (CascadeOperator, RetainedStyleValueData, Arc<[u16]>);
-
-struct MemoizedCustomPropertyReads {
- declarations: Box<[HeldCustomDeclaration]>,
- reads: Option<CustomPropertyNames>,
-}
-
-// A copy of the engine state starts over, as the memo only saves work.
-impl Clone for CustomPropertyReadsByDeclarations {
- fn clone(&self) -> Self {
- Self::default()
- }
-}
-
-impl CustomPropertyReadsByDeclarations {
- /// The most declaration lists remembered at once.
- const LIMIT: usize = 4096;
-
- fn get(
- &self,
- hash: u64,
- declarations: &[(CascadeOperator, &RetainedStyleValueData, Arc<[u16]>)],
- ) -> Option<Option<CustomPropertyNames>> {
- let memoized = self.0.get(&hash)?;
- let same = memoized.declarations.len() == declarations.len()
- && memoized.declarations.iter().zip(declarations).all(
- |((operator, value, name), (other_operator, other_value, other_name))| {
- operator == other_operator
- && value.pointer() == other_value.pointer()
- && Arc::ptr_eq(name, other_name)
- },
- );
- same.then(|| memoized.reads.clone())
+impl LonghandCustomPropertyReads {
+ /// The reads of `names`, where `any` is whether a substitution may read others.
+ pub(super) fn new(names: Vec<Arc<[u16]>>, any: bool) -> Self {
+ match (any, names.is_empty()) {
+ (true, _) => Self::Any,
+ (false, true) => Self::None,
+ (false, false) => Self::Named(sorted_custom_property_names(names)),
+ }
}
- fn remember(
- &mut self,
- hash: u64,
- declarations: &[(CascadeOperator, &RetainedStyleValueData, Arc<[u16]>)],
- reads: Option<CustomPropertyNames>,
- ) {
- if self.0.len() >= Self::LIMIT {
- self.0.clear();
+ /// Whether the longhands substitute one of the custom properties `moved` holds.
+ pub(crate) fn read_any_of(&self, moved: impl Fn(&[u16]) -> bool) -> bool {
+ match self {
+ Self::None => false,
+ Self::Named(names) => names.iter().any(|name| moved(name)),
+ Self::Any => true,
}
- let declarations = declarations
- .iter()
- .map(|(operator, value, name)| (*operator, (*value).clone(), Arc::clone(name)))
- .collect();
- self.0.insert(hash, MemoizedCustomPropertyReads { declarations, reads });
}
}
-pub(super) fn append_custom_property_reads(value: &StyleValueData, names: &mut Vec<Arc<[u16]>>) -> bool {
- let Some((references, all_references_visible)) = custom_property_references(substituted_tokens(value)) else {
- return true;
- };
- names.extend(references.into_iter().map(Arc::from));
- all_references_visible
-}
-
-pub(super) fn value_reads_any_of_custom_properties(value: &StyleValueData, names: &[Arc<[u16]>]) -> bool {
- let Some((references, all_references_visible)) = custom_property_references(substituted_tokens(value)) else {
+/// Add the custom properties a written value reads by name to `names`, answering whether it reads
+/// only those: an `if()` condition, a custom function or an attribute's value can read any.
+pub(super) fn append_named_custom_property_reads(value: &StyleValueData, names: &mut Vec<Arc<[u16]>>) -> bool {
+ let Some(reads) = named_custom_property_reads(value) else {
return false;
};
- !all_references_visible
- || references
- .into_iter()
- .any(|reference| names.binary_search_by(|name| name.as_ref().cmp(reference)).is_ok())
+ names.extend(reads.into_iter().map(Arc::from));
+ true
}
/// The custom properties a written value reads by name, or `None` when it may read others: an
/// `if()` condition, a custom function or an attribute's value can read any.
fn named_custom_property_reads(value: &StyleValueData) -> Option<Vec<&[u16]>> {
let value = substituted_tokens(value);
- if let StyleValueData::Unresolved {
- presence_attr,
- presence_dashed_function,
- presence_if,
- ..
- } = value
- && (*presence_attr || *presence_dashed_function || *presence_if)
+ if let StyleValueData::Unresolved(unresolved) = value
+ && (unresolved.presence().attr || unresolved.presence().dashed_function || unresolved.presence().if_)
{
return None;
}
@@ -508,6 +437,11 @@ fn named_custom_property_reads(value: &StyleValueData) -> Option<Vec<&[u16]>> {
all_references_visible.then_some(references)
}
+/// Whether a written value may read one of the custom properties `moved` holds.
+pub(super) fn value_reads_any_custom_property_of(value: &StyleValueData, moved: impl Fn(&[u16]) -> bool) -> bool {
+ named_custom_property_reads(value).is_none_or(|names| names.into_iter().any(moved))
+}
+
pub(super) fn sorted_custom_property_names(mut names: Vec<Arc<[u16]>>) -> CustomPropertyNames {
names.sort_unstable();
names.dedup();
@@ -516,13 +450,15 @@ pub(super) fn sorted_custom_property_names(mut names: Vec<Arc<[u16]>>) -> Custom
/// Whether a written value substitutes `attr()`, which reads the element's attributes.
pub(super) fn value_reads_attributes(value: &StyleValueData) -> bool {
- matches!(
- substituted_tokens(value),
- StyleValueData::Unresolved {
- presence_attr: true,
- ..
- }
- )
+ unresolved_reading_attributes(value).is_some()
+}
+
+/// The tokens a written value substitutes, where they substitute `attr()`.
+pub(super) fn unresolved_reading_attributes(value: &StyleValueData) -> Option<&crate::css::style_value::UnresolvedBox> {
+ match substituted_tokens(value) {
+ StyleValueData::Unresolved(unresolved) if unresolved.presence().attr => Some(unresolved),
+ _ => None,
+ }
}
/// Whether a written value substitutes `inherit()`, which reads the custom-property environment
@@ -530,10 +466,7 @@ pub(super) fn value_reads_attributes(value: &StyleValueData) -> bool {
pub(super) fn value_reads_inherited_values(value: &StyleValueData) -> bool {
matches!(
substituted_tokens(value),
- StyleValueData::Unresolved {
- presence_inherit: true,
- ..
- }
+ StyleValueData::Unresolved(unresolved) if unresolved.presence().inherit
)
}
@@ -543,11 +476,7 @@ pub(super) fn value_reads_inherited_values(value: &StyleValueData) -> bool {
pub(super) fn value_reads_conditions(value: &StyleValueData) -> bool {
matches!(
substituted_tokens(value),
- StyleValueData::Unresolved { presence_if: true, .. }
- | StyleValueData::Unresolved {
- presence_attr: true,
- ..
- }
+ StyleValueData::Unresolved(unresolved) if unresolved.presence().if_ || unresolved.presence().attr
)
}
@@ -556,55 +485,13 @@ pub(super) fn value_reads_conditions(value: &StyleValueData) -> bool {
pub(super) fn value_calls_custom_functions(value: &StyleValueData) -> bool {
matches!(
substituted_tokens(value),
- StyleValueData::Unresolved {
- presence_dashed_function: true,
- ..
- }
+ StyleValueData::Unresolved(unresolved) if unresolved.presence().dashed_function
)
}
-/// Whether a written value's substitution can come out as `revert` or `revert-layer`, which roll
-/// its property back to the declarations it beat. A custom property never computes to a CSS-wide
-/// keyword, so `var()` and `inherit()` substitute one only from a fallback written in the value,
-/// as `env()` and the branches of `if()` do. A custom function's result is not written in the
-/// value, so it may be one, and so may an attribute's text that an `attr()` parses with the
-/// universal syntax; any other `attr()` parses it as a string or with a syntax no CSS-wide
-/// keyword matches.
-pub(super) fn value_may_substitute_revert(value: &StyleValueData) -> bool {
- fn is_universally_typed_attr(name: &[u16], arguments: &[ComponentValue]) -> bool {
- utf16_equals_ascii_case_insensitive(name, b"attr")
- && arguments.iter().any(|argument| {
- argument.function().is_some_and(|(name, syntax)| {
- utf16_equals_ascii_case_insensitive(name, b"type")
- && syntax.iter().any(|component| component.is_delim(b'*'))
- })
- })
- }
- fn may_yield_revert_keyword(values: &[ComponentValue]) -> bool {
- values.iter().any(|value| match &value.kind {
- ComponentKind::Function { name, values } => {
- is_universally_typed_attr(name, values) || may_yield_revert_keyword(values)
- }
- ComponentKind::SimpleBlock { values, .. } => may_yield_revert_keyword(values),
- ComponentKind::Token(_) => value.ident().is_some_and(|ident| {
- utf16_equals_ascii_case_insensitive(ident, b"revert")
- || utf16_equals_ascii_case_insensitive(ident, b"revert-layer")
- }),
- })
- }
- match substituted_tokens(value) {
- StyleValueData::Unresolved {
- components,
- presence_dashed_function,
- ..
- } => *presence_dashed_function || may_yield_revert_keyword(components.as_slice()),
- _ => false,
- }
-}
-
/// What a written value's substitutions read beyond the element's custom-property environment,
/// as `FfiNodeRecordReads` bits.
-fn substitution_reads(value: &StyleValueData) -> u8 {
+pub(super) fn substitution_reads(value: &StyleValueData) -> u8 {
let mut reads = 0;
if value_calls_custom_functions(value) {
reads |= bridge::FfiNodeRecordReads::CustomFunction as u8;
@@ -621,26 +508,16 @@ fn substitution_reads(value: &StyleValueData) -> u8 {
reads
}
-/// The custom-property environments a node's winners substitute under: its own, which `var()`
-/// reads, and the one it inherits, which `inherit()` reads - the parent's, or the originating
-/// element's for a pseudo-element.
-#[derive(Clone, Copy)]
-pub(super) struct SubstitutionEnvironment {
- pub own: u64,
- pub inherited: u64,
-}
-
/// What a node's winners substitute against beside their written values: the document's inputs
-/// and media features, the custom-property environments, and what is read of the element itself,
+/// and media features, and what is read of the element itself,
/// where a winner reads it - its attributes for `attr()`, the lengths and colors a `style()` query
/// in `if()` resolves against, and the custom functions its calls reach.
pub(super) struct SubstitutionInputs<'a> {
pub document: &'a bridge::FfiDocumentStyleComputationInputs,
pub media: &'a DocumentMediaSnapshot,
- pub environment: SubstitutionEnvironment,
pub attributes: Option<&'a SubstitutionAttributes<'a>>,
- pub style_query: Option<&'a crate::css::cascaded_properties::FfiStyleQueryInputs>,
- /// Where the custom properties a `style()` query reads are noted.
+ pub style_query: Option<&'a crate::css::cascaded_properties::StyleQueryInputs>,
+ /// Where whether a `style()` query reads the sibling position is noted.
pub style_query_references:
Option<&'a std::cell::RefCell<Option<Box<crate::css::custom_properties::StyleQueryDependencies>>>>,
pub functions: Option<&'a PreparedCustomFunctions<'a>>,
@@ -655,173 +532,40 @@ pub(super) struct SubstitutionAttributes<'a> {
}
impl<'a> SubstitutionAttributes<'a> {
- pub(super) fn of(facts: &'a index::ElementFactStore, node: StyleNodeID, html_namespace: StyleAtomID) -> Self {
+ pub(super) fn of(
+ projection: &'a pipeline::projection::Projection,
+ node: StyleNodeID,
+ html_namespace: StyleAtomID,
+ ) -> Self {
+ let facts = projection.facts(node);
Self {
attributes: facts
- .substitution_attributes(node)
- .map(|(name, value)| SubstitutionAttribute { name, value })
+ .map_or(&[][..], |facts| facts.attributes())
+ .iter()
+ .filter_map(|attribute| {
+ Some(SubstitutionAttribute {
+ name: projection.attribute_substitution_name(attribute.name)?,
+ value: projection.attribute_value_text(attribute.value)?,
+ })
+ })
.collect(),
- names_are_ascii_case_insensitive: !html_namespace.is_none() && facts.namespace_of(node) == html_namespace,
+ names_are_ascii_case_insensitive: !html_namespace.is_none()
+ && facts.is_some_and(|facts| facts.namespace() == html_namespace),
}
}
}
-impl RetainedState {
- /// Hand each of a node's element-target matches, with the cascade inputs its priority is
- /// computed from, to `visit`, stopping when it breaks. `None` when the node has no answer to read.
- fn try_for_each_element_match(
- &self,
- node: StyleNodeID,
- visit: impl FnMut(RuleID, TreeScopeID, Specificity, u32) -> ControlFlow<()>,
- ) -> Option<ControlFlow<()>> {
- self.try_for_each_match(node, None, visit)
- }
-
- /// The matches declaring custom properties in the answer a transaction publishes for the node,
- /// read before that answer is installed: the answers the lookups below find are the installed
- /// ones, which a node published in this transaction does not have yet, or has from before.
- pub(super) fn batch_custom_property_matches_of(
- &self,
- published: &PublishedMatchAnswers,
- answer: &PublishedMatchAnswer,
- ) -> Option<Vec<BatchCustomPropertyMatch>> {
- let mut matches = Vec::new();
- let mut push = |rule: RuleID,
- tree_scope: TreeScopeID,
- specificity: Specificity,
- scope_proximity: u32,
- pseudo: Option<u16>| {
- if !self.program.custom_declarations_of(rule).is_empty() {
- matches.push(BatchCustomPropertyMatch {
- rule,
- tree_scope,
- specificity,
- scope_proximity,
- pseudo,
- });
- }
- };
- if let Some(published_matches) = published.matches_for(answer) {
- for entry in published_matches {
- push(
- entry.rule,
- entry.tree_scope,
- entry.specificity,
- entry.scope_proximity,
- entry.pseudo_element.map(|target| target.kind.0),
- );
- }
- } else {
- for rule_match in self.match_answers.answer(answer.cascade_input?)?.iter() {
- let entry = &self.programs.get(rule_match.program).entries()[rule_match.entry as usize];
- push(
- rule_match.rule,
- rule_match.tree_scope,
- entry.specificity,
- rule_match.scope_proximity,
- entry.pseudo_element.map(|target| target.kind.0),
- );
- }
- }
- Some(matches)
- }
-
- /// The element's matches when `pseudo` is `None`, else the matches for that pseudo-element.
- /// In a batch, those declaring custom properties alone.
- fn try_for_each_match(
- &self,
- node: StyleNodeID,
- pseudo: Option<u8>,
- mut visit: impl FnMut(RuleID, TreeScopeID, Specificity, u32) -> ControlFlow<()>,
- ) -> Option<ControlFlow<()>> {
- if let Some(matches) = self.batch_custom_property_matches.get(&node) {
- for entry in matches.iter().filter(|entry| entry.pseudo == pseudo.map(u16::from)) {
- if visit(entry.rule, entry.tree_scope, entry.specificity, entry.scope_proximity).is_break() {
- return Some(ControlFlow::Break(()));
- }
- }
- return Some(ControlFlow::Continue(()));
- }
- self.try_for_each_answer_match(node, pseudo, visit)
- }
-
- /// Every match of the node's answer for the element when `pseudo` is `None`, else for that
- /// pseudo-element: the answer its transaction publishes, else the one it retains.
- pub(super) fn try_for_each_answer_match(
- &self,
- node: StyleNodeID,
- pseudo: Option<u8>,
- mut visit: impl FnMut(RuleID, TreeScopeID, Specificity, u32) -> ControlFlow<()>,
- ) -> Option<ControlFlow<()>> {
- let wanted =
- |target: Option<tree::PseudoElementTarget>| target.map(|target| target.kind.0) == pseudo.map(u16::from);
- if let Some((published, answer)) = Self::published_answer_lookup(
- &self.published_match_answers,
- self.batch_matching_traversal.as_deref(),
- node,
- ) && let Some(matches) = published.matches_for(answer)
- {
- for entry in matches.iter().filter(|entry| wanted(entry.pseudo_element)) {
- if visit(entry.rule, entry.tree_scope, entry.specificity, entry.scope_proximity).is_break() {
- return Some(ControlFlow::Break(()));
- }
- }
- return Some(ControlFlow::Continue(()));
- }
- // An answer published by its identity alone names the matches the catalog holds for it;
- // the answer the node retains from before is not the one it is being published with.
- let published_identity = Self::published_answer_lookup(
- &self.published_match_answers,
- self.batch_matching_traversal.as_deref(),
- node,
- )
- .map(|(_, answer)| answer.cascade_input);
- let answer = match published_identity {
- Some(identity) => identity.and_then(|identity| self.match_answers.answer(identity))?,
- None => match self.retained_match_answer(node) {
- Lookup::Known(answer) => answer,
- _ => return None,
- },
- };
- for rule_match in answer.iter() {
- let entry = &self.programs.get(rule_match.program).entries()[rule_match.entry as usize];
- if !wanted(entry.pseudo_element) {
- continue;
- }
- if visit(
- rule_match.rule,
- rule_match.tree_scope,
- entry.specificity,
- rule_match.scope_proximity,
- )
- .is_break()
- {
- return Some(ControlFlow::Break(()));
- }
- }
- Some(ControlFlow::Continue(()))
- }
+/// Whether a value substitutes something of the element itself beyond its custom properties:
+/// its attributes, conditions on its style and the document's media, or custom functions.
+pub(super) fn value_reads_substitution_subject(value: &StyleValueData) -> bool {
+ value_calls_custom_functions(value) || value_reads_attributes(value) || value_reads_conditions(value)
+}
+impl RetainedState {
/// Whether anything in the document declares a custom property. Nothing declaring one means
/// every environment is the inherited one, and no cascade need look.
pub(super) fn any_custom_property_is_declared(&self) -> bool {
- self.program.any_rule_declares_custom_properties() || self.facts.any_element_declares_custom_properties()
- }
-
- /// The environment the element's own values substitute under: `own`, the one its declarations
- /// resolve to, with what its animations sampled into its custom properties laid over it.
- pub(super) fn sampled_custom_property_environment(&mut self, node: StyleNodeID, own: u64) -> u64 {
- let Some((overlay, sampled_over)) = self
- .element_custom_property_data
- .get(&node)
- .and_then(|held| Some((held.identity, held.sampled_over?)))
- else {
- return own;
- };
- if sampled_over == own {
- return overlay;
- }
- self.custom_property_environments.overlay_moved_over(overlay, own)
+ self.rules.any_rule_declares_custom_properties() || self.element_declarations.any_declares_custom_properties()
}
/// Whether the element's animations sample custom properties, which its own values read.
@@ -831,385 +575,6 @@ impl RetainedState {
.is_some_and(|held| held.sampled_over.is_some())
}
- pub(super) fn node_declares_custom_properties(&self, node: StyleNodeID) -> bool {
- if !self.any_custom_property_is_declared() {
- return false;
- }
- if !self.facts.element_custom_declarations(node).is_empty() {
- return true;
- }
- let declares = |rule: RuleID, _: TreeScopeID, _: Specificity, _: u32| {
- if self.program.custom_declarations_of(rule).is_empty() {
- ControlFlow::Continue(())
- } else {
- ControlFlow::Break(())
- }
- };
- // An element standing for its shadow host's pseudo-element, such as the slot `::details-content` is, cascades
- // the host's rules for that pseudo-element, and its environment resolves their custom declarations.
- let result = match self.backed_host_pseudo_element(node) {
- Some((kind, host)) => self.try_for_each_match(host, Some(kind), declares),
- None => self.try_for_each_element_match(node, declares),
- };
- matches!(result, Some(ControlFlow::Break(())))
- }
-
- /// Whether a reaction on the node may move its custom-property environment, which its
- /// descendants inherit: it holds an environment of its own, or its cascade declares custom
- /// properties now. A node whose environment is its parent's and whose cascade declares none
- /// keeps the parent's whatever its reaction computes.
- pub(super) fn node_environment_may_move(&self, node: StyleNodeID) -> bool {
- let own = self.computed_group_sets.custom_property_environment_identity(node);
- let parent = self
- .tree
- .inheritance_parent(node)
- .map_or(Some(0), |parent| self.inherited_custom_property_environment(parent));
- own != parent || self.node_declares_custom_properties(node)
- }
-
- /// The environment the node's children inherit: the one behind its record, without the custom
- /// properties a registration keeps from inheriting.
- pub(super) fn inherited_custom_property_environment(&self, node: StyleNodeID) -> Option<u64> {
- let environment = self.computed_group_sets.custom_property_environment_identity(node)?;
- Some(self.custom_property_environments.inheritable(environment))
- }
-
- /// Whether the node's style reads custom properties: its cascade declares some, or a winner
- /// of its state was written with a substitution. A node whose reads are unknown reads.
- pub fn node_style_reads_custom_properties(&mut self, node: StyleNodeID) -> bool {
- // Published substitution usage also includes the pseudo styles C++ computes, whose
- // reads are not represented by the element's own winner state.
- if self.facts.uses_unnamed_custom_properties(node) || self.node_declares_custom_properties(node) {
- return true;
- }
- let Lookup::Known((_, state)) = self
- .current_winner_groups()
- .token_for(WinnerGroupKey::current(node, self.program.version()))
- else {
- return true;
- };
- self.state_has_substitutions(node, state)
- }
-
- pub(super) fn node_style_reads_any_of_custom_properties(&self, node: StyleNodeID, names: &[Arc<[u16]>]) -> bool {
- if names.is_empty() {
- return false;
- }
- let reads_any = |reads: &[Arc<[u16]>]| reads.iter().any(|read| names.binary_search(read).is_ok());
- let groups = self.current_winner_groups();
- let Some(state) = self.element_record_winner_state(node) else {
- return true;
- };
- let states_read_any = std::iter::once(state)
- .chain(groups.pseudo_states(node).map(|(_, _, state, _)| state))
- .any(|state| {
- self.state_custom_property_reads(node, state)
- .is_none_or(|reads| reads_any(&reads))
- });
- if states_read_any {
- return true;
- }
- let declarations_read_any = match self.custom_declaration_custom_property_reads.get(&node) {
- Some(reads) => reads.as_ref().is_none_or(|reads| reads_any(reads)),
- None => self.node_declares_custom_properties(node),
- };
- declarations_read_any
- || self
- .animation_effect_descriptions
- .keyframes_read_any_of_custom_properties(node, names)
- }
-
- /// Whether the node's winner inventory is complete once custom properties are set aside: the
- /// engine computes an environment from those itself, and a rule declaring them is otherwise as
- /// complete as any, for the element and for each of its pseudo-elements alike.
- pub(super) fn cascade_winners_are_complete_but_for_custom_properties(&self, node: StyleNodeID) -> bool {
- if let Some(&complete) = self.batch_answers_complete_but_for_custom_properties.get(&node) {
- return complete;
- }
- if let Some((published, answer)) = Self::published_answer_lookup(
- &self.published_match_answers,
- self.batch_matching_traversal.as_deref(),
- node,
- ) && let Some(matches) = published.matches_for(answer)
- {
- return matches
- .iter()
- .all(|entry| self.match_is_complete_but_for_custom_properties(node, entry.rule));
- }
- let Lookup::Known(answer) = self.retained_match_answer(node) else {
- return false;
- };
- self.retained_matches_are_complete_but_for_custom_properties(node, answer)
- }
-
- /// What `cascade_winners_are_complete_but_for_custom_properties` says of the answer a
- /// transaction publishes for the node, read before that answer is installed. `None` when the
- /// answer holds neither its matches nor an identity the catalog materializes.
- pub(super) fn answer_is_complete_but_for_custom_properties(
- &self,
- node: StyleNodeID,
- published: &PublishedMatchAnswers,
- answer: &PublishedMatchAnswer,
- ) -> Option<bool> {
- if let Some(matches) = published.matches_for(answer) {
- return Some(
- matches
- .iter()
- .all(|entry| self.match_is_complete_but_for_custom_properties(node, entry.rule)),
- );
- }
- let matches = self.match_answers.answer(answer.cascade_input?)?;
- Some(self.retained_matches_are_complete_but_for_custom_properties(node, matches))
- }
-
- fn retained_matches_are_complete_but_for_custom_properties(
- &self,
- node: StyleNodeID,
- matches: &[RetainedRuleMatch],
- ) -> bool {
- matches
- .iter()
- .all(|rule_match| self.match_is_complete_but_for_custom_properties(node, rule_match.rule))
- }
-
- /// Whether the winners the cascade publishes hold a match: they hold its container conditions
- /// (`container_gate_is_held`). Its custom properties are the environment's.
- pub(super) fn match_is_complete_but_for_custom_properties(&self, node: StyleNodeID, rule: RuleID) -> bool {
- self.container_gate_is_held(Some(node), rule)
- }
-
- /// The custom properties the node's cascade decides, each with its winning declaration and
- /// the value it was written with, in the order the C++ cascade lists them: by first
- /// appearance, applying blocks from the lowest priority up, a later declaration of a name
- /// replacing the earlier in place. `None` when the node has no answer to cascade from, or a
- /// declaration arrived without its written value.
- fn cascaded_custom_declarations(
- &self,
- node: StyleNodeID,
- ) -> Option<Vec<(CustomDeclaration, RetainedStyleValueData)>> {
- self.cascaded_custom_declarations_of(node, None)
- }
-
- /// What `cascaded_custom_declarations` says of the element, for one of its pseudo-elements:
- /// its rules alone, since a pseudo-element has no declarations of its own.
- fn cascaded_custom_declarations_of(
- &self,
- node: StyleNodeID,
- pseudo: Option<u8>,
- ) -> Option<Vec<(CustomDeclaration, RetainedStyleValueData)>> {
- self.cascade_custom_declarations(node, pseudo, None)
- }
-
- /// What a pseudo-element's custom declarations cascade to, from the matches being published
- /// for it rather than from a published answer. `None` when a declaration arrived without its
- /// written value.
- pub(super) fn cascaded_pseudo_custom_declarations_in(
- &self,
- node: StyleNodeID,
- matches: &[RuleMatch],
- pseudo: tree::PseudoElementTarget,
- ) -> Option<Vec<CustomDeclaration>> {
- let kind = u8::try_from(pseudo.kind.0).ok()?;
- let cascaded = self.cascade_custom_declarations(node, Some(kind), Some(matches))?;
- Some(cascaded.into_iter().map(|(declared, _)| declared).collect())
- }
-
- pub(super) fn cascade_custom_declarations(
- &self,
- node: StyleNodeID,
- pseudo: Option<u8>,
- matches: Option<&[RuleMatch]>,
- ) -> Option<Vec<(CustomDeclaration, RetainedStyleValueData)>> {
- struct Candidate<'a> {
- priority: CascadePriority,
- stratum: CascadeStratum,
- declared: CustomDeclaration,
- written: &'a RetainedStyleValueData,
- }
-
- let mut candidates = Vec::new();
- let mut visit = |rule: RuleID, tree_scope: TreeScopeID, specificity: Specificity, scope_proximity: u32| {
- let declared = self.program.custom_declarations_of(rule);
- if declared.is_empty() {
- return ControlFlow::Continue(());
- }
- // A gated rule declares for the node where its container conditions held when its
- // winners were published, as its longhands do.
- if !self.published_container_verdict_holds(node, rule, pseudo.is_some()) {
- return ControlFlow::Continue(());
- }
- let written = self.program.custom_written_values_of(rule);
- if written.len() != declared.len() {
- return ControlFlow::Break(());
- }
- let mut priority_and_stratum_by_importance = [None; 2];
- for (&declared, written) in declared.iter().zip(written) {
- let (priority, stratum) = *priority_and_stratum_by_importance[declared.important as usize]
- .get_or_insert_with(|| {
- (
- self.cascade_priority_of(
- node,
- rule,
- tree_scope,
- specificity,
- scope_proximity,
- declared.important,
- ),
- self.cascade_stratum_of(node, rule, tree_scope, declared.important),
- )
- });
- candidates.push(Candidate {
- priority,
- stratum,
- declared,
- written,
- });
- }
- ControlFlow::Continue(())
- };
- let result = match matches {
- Some(matches) => {
- let wanted = pseudo.map(u16::from);
- let mut result = ControlFlow::Continue(());
- for entry in matches
- .iter()
- .filter(|entry| entry.pseudo_element.map(|target| target.kind.0) == wanted)
- {
- result = visit(entry.rule, entry.tree_scope, entry.specificity, entry.scope_proximity);
- if result.is_break() {
- break;
- }
- }
- result
- }
- None => self.try_for_each_match(node, pseudo, &mut visit)?,
- };
- if result.is_break() {
- return None;
- }
- let element_declarations = pseudo
- .is_none()
- .then(|| self.facts.element_custom_declarations_written(node))
- .flatten();
- let mut priority_and_stratum_by_importance = [None; 2];
- for (&declared, written) in element_declarations
- .into_iter()
- .flat_map(index::ElementCustomDeclarations::iter)
- {
- let (priority, stratum) = *priority_and_stratum_by_importance[declared.important as usize]
- .get_or_insert_with(|| {
- (
- self.element_cascade_priority(node, ElementDeclarationKind::InlineStyle, declared.important),
- self.element_cascade_stratum(node, ElementDeclarationKind::InlineStyle, declared.important),
- )
- });
- candidates.push(Candidate {
- priority,
- stratum,
- declared,
- written,
- });
- }
- if let [candidate] = candidates.as_slice() {
- return Some(if candidate.stratum.ceiling(candidate.declared.operator).is_none() {
- vec![(candidate.declared, candidate.written.clone_retained())]
- } else {
- Vec::new()
- });
- }
- // Keep insertion order for declarations with equal cascade priority.
- candidates.sort_by_key(|candidate| candidate.priority);
- let mut name_indices = HashMap::default();
- let mut candidates_by_name: Vec<Vec<Candidate>> = Vec::new();
- for candidate in candidates {
- let index = *name_indices.entry(candidate.declared.name).or_insert_with(|| {
- candidates_by_name.push(Vec::new());
- candidates_by_name.len() - 1
- });
- candidates_by_name[index].push(candidate);
- }
- let mut cascaded = Vec::with_capacity(candidates_by_name.len());
- let mut ceilings = Vec::new();
- for candidates in candidates_by_name {
- ceilings.clear();
- for candidate in candidates.into_iter().rev() {
- if !ceilings.iter().all(|&ceiling| candidate.stratum.is_below(ceiling)) {
- continue;
- }
- let Some(ceiling) = candidate.stratum.ceiling(candidate.declared.operator) else {
- cascaded.push((candidate.declared, candidate.written.clone_retained()));
- break;
- };
- ceilings.push(ceiling);
- }
- }
- Some(cascaded)
- }
-
- fn environment_inputs(
- parent: u64,
- registration_generation: u64,
- cascaded: &[(CustomDeclaration, RetainedStyleValueData)],
- ) -> custom_property_environments::EnvironmentInputs {
- custom_property_environments::EnvironmentInputs {
- parent,
- registration_generation,
- cascaded: cascaded
- .iter()
- .map(|(declared, written)| CascadedCustomProperty {
- name: declared.name,
- important: declared.important,
- written_value: written.pointer() as usize,
- })
- .collect(),
- }
- }
-
- /// Remember the environment C++ resolved for a node's custom declarations, so a later engine
- /// derivation of the node, or of an element alike in its declarations, takes that environment
- /// rather than resolving an equal one under an identity of its own.
- pub(super) fn remember_cpp_custom_property_environment(&mut self, node: StyleNodeID, environment: u64) {
- if environment == 0 || environment & custom_property_environments::ENGINE_ENVIRONMENT_IDENTITY_BIT != 0 {
- return;
- }
- let inputs = self.document_style_computation_inputs;
- if !self.node_declares_custom_properties(node) {
- return;
- }
- let Some(cascaded) = self.cascaded_custom_declarations(node) else {
- return;
- };
- if cascaded.is_empty() {
- return;
- }
- // What an `attr()`, an `if()` or a custom function call resolves to is the element's
- // alone, which no memo hands to another.
- if cascaded.iter().any(|(_, written)| {
- value_reads_attributes(written.data())
- || value_reads_conditions(written.data())
- || value_calls_custom_functions(written.data())
- }) {
- return;
- }
- let parent_environment = match self.tree.inheritance_parent(node) {
- Some(parent) => match self.computed_group_sets.custom_property_environment_identity(parent) {
- Some(parent_environment) => parent_environment,
- None => return,
- },
- None => 0,
- };
- let key = Self::environment_inputs(
- parent_environment,
- inputs.custom_property_registration_generation,
- &cascaded,
- );
- if self.custom_property_environments.memoized(&key).is_none() {
- let written_values = cascaded.into_iter().map(|(_, written)| written).collect();
- self.custom_property_environments
- .remember(key, environment, written_values);
- }
- }
-
/// What a `style()` query of an `if()` resolves against for a node or one of its
/// pseudo-elements, as the host takes it: the style the target holds, else the one its parent
/// holds, which for a pseudo-element is its originating element's, else the document's initial
@@ -1217,15 +582,12 @@ impl RetainedState {
pub(super) fn style_query_inputs(
&self,
target: computed::ComputedStyleTarget,
- ) -> Option<crate::css::cascaded_properties::FfiStyleQueryInputs> {
+ ) -> Option<crate::css::cascaded_properties::StyleQueryInputs> {
let node = target.node();
- let tree_counting = self
- .element_sibling_position(node)
- .map(|(count, index)| (u64::from(count), u64::from(index)));
let parent_record = || {
if target.pseudo_kind() == u8::MAX {
self.computed_group_sets
- .assigned_style_record(self.tree.inheritance_parent(node)?)
+ .assigned_style_record(self.projection.inheritance_parent(node)?)
} else {
self.computed_group_sets.assigned_style_record(node)
}
@@ -1235,20 +597,30 @@ impl RetainedState {
.assigned_final_style_record(target)
.or_else(parent_record)
.and_then(|record| self.computed_group_sets.style_record_view(record.raw()));
- if let Some(view) = held
- && let Some(length) = self.record_length_resolution_context(&view)
+ self.style_query_inputs_of(held.as_ref().map(|view| (view.payloads, view.dependency_flags)), node)
+ }
+
+ /// What `style_query_inputs` says, against the style `view`, or no style at all.
+ pub(super) fn style_query_inputs_of(
+ &self,
+ style: Option<(&crate::css::computed_values::StyleGroups, u8)>,
+ node: StyleNodeID,
+ ) -> Option<crate::css::cascaded_properties::StyleQueryInputs> {
+ let tree_counting = self
+ .element_sibling_position(node)
+ .map(|(count, index)| (u64::from(count), u64::from(index)));
+ if let Some((payloads, dependency_flags)) = style
+ && let Some(length) = self.record_length_resolution_context(payloads, dependency_flags)
{
- let values = crate::css::computed_value_views::ComputedValuesView::new(
- crate::css::host_shared::SharedPayload::as_pointer_slice(view.payloads),
- );
- return Some(crate::css::cascaded_properties::FfiStyleQueryInputs {
+ let values = crate::css::computed_value_views::ComputedValuesView::of(payloads);
+ return Some(crate::css::cascaded_properties::StyleQueryInputs {
length,
tree_counting,
color_scheme: values.inherited_ui().color_scheme,
current_color: values.inherited_text().color,
});
}
- Some(crate::css::cascaded_properties::FfiStyleQueryInputs {
+ Some(crate::css::cascaded_properties::StyleQueryInputs {
length: *self.document_media.length()?,
tree_counting,
color_scheme: self.document_style_computation_inputs.preferred_color_scheme,
@@ -1257,135 +629,13 @@ impl RetainedState {
})
}
- /// Whether the custom declarations of a node, or of one of its pseudo-elements, name a
- /// registered custom property: its drive may need to resolve them again against the font it
- /// settles, as `FullDrive::AwaitsRegisteredContext` says.
- pub(super) fn declares_registered_custom_property(
- &self,
- node: StyleNodeID,
- pseudo: Option<u8>,
- inputs: &bridge::FfiDocumentStyleComputationInputs,
- ) -> bool {
- inputs.custom_property_registry().has_registrations()
- && self
- .cascaded_custom_declarations_of(node, pseudo)
- .is_some_and(|cascaded| self.declarations_name_a_registered_custom_property(&cascaded, inputs))
- }
-
- pub(super) fn declarations_name_a_registered_custom_property(
- &self,
- cascaded: &[(CustomDeclaration, RetainedStyleValueData)],
- inputs: &bridge::FfiDocumentStyleComputationInputs,
- ) -> bool {
- let registry = inputs.custom_property_registry();
- registry.has_registrations()
- && cascaded.iter().any(|(declared, _)| {
- self.declared_custom_property_name(declared.name)
- .is_some_and(|name| registry.name_is_registered(&name.text))
- })
- }
-
- pub(super) fn declares_custom_property_registered_with_syntax(
- &self,
- node: StyleNodeID,
- inputs: &bridge::FfiDocumentStyleComputationInputs,
- ) -> bool {
- let registry = inputs.custom_property_registry();
+ /// Whether the custom property a declaration names is registered.
+ pub(super) fn custom_property_name_is_registered(&self, name: StyleAtomID) -> bool {
+ let registry = self.document_style_computation_inputs.custom_property_registry();
registry.has_registrations()
&& self
- .cascaded_custom_declarations_of(node, None)
- .is_some_and(|cascaded| {
- cascaded.iter().any(|(declared, _)| {
- self.declared_custom_property_name(declared.name)
- .is_some_and(|name| registry.name_has_syntax(&name.text))
- })
- })
- }
-
- /// Construct a registered value context with the subject's query containers' sizes.
- pub(super) fn registered_value_context(
- &self,
- node: StyleNodeID,
- mut length: crate::css::style_compute::FfiLengthResolutionContext,
- color_scheme: u8,
- subject_is_pseudo_element: bool,
- ) -> RegisteredValueContext {
- self.container_unit_bases(node, subject_is_pseudo_element)
- .apply_to(&mut length);
- RegisteredValueContext { length, color_scheme }
- }
-
- /// What a registered custom property computes against: the record's lengths, the subject's
- /// query container sizes, and the color scheme its table settled. `None` for a record without a font.
- pub(super) fn record_registered_value_context(
- &self,
- node: StyleNodeID,
- record: computed::FinalStyleRecordID,
- subject_is_pseudo_element: bool,
- ) -> Option<RegisteredValueContext> {
- let view = self.computed_group_sets.style_record_view(record.raw())?;
- let length = self.record_length_resolution_context(&view)?;
- let table = view.longhand_table?;
- let color_scheme = u8::try_from(table.effective_color_scheme())
- .unwrap_or(self.document_style_computation_inputs.preferred_color_scheme);
- Some(self.registered_value_context(node, length, color_scheme, subject_is_pseudo_element))
- }
-
- /// What a registered custom property computes against where the caller brings nothing
- /// better: the record the node holds, as a row keeping its font reads it, else the one its
- /// parent holds, as a first record's provisional environment reads it before the drive
- /// settles its font, else the document's initial font. A pseudo-element's is its originating
- /// element's.
- pub(super) fn standing_registered_value_context(
- &self,
- node: StyleNodeID,
- pseudo: Option<u8>,
- ) -> RegisteredValueContext {
- let own = self.computed_group_sets.assigned_style_record(node);
- let record = match pseudo {
- Some(_) => own,
- None => own.or_else(|| {
- self.tree
- .inheritance_parent(node)
- .and_then(|parent| self.computed_group_sets.assigned_style_record(parent))
- }),
- };
- if let Some(context) =
- record.and_then(|record| self.record_registered_value_context(node, record, pseudo.is_some()))
- {
- return context;
- }
- use crate::css::style_compute::{FfiFontMetrics, FfiLengthResolutionContext};
- let inputs = &self.document_style_computation_inputs;
- let initial = FfiFontMetrics {
- font_size: inputs.initial_font_size,
- x_height: inputs.initial_font_x_height,
- cap_height: inputs.initial_font_cap_height,
- zero_advance: inputs.initial_font_zero_advance,
- line_height: 0.0,
- };
- self.registered_value_context(
- node,
- FfiLengthResolutionContext {
- viewport_width: inputs.viewport_width,
- viewport_height: inputs.viewport_height,
- font_metrics: initial,
- root_font_metrics: initial,
- font_metrics_depend_on_viewport_metrics: false,
- root_font_metrics_depend_on_viewport_metrics: false,
- has_container_width_basis: false,
- has_container_height_basis: false,
- container_width_basis: 0.0,
- container_height_basis: 0.0,
- container_width_basis_depends_on_viewport_metrics: false,
- container_height_basis_depends_on_viewport_metrics: false,
- subject_inline_axis_is_horizontal: true,
- resolved_viewport_relative_length: std::ptr::null_mut(),
- zoom: 1.0,
- },
- inputs.preferred_color_scheme,
- pseudo.is_some(),
- )
+ .declared_custom_property_name(name)
+ .is_some_and(|name| name.with_fly_string(|name| registry.is_registered(name)))
}
/// What the custom function calls in the values of a node, or of one of its pseudo-elements,
@@ -1398,7 +648,21 @@ impl RetainedState {
node: StyleNodeID,
pseudo: Option<u8>,
) -> Option<PreparedCustomFunctions<'a>> {
- let (caller_scope, visible) = snapshot.scope_functions(self.tree.tree_scope(node));
+ self.prepare_custom_functions_with(snapshot, node, |containers| {
+ self.container_conditions_verdict(containers, node, pseudo.is_some())
+ })
+ }
+
+ /// What `prepare_custom_functions` says, with `verdict` deciding the container conditions.
+ pub(super) fn prepare_custom_functions_with<'a>(
+ &self,
+ snapshot: &'a DocumentFunctionSnapshot,
+ node: StyleNodeID,
+ verdict: impl Fn(
+ &[std::sync::Arc<crate::css::container_conditions::ContainerConditionsData>],
+ ) -> Option<super::container_queries::ContainerVerdict>,
+ ) -> Option<PreparedCustomFunctions<'a>> {
+ let (caller_scope, visible) = snapshot.scope_functions(self.projection.tree_scope(node));
let visible_definitions = visible.map_or(&[][..], |visible| visible.definitions.as_slice());
let mut container_effects: Option<super::container_queries::ContainerVerdict> = None;
let mut reads_attributes = false;
@@ -1408,7 +672,7 @@ impl RetainedState {
let mut selected = Vec::new();
for input in selected_inputs.iter().map(|&index| &function.inputs[index]) {
if !input.containers.is_empty() {
- let verdict = self.container_conditions_verdict(&input.containers, node, pseudo.is_some())?;
+ let verdict = verdict(&input.containers)?;
let matches = verdict.matches;
container_effects.get_or_insert_default().add_reads(verdict);
if !matches {
@@ -1437,476 +701,16 @@ impl RetainedState {
})
}
- fn cascaded_custom_property_reads(
- &mut self,
- cascaded: &[(CustomDeclaration, RetainedStyleValueData)],
- ) -> Option<CustomPropertyNames> {
- let mut declarations = Vec::with_capacity(cascaded.len());
- for (declared, value) in cascaded {
- if !matches!(declared.operator, CascadeOperator::Declared | CascadeOperator::Initial) {
- return None;
- }
- let name = Arc::clone(&self.declared_custom_property_name(declared.name)?.text);
- declarations.push((declared.operator, value, name));
- }
- // OPTIMIZATION: Elements alike in their rules cascade the same declarations, which read the same names.
- let hash = intern_table::content_hash(
- declarations
- .iter()
- .map(|(operator, value, name)| (*operator, value.pointer(), Arc::as_ptr(name).cast::<u16>()))
- .collect::<SmallVec<[_; 16]>>(),
- );
- if let Some(memoized) = self.custom_property_reads_by_declarations.get(hash, &declarations) {
- return memoized;
- }
- let mut names = Vec::new();
- let mut reads_are_listed = true;
- for (_, value, name) in &declarations {
- if !append_custom_property_reads(value.data(), &mut names) {
- reads_are_listed = false;
- break;
- }
- // A declared name counts as a read. An environment leaves out a declared value equal to the
- // one it inherits.
- names.push(Arc::clone(name));
- }
- let reads = reads_are_listed.then(|| sorted_custom_property_names(names));
- self.custom_property_reads_by_declarations
- .remember(hash, &declarations, reads.clone());
- reads
- }
-
/// The name a cascaded custom declaration names, as its store entry keys it. A block's
/// publication notes every custom property name it declares before the block is set, so a
/// live declaration's name is always known.
- fn declared_custom_property_name(&self, name: StyleAtomID) -> Option<&CustomPropertyName> {
+ pub(super) fn declared_custom_property_name(&self, name: StyleAtomID) -> Option<&CustomPropertyName> {
let noted = self.custom_property_environments.name(name);
debug_assert!(
noted.is_some(),
"a custom declaration's name is noted at its publication"
);
- noted.filter(|noted| noted.raw.raw() != 0)
- }
-
- /// The store behind an environment a node inherits, null for the empty one. A record that
- /// names an environment keeps its store alive, and C++ makes a store for every environment,
- /// so a parent's is always held. `None` if it is not anyway: an environment built over no
- /// store would drop every custom property the node inherits.
- fn inherited_environment_store(&self, environment: u64) -> Option<Option<Arc<CustomPropertyStore>>> {
- if environment == 0 {
- return Some(None);
- }
- let store = self.custom_property_environments.store(environment);
- debug_assert!(store.is_some(), "an inherited environment keeps its store");
- store.cloned().map(Some)
- }
-
- /// The environment of a node the engine computes a record for: the one it inherits of its
- /// parent's when its cascade declares no custom property, else what its declarations resolve
- /// to over that one. What a node inherits is the parent's environment without the custom
- /// properties a registration keeps from inheriting, while `inherit` reads the parent's whole.
- /// A registered name computes against `registered`, else against what
- /// `standing_registered_value_context` says. Refused when an input is missing.
- pub(super) fn engine_custom_property_environment(
- &mut self,
- node: StyleNodeID,
- parent_environment: u64,
- inputs: &bridge::FfiDocumentStyleComputationInputs,
- registered: Option<&RegisteredValueContext>,
- ) -> Drive<u64> {
- self.engine_custom_property_environment_of(node, None, parent_environment, inputs, registered)
- }
-
- /// `engine_custom_property_environment` for an element whose cascade declares no registered custom property: the
- /// environment an element alike in its match answer, its tree and the environment it inherits resolved to.
- pub(super) fn engine_custom_property_environment_by_answer(
- &mut self,
- node: StyleNodeID,
- parent_environment: u64,
- inputs: &bridge::FfiDocumentStyleComputationInputs,
- ) -> Drive<u64> {
- let key = self.environment_by_answer_key(node, parent_environment, inputs);
- if let Some(key) = key
- && let Some(memoized) = self.custom_property_environments_by_answer.get(&key).cloned()
- {
- self.counters.bump(Counter::EngineCustomPropertyEnvironmentAnswerHits);
- match memoized.reads {
- 0 => self.custom_declaration_reads.remove(&node),
- reads => self.custom_declaration_reads.insert(node, reads),
- };
- match memoized.custom_property_reads {
- None => self.custom_declaration_custom_property_reads.remove(&node),
- Some(reads) => self.custom_declaration_custom_property_reads.insert(node, reads),
- };
- return Ok(memoized.environment);
- }
- self.last_custom_property_environment_memoizable = false;
- let environment = self.engine_custom_property_environment(node, parent_environment, inputs, None)?;
- if let Some(key) = key
- && self.last_custom_property_environment_memoizable
- {
- let memoized = EnvironmentByAnswer {
- environment,
- reads: self.custom_declaration_reads.get(&node).copied().unwrap_or(0),
- custom_property_reads: self.custom_declaration_custom_property_reads.get(&node).cloned(),
- };
- self.custom_property_environments_by_answer.insert(key, memoized);
- }
- Ok(environment)
- }
-
- /// What decides an element's custom declarations, where its published match answer does: no batch of matches
- /// stands in for the answer, the element's inline style declares no custom property, and no container condition
- /// gates a rule of the answer declaring one.
- fn environment_by_answer_key(
- &self,
- node: StyleNodeID,
- parent_environment: u64,
- inputs: &bridge::FfiDocumentStyleComputationInputs,
- ) -> Option<EnvironmentByAnswerKey> {
- if self.facts.element_custom_declarations_written(node).is_some() {
- return None;
- }
- let gated = |rule: RuleID| {
- self.program.rule_is_gated_by_container_query(rule) && !self.program.custom_declarations_of(rule).is_empty()
- };
- let answer_id = if let Some(matches) = self.batch_custom_property_matches.get(&node) {
- if matches.iter().any(|entry| entry.pseudo.is_none() && gated(entry.rule)) {
- return None;
- }
- *self.batch_custom_property_answers.get(&node)?
- } else {
- let (published, answer) = Self::published_answer_lookup(
- &self.published_match_answers,
- self.batch_matching_traversal.as_deref(),
- node,
- )?;
- let matches = published.matches_for(answer)?;
- if matches
- .iter()
- .any(|entry| entry.pseudo_element.is_none() && gated(entry.rule))
- {
- return None;
- }
- answer.cascade_input?
- };
- Some(EnvironmentByAnswerKey {
- answer: answer_id,
- tree_scope: self.tree.tree_scope(node),
- parent_environment,
- registration_generation: inputs.custom_property_registration_generation,
- })
- }
-
- /// Forget the environments taken by match answer, whose identities may be handed out again.
- pub(super) fn forget_custom_property_environments_by_answer(&mut self) {
- self.custom_property_environments_by_answer.clear();
- }
-
- /// What `engine_custom_property_environment` says of the element, for one of its
- /// pseudo-elements over the element's own environment.
- pub(super) fn engine_custom_property_environment_of(
- &mut self,
- node: StyleNodeID,
- pseudo: Option<u8>,
- parent_environment: u64,
- inputs: &bridge::FfiDocumentStyleComputationInputs,
- registered: Option<&RegisteredValueContext>,
- ) -> Drive<u64> {
- if !self.any_custom_property_is_declared() {
- if pseudo.is_none() {
- self.custom_declaration_reads.remove(&node);
- self.custom_declaration_custom_property_reads.remove(&node);
- }
- self.last_custom_property_environment_memoizable = true;
- return Ok(self.custom_property_environments.inheritable(parent_environment));
- }
- // A node the engine drives has the match answer its winners came from, and a published
- // block carries a written value for each custom declaration, so the cascade answers. One
- // that does not is refused rather than resolved without the node's own declarations.
- let cascaded = self.cascaded_custom_declarations_of(node, pseudo);
- debug_assert!(cascaded.is_some(), "a driven node's custom declarations cascade");
- let Some(cascaded) = cascaded else {
- self.counters.bump(Counter::EngineCustomPropertyEnvironmentBails);
- return Err(Unanswered::Refused);
- };
- self.note_custom_declaration_reads(node, pseudo, &cascaded);
- self.engine_custom_property_environment_over(node, pseudo, cascaded, parent_environment, inputs, registered)
- }
-
- /// Note what the custom declarations cascaded for an element or one of its pseudo-elements
- /// read beyond the environment they resolve over, whatever they resolve to: the host notes it
- /// beside the element's record. The element's own resolve first, and its pseudo-elements'
- /// only add to what they found.
- pub(super) fn note_custom_declaration_reads(
- &mut self,
- node: StyleNodeID,
- pseudo: Option<u8>,
- cascaded: &[(CustomDeclaration, RetainedStyleValueData)],
- ) {
- let custom_property_reads = (!cascaded.is_empty()).then(|| self.cascaded_custom_property_reads(cascaded));
- match (custom_property_reads, pseudo) {
- (None, None) => {
- self.custom_declaration_custom_property_reads.remove(&node);
- }
- (None, Some(_)) => {}
- (Some(reads), None) => {
- self.custom_declaration_custom_property_reads.insert(node, reads);
- }
- (Some(reads), Some(_)) => {
- let merged = match (self.custom_declaration_custom_property_reads.remove(&node), reads) {
- (None, reads) => reads,
- (Some(Some(existing)), Some(reads)) => Some(sorted_custom_property_names(
- existing.iter().chain(reads.iter()).cloned().collect(),
- )),
- (Some(_), _) => None,
- };
- self.custom_declaration_custom_property_reads.insert(node, merged);
- }
- }
- let reads = cascaded
- .iter()
- .fold(0, |reads, (_, value)| reads | substitution_reads(value.data()));
- match (reads, pseudo) {
- (0, None) => {
- self.custom_declaration_reads.remove(&node);
- }
- (0, Some(_)) => {}
- (reads, None) => {
- self.custom_declaration_reads.insert(node, reads);
- }
- (reads, Some(_)) => *self.custom_declaration_reads.entry(node).or_default() |= reads,
- }
- }
-
- /// What `engine_custom_property_environment_of` says of custom declarations the caller
- /// cascaded for the node or one of its pseudo-elements; `attr()` among them reads the node's
- /// attributes.
- pub(super) fn engine_custom_property_environment_over(
- &mut self,
- node: StyleNodeID,
- pseudo: Option<u8>,
- cascaded: Vec<(CustomDeclaration, RetainedStyleValueData)>,
- parent_environment: u64,
- inputs: &bridge::FfiDocumentStyleComputationInputs,
- registered: Option<&RegisteredValueContext>,
- ) -> Drive<u64> {
- let inherited_environment = self.custom_property_environments.inheritable(parent_environment);
- if cascaded.is_empty() {
- self.last_custom_property_environment_memoizable = true;
- return Ok(inherited_environment);
- }
- let registry_ref = inputs.custom_property_registry();
- // A registered name computes against the element's own font and viewport, so what it
- // resolves to is the element's alone and takes no memo.
- let registered = self
- .declarations_name_a_registered_custom_property(&cascaded, inputs)
- .then(|| {
- registered
- // A backing element supplies its font; query containers belong to its originating element.
- .map(|registered| {
- self.registered_value_context(
- node,
- registered.length,
- registered.color_scheme,
- pseudo.is_some(),
- )
- })
- .unwrap_or_else(|| self.standing_registered_value_context(node, pseudo))
- });
- // A custom function call reads the definitions its scope sees, with the blocks of
- // declarations their conditions select for the element. What those conditions read of
- // the containers is noted once the environment resolves.
- let mut container_effects = None;
- let functions = if cascaded
- .iter()
- .any(|(_, value)| value_calls_custom_functions(value.data()))
- {
- // A container condition the engine cannot decide asks about an ancestor the host styles
- // in this update: the row waits for it.
- let Some(mut functions) = self.prepare_custom_functions(&self.document_functions, node, pseudo) else {
- self.counters.bump(Counter::EngineComputedRecordBailRecordParent);
- return Err(Unanswered::AwaitsParent);
- };
- container_effects = functions.container_effects.take();
- Some(functions)
- } else {
- None
- };
- // An `attr()` among the declarations, or in the declarations of a function they call,
- // reads the element's attributes, so what they resolve to is the element's alone and
- // takes no memo.
- let reads_attributes = functions.as_ref().is_some_and(|functions| functions.reads_attributes)
- || cascaded.iter().any(|(_, value)| value_reads_attributes(value.data()));
- // So does an `if()`, whose conditions read the document's media features and the
- // element's lengths, and so does a function call, which may hold one.
- let reads_conditions =
- functions.is_some() || cascaded.iter().any(|(_, value)| value_reads_conditions(value.data()));
- let memoizes = !reads_attributes && !reads_conditions && registered.is_none();
- self.last_custom_property_environment_memoizable = memoizes;
- let key = Self::environment_inputs(
- parent_environment,
- inputs.custom_property_registration_generation,
- &cascaded,
- );
- // An environment C++ resolved for an element alike in its declarations is C++'s own
- // identity, and the host installs no record under one it does not recognise as the
- // engine's: handing it back settles a row the host then computes again. The memo is worth
- // only what it saves, so where it holds such an identity this resolves one of its own.
- let memoized = self.custom_property_environments.memoized(&key);
- let keeps_cpp_environment = memoized.is_some_and(|identity| {
- identity != inherited_environment
- && identity & custom_property_environments::ENGINE_ENVIRONMENT_IDENTITY_BIT == 0
- });
- if memoizes && let Some(identity) = memoized.filter(|_| !keeps_cpp_environment) {
- self.counters.bump(Counter::EngineCustomPropertyEnvironmentMemoHits);
- return Ok(identity);
- }
- let (Some(parent_store), Some(inheritance_store)) = (
- self.inherited_environment_store(inherited_environment),
- self.inherited_environment_store(parent_environment),
- ) else {
- self.counters.bump(Counter::EngineCustomPropertyEnvironmentBails);
- return Err(Unanswered::Refused);
- };
- let parent = parent_store.as_deref();
- let mut values = Vec::with_capacity(cascaded.len());
- for (declared, value) in &cascaded {
- let Some(name) = self.declared_custom_property_name(declared.name) else {
- continue;
- };
- // A value the parent already holds, by identity, declares nothing new.
- if parent.is_some_and(|parent| parent.value_is_identical(name.raw.raw(), value.pointer().cast())) {
- continue;
- }
- values.push((name.raw.raw(), declared.important, value.pointer().cast()));
- }
- if values.is_empty() {
- if let Some(effects) = container_effects {
- self.note_container_effects_for_host(node, effects);
- }
- if memoizes && !keeps_cpp_environment {
- let written_values = cascaded.into_iter().map(|(_, written)| written).collect();
- self.custom_property_environments
- .remember(key, inherited_environment, written_values);
- }
- return Ok(inherited_environment);
- }
- // The attributes an `attr()` among the declarations reads.
- let attributes =
- reads_attributes.then(|| SubstitutionAttributes::of(&self.facts, node, self.html_element_namespace));
- // SAFETY: The values are the program's interned values, live for the call.
- let cascaded_store = unsafe { CustomPropertyStore::cascaded_child(parent_store.clone(), values) };
- let random_function_index = crate::css::parser::value_parser::RandomFunctionIndex::default();
- let mut parse_context = registry_ref.parse_context(&random_function_index);
- parse_context.in_quirks_mode = inputs.in_quirks_mode;
- let media_environment = self.document_media.environment();
- let style_query = reads_conditions
- .then(|| self.style_query_inputs(computed::ComputedStyleTarget::new(node, pseudo.unwrap_or(u8::MAX))))
- .flatten();
- // The custom properties a `style()` query reads are the element's style query references,
- // which the host records with its record.
- let mut style_query_references = None;
- let mut resolution_context = engine_resolution_context(
- &parse_context,
- Some(&cascaded_store),
- inheritance_store.as_deref(),
- registry_ref,
- attributes.as_ref(),
- &media_environment,
- style_query.as_ref(),
- Some(&mut style_query_references),
- functions.as_ref(),
- );
- // A registered value computes as the host computes one: against the element's lengths with
- // its query containers' sizes, its place among its siblings, and the random base values
- // drawn for the element, which the engine keeps. A pseudo-element's are its element's.
- let length = registered.as_ref().map(|registered| &registered.length);
- let tree_counting = registered
- .is_some()
- .then(|| self.sibling_position(node))
- .flatten()
- .map(|position| (u64::from(position.count), u64::from(position.index)));
- let random_base_values = std::cell::RefCell::new(&mut self.random_base_values);
- let draw_random_base_value = |name: &[u16], element_shared: bool| {
- random_base_values.borrow_mut().ensure(Some(node), name, element_shared)
- };
- let finalization = CustomPropertyFinalization {
- length,
- tree_counting,
- random_base_values: &[],
- color_scheme: registered.as_ref().map_or(0, |registered| registered.color_scheme),
- draw_random_base_value: Some(&draw_random_base_value),
- };
- let (rust_store, reads) = resolve_declared_custom_properties(
- &cascaded_store,
- parent_store.as_ref(),
- parent_store.is_some(),
- &mut resolution_context,
- finalization,
- );
- drop(cascaded_store);
- self.counters.bump(Counter::EngineCustomPropertyEnvironmentsResolved);
- // What the registered values and style queries read beyond the element's fonts reaches
- // the element's records as what they read themselves does: a sibling change, a container's size.
- if reads.sibling_position
- || style_query_references
- .as_ref()
- .is_some_and(|dependencies| dependencies.sibling_position)
- {
- *self.custom_declaration_reads.entry(node).or_default() |=
- bridge::FfiNodeRecordReads::SiblingPosition as u8;
- }
- if reads.container_unit_mask != 0
- && let Some(length) = length
- {
- self.note_container_unit_reads_for_host(
- node,
- reads.container_unit_mask,
- length.subject_inline_axis_is_horizontal,
- pseudo.is_some(),
- );
- }
- if let Some(effects) = container_effects {
- self.note_container_effects_for_host(node, effects);
- }
- if style_query_references.is_some() {
- self.note_container_effects_for_host(
- node,
- super::container_queries::ContainerVerdict {
- style_query_references,
- ..Default::default()
- },
- );
- }
- let identity = match rust_store {
- None => inherited_environment,
- Some(rust_store) => {
- if let Some(previous) =
- self.environment_resolving_to_the_same_values(node, pseudo, &rust_store, registry_ref)
- {
- previous
- } else {
- self.custom_property_environments.adopt_engine_environment(
- rust_store,
- inherited_environment,
- parent_store.as_deref(),
- registry_ref,
- )
- }
- }
- };
- // A viewport change reaches the records under the environment. One the element shares with
- // its parent is the parent's too, which then restyles with it.
- if reads.viewport {
- self.custom_property_environments.note_reads_viewport(identity);
- }
- if memoizes && !keeps_cpp_environment {
- let written_values = cascaded.into_iter().map(|(_, written)| written).collect();
- self.custom_property_environments
- .remember(key, identity, written_values);
- }
- Ok(identity)
+ noted.filter(|noted| noted.raw() != 0)
}
/// The environment the element's declarations resolved to last, beneath any animation overlay, where they resolve to
@@ -1914,7 +718,21 @@ impl RetainedState {
/// what the element's descendants inherit without moving any value they see. What an environment hands down was
/// decided under the registrations it was resolved under, so only one handing down every value, then and now, is
/// kept.
- fn environment_resolving_to_the_same_values(
+ /// The store of the environment the element's declarations resolved to last, where `resolved` holds the same values
+ /// over the same stores, as [`Self::environment_resolving_to_the_same_values`] keeps it: a store computed again
+ /// gives way to it, so that the element's record holds the store its environment is named by.
+ pub(super) fn store_resolving_to_the_same_values(
+ &self,
+ node: StyleNodeID,
+ pseudo: Option<u8>,
+ resolved: &Arc<CustomPropertyStore>,
+ ) -> Option<Arc<CustomPropertyStore>> {
+ let registry = self.document_style_computation_inputs.custom_property_registry();
+ let previous = self.environment_resolving_to_the_same_values(node, pseudo, resolved, registry)?;
+ self.custom_property_environments.store(previous).cloned()
+ }
+
+ pub(super) fn environment_resolving_to_the_same_values(
&self,
node: StyleNodeID,
pseudo: Option<u8>,
@@ -1926,7 +744,7 @@ impl RetainedState {
}
let held = self.element_custom_property_data.get(&node)?;
let previous = held.sampled_over.unwrap_or(held.identity);
- if previous & custom_property_environments::ENGINE_ENVIRONMENT_IDENTITY_BIT == 0
+ if !self.custom_property_environments.is_engine_made(previous)
|| self.custom_property_environments.inheritable(previous) != previous
{
return None;
@@ -1935,41 +753,80 @@ impl RetainedState {
(resolved.hands_down_every_value(registry) && resolved.holds_same_values_as(previous_store)).then_some(previous)
}
- /// What a node's records read beyond their cascade, as `FfiNodeRecordReads` bits, for the row
- /// that installs them: an `attr()`, `inherit()`, `if()` or custom function call in the
- /// element's winners, in its pseudo-elements' (which read the originating element's
- /// attributes), or in the custom properties either declares, as their resolution found; a
- /// tree-counting function in the records the engine derived for the element or its
- /// pseudo-elements, written or substituted, as their installation noted.
- pub(super) fn node_record_reads(&self, node: StyleNodeID) -> u8 {
- let groups = self.current_winner_groups();
- let state = match groups.token_for(WinnerGroupKey::current(node, self.program.version())) {
- Lookup::Known((_, state)) => Some(state),
- _ => None,
- };
- let mut reads = self.custom_declaration_reads.get(&node).copied().unwrap_or(0);
- for state in state
- .into_iter()
- .chain(groups.pseudo_states(node).map(|(_, _, state, _)| state))
- {
- let state_reads = self.state_reads(node, state);
- if state_reads & cascade::STATE_READS_ATTRIBUTES != 0 {
- reads |= bridge::FfiNodeRecordReads::Attributes as u8;
- }
- if state_reads & cascade::STATE_READS_INHERIT_FUNCTION != 0 {
- reads |= bridge::FfiNodeRecordReads::InheritFunction as u8;
- }
- if state_reads & cascade::STATE_READS_IF_FUNCTION != 0 {
- reads |= bridge::FfiNodeRecordReads::IfFunction as u8;
- }
- if state_reads & cascade::STATE_READS_CUSTOM_FUNCTION != 0 {
- reads |= bridge::FfiNodeRecordReads::CustomFunction as u8;
+ /// The custom properties in a dependency cycle through what an element's animations declare, as
+ /// `--p: var(--q)` in a keyframe beside `--q: var(--p)` on the element. An animated value wins
+ /// the cascade over a declared one, so a name it animates reads as its keyframes do.
+ pub(crate) fn custom_properties_in_an_animated_cycle(
+ &self,
+ node: StyleNodeID,
+ pseudo: Option<u8>,
+ ) -> Vec<crate::css::retained_fly_string::RetainedUtf16FlyString> {
+ type Name = crate::css::retained_fly_string::RetainedUtf16FlyString;
+ let slot = pseudo.map_or(0, |kind| kind + 1);
+ let mut reads: Vec<(Name, Vec<Arc<[u16]>>)> = Vec::new();
+ for effect in self.element_animation_effects(node, slot) {
+ for keyframe in effect.keyframes() {
+ for declaration in effect.custom_declarations_of(keyframe) {
+ let crate::css::style::effect_descriptions::PublishedValue::Declared(value) = &declaration.value
+ else {
+ continue;
+ };
+ let names = named_custom_property_reads(value.data()).unwrap_or_default();
+ let names = names.into_iter().map(Arc::from);
+ match reads.iter_mut().find(|(name, _)| *name == declaration.name) {
+ Some((_, read)) => read.extend(names),
+ None => reads.push((declaration.name.clone(), names.collect())),
+ }
+ }
}
}
- if self.nodes_with_tree_counting_records.contains_key(&node) {
- reads |= bridge::FfiNodeRecordReads::SiblingPosition as u8;
+ if reads.iter().all(|(_, read)| read.is_empty()) {
+ return Vec::new();
}
+ if let Some(declarations) = self
+ .live_style
+ .as_ref()
+ .and_then(|live| live.custom_declarations_of(node, pseudo))
+ {
+ for (declared, value) in declarations
+ .iter()
+ .filter(|(declared, _)| declared.operator() == CascadeOperator::Declared)
+ {
+ let Some(name) = self.declared_custom_property_name(declared.name) else {
+ continue;
+ };
+ let name = Name::from_utf16(name.to_utf16().as_ref());
+ if reads.iter().all(|(animated, _)| *animated != name) {
+ let names = named_custom_property_reads(value.data()).unwrap_or_default();
+ reads.push((name, names.into_iter().map(Arc::from).collect()));
+ }
+ }
+ }
+ let reads_of = |name: &[u16]| {
+ reads
+ .iter()
+ .find(|(candidate, _)| candidate.to_utf16().as_ref() == name)
+ .map(|(_, read)| read.as_slice())
+ };
reads
+ .iter()
+ .filter(|(name, read)| {
+ let name = name.to_utf16();
+ let mut seen: Vec<&[u16]> = Vec::new();
+ let mut waiting: Vec<&[u16]> = read.iter().map(|read| &**read).collect();
+ while let Some(read) = waiting.pop() {
+ if read == name.as_ref() {
+ return true;
+ }
+ if !seen.contains(&read) {
+ seen.push(read);
+ waiting.extend(reads_of(read).unwrap_or_default().iter().map(|read| &**read));
+ }
+ }
+ false
+ })
+ .map(|(name, _)| name.clone())
+ .collect()
}
/// What the custom properties an element declares resolve to once its animations sampled
@@ -2000,7 +857,12 @@ impl RetainedState {
if animated.is_empty() || !self.any_custom_property_is_declared() {
return Ok(Vec::new());
}
- let Some(cascaded) = self.cascaded_custom_declarations_of(node, pseudo) else {
+ // What the element's cascade decided is the record the engine holds for it.
+ let Some(cascaded) = self
+ .live_style
+ .as_ref()
+ .and_then(|live| live.custom_declarations_of(node, pseudo))
+ else {
return Err(());
};
let mut moved: HashSet<Arc<[u16]>> = animated
@@ -2009,12 +871,12 @@ impl RetainedState {
.collect();
let mut candidates: Vec<_> = cascaded
.iter()
- .filter(|(declared, _)| declared.operator == CascadeOperator::Declared)
+ .filter(|(declared, _)| declared.operator() == CascadeOperator::Declared)
.filter_map(|(declared, value)| {
let name = self.declared_custom_property_name(declared.name)?;
Some((name, declared, value, named_custom_property_reads(value.data())))
})
- .filter(|(name, _, _, _)| !moved.contains(&name.text))
+ .filter(|(name, _, _, _)| !moved.contains(name.to_utf16().as_ref()))
.collect();
// What a declaration reads moves where any name it reads moved, and a read the scan
// cannot name may read any.
@@ -2029,7 +891,7 @@ impl RetainedState {
break;
};
let (name, declared, value, _) = candidates.swap_remove(index);
- moved.insert(name.text.clone());
+ moved.insert(Arc::from(name.to_utf16().as_ref()));
readers.push((name.clone(), declared, value));
}
if readers.is_empty() {
@@ -2052,7 +914,7 @@ impl RetainedState {
|| readers.iter().any(|(_, _, value)| value_reads_attributes(value.data()));
let attribute_element = self.substitution_attribute_element(node, pseudo);
let attributes = reads_attributes
- .then(|| SubstitutionAttributes::of(&self.facts, attribute_element, self.html_element_namespace));
+ .then(|| SubstitutionAttributes::of(&self.projection, attribute_element, self.html_element_namespace));
let reads_conditions =
functions.is_some() || readers.iter().any(|(_, _, value)| value_reads_conditions(value.data()));
let style_query = reads_conditions
@@ -2062,7 +924,7 @@ impl RetainedState {
// The readers resolve as declared, over the element's environment, beside the animated values.
let values = readers
.iter()
- .map(|(name, declared, value)| (name.raw.raw(), declared.important, value.pointer().cast()))
+ .map(|(name, declared, value)| (name.raw(), declared.important(), value.pointer().cast()))
.chain(
animated
.iter()
@@ -2070,7 +932,7 @@ impl RetainedState {
)
.collect();
// SAFETY: The base store is live for the sample, and the values are live for the call.
- let base = unsafe { super::environment_move::retained_store(base) };
+ let base = unsafe { retained_store(base) };
// SAFETY: The values are live for the call.
let cascaded_store = unsafe { CustomPropertyStore::cascaded_child(base.clone(), values) };
let registry = self.document_style_computation_inputs.custom_property_registry();
@@ -2078,8 +940,6 @@ impl RetainedState {
let mut parse_context = registry.parse_context(&random_function_index);
parse_context.in_quirks_mode = self.document_style_computation_inputs.in_quirks_mode;
let media_environment = self.document_media.environment();
- // The `style()` queries the declarations read were noted as they resolved beneath the animations.
- let mut style_query_references = None;
// SAFETY: The store the element inherits from is live for the sample.
let inheritance_store = unsafe { inheritance.cast::<CustomPropertyStore>().as_ref() };
let mut resolution_context = engine_resolution_context(
@@ -2090,7 +950,6 @@ impl RetainedState {
attributes.as_ref(),
&media_environment,
style_query.as_ref(),
- Some(&mut style_query_references),
functions.as_ref(),
);
// A registered reader's random() takes the base value drawn for the element as its
@@ -2117,8 +976,8 @@ impl RetainedState {
let readers = readers
.iter()
.filter_map(|(name, _, _)| {
- let name_raw = name.raw.raw();
- if !resolved.declared_names.contains(&name_raw) {
+ let name_raw = name.raw();
+ if !resolved.declares(name_raw) {
return None;
}
let value = resolved.own_values.get(&name_raw)?.value.clone();
@@ -2132,13 +991,19 @@ impl RetainedState {
Ok(readers)
}
+ /// Whether what `written` substitutes to on an element depends only on the custom-property stores the element
+ /// holds and inherits from, and the registrations: whether it reads no attribute, condition or custom function.
+ pub(crate) fn keyframe_substitution_reads_only_stores(written: &StyleValueData) -> bool {
+ !value_reads_attributes(written) && !value_reads_conditions(written) && !value_calls_custom_functions(written)
+ }
+
/// What a keyframe's written value substitutes to on the element being sampled, against the
/// custom-property store the element holds and the one it inherits from, which the host hands
- /// over: what the host's `resolve_unresolved_style_value` makes of it.
+ /// over.
/// `root_custom_property_name` names the custom property the value is written for, and is
/// empty for a longhand. Like a cascaded declaration, a value that does not substitute or parse
/// is guaranteed-invalid, and so is one calling a custom function whose container condition the
- /// engine cannot decide. The custom properties a `style()` query reads are noted in
+ /// engine cannot decide. Whether a `style()` query reads the sibling position is noted in
/// `style_query_references`.
#[allow(clippy::too_many_arguments)]
pub(crate) fn substitute_keyframe_value(
@@ -2160,7 +1025,7 @@ impl RetainedState {
|| functions.as_ref().is_some_and(|functions| functions.reads_attributes);
let attributes = reads_attributes.then(|| {
SubstitutionAttributes::of(
- &self.facts,
+ &self.projection,
self.substitution_attribute_element(node, pseudo_kind),
self.html_element_namespace,
)
@@ -2171,7 +1036,6 @@ impl RetainedState {
let inputs = SubstitutionInputs {
document: &self.document_style_computation_inputs,
media: &self.document_media,
- environment: SubstitutionEnvironment { own: 0, inherited: 0 },
attributes: attributes.as_ref(),
style_query: style_query.as_ref(),
style_query_references: Some(style_query_references),
@@ -2193,72 +1057,6 @@ impl RetainedState {
written,
)
}
-
- /// What a written value with `var()` references substitutes to for a property under an
- /// environment, parsed as the property's value: what the C++ cascade computes for the
- /// declaration, memoized by the written value. An `attr()` reads the element's attributes, an
- /// `inherit()` the environment the element inherits, an `if()` the document's media features
- /// and the element's lengths, and a custom function call the definitions its scope sees and
- /// whatever their declarations read, so any of these values is the element's alone and takes
- /// no memo. A substitution the resolver cannot make, or a substituted source no grammar
- /// accepts, is the guaranteed-invalid value, as in the C++ cascade: the declaration is invalid
- /// at computed-value time. Refused when the inputs lack what the value reads, or an
- /// environment is one the engine holds no store for.
- pub(super) fn substitute_written_value(
- environments: &mut custom_property_environments::CustomPropertyEnvironments,
- inputs: &SubstitutionInputs<'_>,
- property: u16,
- written: RetainedStyleValueData,
- counters: &Counters,
- ) -> Drive<RetainedStyleValueData> {
- let calls_functions = value_calls_custom_functions(written.data());
- let functions = inputs.functions.filter(|_| calls_functions);
- let reads_attributes =
- value_reads_attributes(written.data()) || functions.is_some_and(|functions| functions.reads_attributes);
- let attributes = inputs.attributes.filter(|_| reads_attributes);
- if (reads_attributes && attributes.is_none()) || (calls_functions && functions.is_none()) {
- counters.bump(Counter::EngineComputedRecordBailSubstitution);
- return Err(Unanswered::Refused);
- }
- // A function's declarations may substitute `inherit()` and `if()` as well.
- let reads_inherited_values = calls_functions || value_reads_inherited_values(written.data());
- let memoizes =
- !reads_attributes && !reads_inherited_values && !calls_functions && !value_reads_conditions(written.data());
- let environment = inputs.environment;
- if memoizes && let Some(value) = environments.substitution(&written, property, environment.own) {
- counters.bump(Counter::EngineComputedRecordSubstitutionMemoHits);
- return Ok(value);
- }
- let store_of = |identity| match identity {
- 0 => Some(None),
- identity => environments.store(identity).map(|store| Some(&**store)),
- };
- let Some(store) = store_of(environment.own) else {
- counters.bump(Counter::EngineComputedRecordBailSubstitution);
- return Err(Unanswered::Refused);
- };
- let inheritance_store = if reads_inherited_values {
- let Some(store) = store_of(environment.inherited) else {
- counters.bump(Counter::EngineComputedRecordBailSubstitution);
- return Err(Unanswered::Refused);
- };
- store
- } else {
- None
- };
- // The resolution reads the attributes and the custom functions only where the value does.
- let inputs = SubstitutionInputs {
- attributes,
- functions,
- ..*inputs
- };
- let value = substitute_against_stores(store, inheritance_store, &inputs, property, &[], &written);
- counters.bump(Counter::EngineComputedRecordSubstitutions);
- if memoizes {
- environments.remember_substitution(written, property, environment.own, value.clone_retained());
- }
- Ok(value)
- }
}
/// What a written value substitutes to for a property against a custom-property store and the
@@ -2267,7 +1065,7 @@ impl RetainedState {
/// for, and is empty for a longhand. A substitution the resolver cannot make, or a substituted
/// source no grammar accepts, is the guaranteed-invalid value: the declaration is invalid at
/// computed-value time.
-fn substitute_against_stores(
+pub(super) fn substitute_against_stores(
store: Option<&CustomPropertyStore>,
inheritance_store: Option<&CustomPropertyStore>,
inputs: &SubstitutionInputs<'_>,
@@ -2311,8 +1109,10 @@ fn substitute_against_stores(
source,
contains_attr_tainted_values,
} => {
- // FIXME: Preserve the resolved components rather than retokenizing their normalized serialization.
- let Ok(values) = component_values_from_source(source.as_slice()) else {
+ let Ok(values) = crate::css::style_value::components_of_text(
+ crate::css::css_tokenizer::TokenizerInput::Utf16(&source),
+ crate::css::css_tokenizer::Comments::Separating,
+ ) else {
crate::css::ffi_stats::bump(crate::css::ffi_stats::FfiOp::SubstitutionParse);
return invalid();
};
diff --git a/Libraries/LibWeb/Rust/src/css/style/custom_property_environments.rs b/Libraries/LibWeb/Rust/src/css/style/custom_property_environments.rs
index 2cf9de7e1cc..f13b644f574 100644
--- a/Libraries/LibWeb/Rust/src/css/style/custom_property_environments.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/custom_property_environments.rs
@@ -21,76 +21,42 @@ use super::fast_hash::FastSet as HashSet;
use super::index::StyleAtomID;
use crate::css::custom_properties::{CustomPropertyRegistry, CustomPropertyStore};
use crate::css::retained_fly_string::RetainedUtf16FlyString;
-use crate::css::style_value::RetainedStyleValueData;
-/// How many substituted values the engine keeps before starting over.
-const SUBSTITUTION_MEMO_LIMIT: usize = 1 << 16;
-
-/// The bit that marks an environment identity as one the engine minted. C++ mints its own from a
-/// counter; the two never collide.
-pub(super) const ENGINE_ENVIRONMENT_IDENTITY_BIT: u64 = 1 << 62;
-
-/// One custom property an element's cascade decided: its name, its importance, and the value it
-/// was written with, by identity. Two spellings of one value can serialize differently, so the
-/// written value is what an environment resolves from and what names it.
-#[derive(Clone, Copy, PartialEq, Eq, Hash)]
-pub(super) struct CascadedCustomProperty {
- pub(super) name: StyleAtomID,
- pub(super) important: bool,
- pub(super) written_value: usize,
-}
-
-/// What decides an engine-computed environment: the environment inherited, the registrations in
-/// force, and the custom properties the element's cascade decided, in cascade order. Two elements
-/// alike in these resolve alike.
-#[derive(Clone, PartialEq, Eq, Hash)]
-pub(super) struct EnvironmentInputs {
- pub(super) parent: u64,
- pub(super) registration_generation: u64,
- pub(super) cascaded: Box<[CascadedCustomProperty]>,
+/// The identity of the environment `store` is: its address. A store names one environment, and the catalogs keep it
+/// alive while they name it, so no other store takes its address while the identity is in use.
+pub(super) fn environment_identity(store: &Arc<CustomPropertyStore>) -> u64 {
+ Arc::as_ptr(store) as usize as u64
}
-/// An environment the engine resolved: its store, and the environment it was resolved over.
+/// The store behind an environment, and for one the engine resolved, the environment it was resolved over.
#[derive(Clone)]
-struct EngineEnvironment {
- store: RetainedCustomPropertyStore,
- parent: u64,
+struct Environment {
+ store: Arc<CustomPropertyStore>,
+ /// `None` for an environment C++ published.
+ parent: Option<ResolvedOver>,
}
-/// An environment memo entry and the written values whose addresses name its key. Keeping those
-/// values alive prevents later declarations from being allocated at the same addresses.
+/// The environment one the engine resolved was resolved over, whose store it holds, so that no other store takes the
+/// address that identifies it for as long as this names it.
#[derive(Clone)]
-struct MemoizedEnvironment {
+struct ResolvedOver {
identity: u64,
- _written_values: Box<[RetainedStyleValueData]>,
+ _store: Option<Arc<CustomPropertyStore>>,
}
-/// One substituted value and the written value whose identity names it. Keeping the written value
-/// alive prevents a later declaration from being allocated at the same address as the key.
-#[derive(Clone)]
-struct MemoizedSubstitution {
- written_value: RetainedStyleValueData,
- value: RetainedStyleValueData,
-}
-
-/// One strong reference to a custom-property store, released with the handle.
-#[derive(Clone)]
-pub(crate) struct RetainedCustomPropertyStore(Arc<CustomPropertyStore>);
-
-impl RetainedCustomPropertyStore {
- /// # Safety
- /// `store` must be a live raw `Arc` pointer to a `CustomPropertyStore`.
- pub(super) unsafe fn from_borrowed(store: *const c_void) -> Self {
- let store = store.cast::<CustomPropertyStore>();
- // SAFETY: Guaranteed by the caller.
- unsafe {
- Arc::increment_strong_count(store);
- Self(Arc::from_raw(store))
- }
+/// A strong reference to the custom-property store `store` names, if it names one.
+///
+/// # Safety
+/// `store` must be null or a live raw `Arc` pointer to a `CustomPropertyStore`.
+pub(super) unsafe fn retained_store(store: *const c_void) -> Option<Arc<CustomPropertyStore>> {
+ if store.is_null() {
+ return None;
}
-
- pub(super) fn store(&self) -> &Arc<CustomPropertyStore> {
- &self.0
+ let store = store.cast::<CustomPropertyStore>();
+ // SAFETY: Guaranteed by the caller.
+ unsafe {
+ Arc::increment_strong_count(store);
+ Some(Arc::from_raw(store))
}
}
@@ -114,59 +80,69 @@ impl SharedUtf16FlyString {
pub(super) fn raw(&self) -> usize {
self.0.raw()
}
-}
-/// What a custom property's name atom spells, and the fly string it is: a store names its entries
-/// by the fly string, and a `var()` reference names one by its text.
-#[derive(Clone)]
-pub(super) struct CustomPropertyName {
- pub(super) raw: SharedUtf16FlyString,
- pub(super) text: Arc<[u16]>,
+ /// What the name spells. The catalog's reference keeps the string alive and its text never changes, so a worker
+ /// may read it.
+ pub(super) fn to_utf16(&self) -> std::borrow::Cow<'_, [u16]> {
+ self.0.to_utf16()
+ }
+
+ /// Answers `read` of the fly string the handle holds, borrowed: no reference is taken or given up.
+ pub(super) fn with_fly_string<R>(&self, read: impl FnOnce(&ak::Utf16FlyString) -> R) -> R {
+ // SAFETY: The handle's reference keeps the string alive for the call, and the borrowed owner is never
+ // dropped, so it gives up no reference.
+ let string = std::mem::ManuallyDrop::new(unsafe { ak::Utf16FlyString::from_raw_owned(self.0.raw()) });
+ read(&string)
+ }
}
+/// The fly string a custom property's name atom is: a store names its entries by the fly string, and a `var()`
+/// reference names one by its text, which the fly string spells.
+pub(super) type CustomPropertyName = SharedUtf16FlyString;
+
#[derive(Clone, Default)]
pub(super) struct CustomPropertyEnvironments {
- stores: HashMap<u64, RetainedCustomPropertyStore>,
+ /// Every environment a record names, whether C++ published it or the engine resolved it.
+ environments: HashMap<u64, Environment>,
names: HashMap<StyleAtomID, CustomPropertyName>,
- engine: HashMap<u64, EngineEnvironment>,
/// The environment a child inherits from one holding custom properties a registration keeps
/// from inheriting, for each such environment; any other environment hands itself down.
inheritable: HashMap<u64, u64>,
/// The environments `inheritable` hands down, gathered by `retain_only`, which keeps the set to
/// reuse its allocation.
handed_down: HashSet<u64>,
- /// The environments holding a registered value resolved against the viewport.
- reads_viewport: HashSet<u64>,
- /// What inputs resolved to which environment, so an element alike in its inputs takes the
- /// environment an earlier one got.
- memo: HashMap<EnvironmentInputs, MemoizedEnvironment>,
- /// The environment an animation overlay's values laid over another base make, by the overlay
- /// and that base.
- overlays_moved: HashMap<(u64, u64), u64>,
- minted: u64,
- /// What a written value substitutes to for a property under an environment, by the written
- /// value's identity: the same declaration under the same environment substitutes alike.
- substitutions: HashMap<(usize, u16, u64), MemoizedSubstitution>,
}
impl CustomPropertyEnvironments {
+ /// The bytes of the catalogs and the stores they hold, each store counted once.
+ pub(super) fn heap_size(&self, sizer: &mut crate::heap_size::HeapSizer) -> usize {
+ use crate::heap_size::{HeapSize, map_bytes, set_bytes};
+ map_bytes(&self.environments)
+ + self
+ .environments
+ .values()
+ .map(|environment| environment.store.heap_size(sizer))
+ .sum::<usize>()
+ + map_bytes(&self.names)
+ + map_bytes(&self.inheritable)
+ + set_bytes(&self.handed_down)
+ }
+
/// Record what a custom property's name atom spells. A name is noted once; the text of an
/// atom never changes.
///
/// # Safety
/// `raw` must be zero or a live `AK::Utf16FlyString` raw representation.
- pub(super) unsafe fn note_name(&mut self, name: StyleAtomID, raw: usize, text: &[u16]) -> bool {
+ pub(super) unsafe fn note_name(&mut self, name: StyleAtomID, raw: usize) -> bool {
if name.is_none() {
return false;
}
let Entry::Vacant(entry) = self.names.entry(name) else {
return false;
};
- let text: Arc<[u16]> = text.into();
- entry.insert(CustomPropertyName {
- raw: SharedUtf16FlyString(unsafe { RetainedUtf16FlyString::from_borrowed_raw(raw) }),
- text,
- });
+ entry.insert(SharedUtf16FlyString(unsafe {
+ RetainedUtf16FlyString::from_borrowed_raw(raw)
+ }));
true
}
@@ -187,9 +163,10 @@ impl CustomPropertyEnvironments {
let Some(store) = store.filter(|_| identity != 0) else {
return;
};
- self.stores
- .entry(identity)
- .or_insert_with(|| RetainedCustomPropertyStore(Arc::clone(store)));
+ self.environments.entry(identity).or_insert_with(|| Environment {
+ store: Arc::clone(store),
+ parent: None,
+ });
}
/// [`Self::retain`], for a store C++ names by its raw `Arc` pointer.
@@ -200,9 +177,10 @@ impl CustomPropertyEnvironments {
if identity == 0 || store.is_null() {
return;
}
- self.stores
- .entry(identity)
- .or_insert_with(|| unsafe { RetainedCustomPropertyStore::from_borrowed(store) });
+ self.environments.entry(identity).or_insert_with(|| Environment {
+ store: unsafe { retained_store(store) }.expect("an environment names a store"),
+ parent: None,
+ });
}
/// The store behind an environment, whether C++ published it or the engine resolved it.
@@ -210,10 +188,7 @@ impl CustomPropertyEnvironments {
if identity == 0 {
return None;
}
- self.stores
- .get(&identity)
- .map(RetainedCustomPropertyStore::store)
- .or_else(|| self.engine.get(&identity).map(|environment| environment.store.store()))
+ self.environments.get(&identity).map(|environment| &environment.store)
}
/// Keep the environment a child inherits from `identity`, which C++ made without the custom
@@ -236,87 +211,45 @@ impl CustomPropertyEnvironments {
self.inheritable.insert(identity, inheritable);
}
- /// The values `overlay`, an element's animation overlay, sampled over another environment, laid
- /// over `base`, which the element's declarations resolve to now.
- pub(super) fn overlay_moved_over(&mut self, overlay: u64, base: u64) -> u64 {
- if let Some(&identity) = self.overlays_moved.get(&(overlay, base)) {
- return identity;
- }
- let overlay_store = self.store(overlay);
- debug_assert!(overlay_store.is_some(), "an element's overlay was noted with its store");
- let Some(overlay_store) = overlay_store else {
- return base;
- };
- let store = CustomPropertyStore::animated_values_over(overlay_store, self.store(base).map(Arc::as_ref));
- let identity = self.mint(Arc::new(store), base);
- self.overlays_moved.insert((overlay, base), identity);
- identity
- }
-
/// The environment a child inherits from `identity`.
pub(super) fn inheritable(&self, identity: u64) -> u64 {
self.inheritable.get(&identity).copied().unwrap_or(identity)
}
- /// Note that an environment holds a registered value resolved against the viewport.
- pub(super) fn note_reads_viewport(&mut self, identity: u64) {
- if identity != 0 {
- self.reads_viewport.insert(identity);
- }
- }
-
- /// Whether an environment holds a registered value resolved against the viewport.
- pub(super) fn reads_viewport(&self, identity: u64) -> bool {
- self.reads_viewport.contains(&identity)
+ /// Whether the engine resolved the environment `identity` names, rather than C++.
+ pub(super) fn is_engine_made(&self, identity: u64) -> bool {
+ self.environments
+ .get(&identity)
+ .is_some_and(|environment| environment.parent.is_some())
}
/// An engine-resolved environment's store and the environment it was resolved over.
pub(super) fn engine_environment(&self, identity: u64) -> Option<(&Arc<CustomPropertyStore>, u64)> {
- self.engine
- .get(&identity)
- .map(|environment| (environment.store.store(), environment.parent))
- }
-
- pub(super) fn memoized(&self, inputs: &EnvironmentInputs) -> Option<u64> {
- self.memo.get(inputs).map(|environment| environment.identity)
- }
-
- /// Remember what inputs resolved to, which may be the inherited environment itself.
- pub(super) fn remember(
- &mut self,
- inputs: EnvironmentInputs,
- identity: u64,
- written_values: Vec<RetainedStyleValueData>,
- ) {
- let environment = MemoizedEnvironment {
- identity,
- _written_values: written_values.into_boxed_slice(),
- };
- match self.memo.entry(inputs) {
- Entry::Occupied(mut entry) => {
- entry.insert(environment);
- }
- Entry::Vacant(entry) => {
- entry.insert(environment);
- }
- }
+ let environment = self.environments.get(&identity)?;
+ Some((&environment.store, environment.parent.as_ref()?.identity))
}
/// Take over a store the engine resolved over `parent`, an environment children inherit, and
- /// give it an identity of the engine's own. What its children inherit is the store without
- /// the custom properties `registry` keeps from inheriting: `parent` again when nothing else
- /// is left that `parent` does not hold.
+ /// give it an identity of the engine's own. What its children inherit is `handed_down`, the
+ /// store without the custom properties `registry` keeps from inheriting, which the record
+ /// holding `store` holds where it holds one: `parent` again when nothing else is left that
+ /// `parent` does not hold.
pub(super) fn adopt_engine_environment(
&mut self,
store: Arc<CustomPropertyStore>,
+ handed_down: Option<&Arc<CustomPropertyStore>>,
parent: u64,
parent_store: Option<&CustomPropertyStore>,
registry: &CustomPropertyRegistry,
) -> u64 {
- let inheritable = store.inheritable(registry);
+ let inheritable = match handed_down {
+ Some(handed_down) if Arc::ptr_eq(handed_down, &store) => None,
+ Some(handed_down) => Some(handed_down.clone()),
+ None => store.inheritable(registry),
+ };
let identity = self.mint(store, parent);
if let Some(inheritable) = inheritable {
- let parent_holds_every_value = inheritable.own_values.iter().all(|(&name, entry)| {
+ let parent_holds_every_value = inheritable.own_values.iter().all(|(name, entry)| {
parent_store.is_some_and(|parent| parent.value_is_identical(name, entry.value.pointer().cast()))
});
let inheritable = if parent_holds_every_value {
@@ -329,62 +262,27 @@ impl CustomPropertyEnvironments {
identity
}
+ /// NB: A store resolved again over another environment, as one an element keeps where what
+ /// its parent hands down moved but its values did not, names the environment it was
+ /// resolved over last.
fn mint(&mut self, store: Arc<CustomPropertyStore>, parent: u64) -> u64 {
- self.minted += 1;
- let identity = ENGINE_ENVIRONMENT_IDENTITY_BIT | self.minted;
- self.engine.insert(
+ let identity = environment_identity(&store);
+ let parent_store = self.environments.get(&parent).map(|parent| parent.store.clone());
+ self.environments.insert(
identity,
- EngineEnvironment {
- store: RetainedCustomPropertyStore(store),
- parent,
+ Environment {
+ store,
+ parent: Some(ResolvedOver {
+ identity: parent,
+ _store: parent_store,
+ }),
},
);
identity
}
- pub(super) fn substitution(
- &self,
- written: &RetainedStyleValueData,
- property: u16,
- environment: u64,
- ) -> Option<RetainedStyleValueData> {
- self.substitutions
- .get(&(written.pointer() as usize, property, environment))
- .map(|substitution| {
- debug_assert_eq!(substitution.written_value.pointer(), written.pointer());
- substitution.value.clone_retained()
- })
- }
-
- /// The registrations changed. What a written value substitutes to under an environment depends
- /// on them: forget those. So does what an environment C++ published hands down, which C++
- /// names again for every environment an element holds as the registrations change, and as it
- /// hands any environment over.
- pub(super) fn registrations_changed(&mut self) {
- self.substitutions.clear();
- }
-
- pub(super) fn remember_substitution(
- &mut self,
- written: RetainedStyleValueData,
- property: u16,
- environment: u64,
- value: RetainedStyleValueData,
- ) {
- if self.substitutions.len() >= SUBSTITUTION_MEMO_LIMIT {
- self.substitutions.clear();
- }
- self.substitutions.insert(
- (written.pointer() as usize, property, environment),
- MemoizedSubstitution {
- written_value: written,
- value,
- },
- );
- }
-
/// Release the stores of environments no record names any more, and forget what resolved to
- /// them and what substituted under them.
+ /// them.
/// What a live environment hands its children stays as long as it does.
pub(super) fn retain_only(&mut self, is_live: impl Fn(u64) -> bool) {
self.inheritable.retain(|&identity, _| is_live(identity));
@@ -392,16 +290,7 @@ impl CustomPropertyEnvironments {
handed_down.clear();
handed_down.extend(self.inheritable.values());
let is_live = |identity| is_live(identity) || handed_down.contains(&identity);
- self.stores.retain(|&identity, _| is_live(identity));
- self.engine.retain(|&identity, _| is_live(identity));
- self.reads_viewport.retain(|&identity| is_live(identity));
- self.memo.retain(|inputs, environment| {
- is_live(environment.identity) && (inputs.parent == 0 || is_live(inputs.parent))
- });
- self.substitutions
- .retain(|&(_, _, environment), _| environment == 0 || is_live(environment));
- self.overlays_moved
- .retain(|&(overlay, base), &mut moved| is_live(overlay) && (base == 0 || is_live(base)) && is_live(moved));
+ self.environments.retain(|&identity, _| is_live(identity));
self.handed_down = handed_down;
}
}
@@ -411,25 +300,13 @@ mod tests {
use super::*;
#[test]
- fn nested_capacity_tracks_names_and_replaced_environment_entries() {
+ fn nested_capacity_tracks_names() {
let mut environments = CustomPropertyEnvironments::default();
// SAFETY: A zero raw representation carries no borrowed fly string.
unsafe {
- assert!(environments.note_name(StyleAtomID(1), 0, &[45, 45, 120]));
- assert!(!environments.note_name(StyleAtomID(1), 0, &[45, 45, 120]));
+ assert!(environments.note_name(StyleAtomID(1), 0));
+ assert!(!environments.note_name(StyleAtomID(1), 0));
}
- let inputs = || EnvironmentInputs {
- parent: 0,
- registration_generation: 1,
- cascaded: Box::new([CascadedCustomProperty {
- name: StyleAtomID(1),
- important: false,
- written_value: 0,
- }]),
- };
- environments.remember(inputs(), 1, Vec::with_capacity(2));
- // Equal keys retain the original key's allocation when replacing the value.
- environments.remember(inputs(), 2, Vec::with_capacity(5));
environments.forget_names(&[StyleAtomID(1), StyleAtomID(1)]);
environments.retain_only(|_| false);
}
diff --git a/Libraries/LibWeb/Rust/src/css/style/font_resolution.rs b/Libraries/LibWeb/Rust/src/css/style/font_resolution.rs
index 339e156098e..b9a59bd52c3 100644
--- a/Libraries/LibWeb/Rust/src/css/style/font_resolution.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/font_resolution.rs
@@ -11,6 +11,8 @@ use super::bridge::{
use super::tree::TreeScopeID;
use crate::css::host_shared::HostShared;
use crate::css::style_value::{RetainedStyleValueData, retain_style_value};
+use crate::fork::ForkShared;
+use smallvec::SmallVec;
use std::ffi::c_void;
/// Resolves one request against the document's published `@font-face` table, through the memo of
@@ -35,72 +37,170 @@ unsafe extern "C" {
fn web_css_font_cascade_memo_unreference(memo: *const c_void);
}
-#[derive(Clone, PartialEq, Eq, Hash)]
-struct FontResolutionKey {
- font_family: usize,
- font_feature_values: [usize; FONT_RESOLUTION_FEATURE_INPUT_COUNT],
+/// The scalars of a request, as bits: a request answers another exactly where both name the same
+/// values and these are equal.
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
+struct FontRequestScalars {
font_size_raw: i32,
font_slope: i32,
font_weight: u64,
font_width: u64,
+ font_size_adjust_value: u64,
+ font_feature_values_scope: u32,
font_optical_sizing: u8,
font_size_adjust: FontSizeAdjustKind,
font_size_adjust_metric: u8,
- font_size_adjust_value: u64,
- font_feature_values_scope: u32,
}
-impl FontResolutionKey {
- fn new(request: FfiFontResolutionRequest) -> Self {
+impl FontRequestScalars {
+ fn of(request: &FfiFontResolutionRequest) -> Self {
Self {
- font_family: request.font_family.address,
- font_feature_values: request.font_feature_values.map(|value| value.address),
font_size_raw: request.font_size_raw,
font_slope: request.font_slope,
font_weight: request.font_weight.to_bits(),
font_width: request.font_width.to_bits(),
+ font_size_adjust_value: request.font_size_adjust_value.to_bits(),
+ font_feature_values_scope: request.font_feature_values_scope,
font_optical_sizing: request.font_optical_sizing,
font_size_adjust: request.font_size_adjust,
font_size_adjust_metric: request.font_size_adjust_metric,
- font_size_adjust_value: request.font_size_adjust_value.to_bits(),
- font_feature_values_scope: request.font_feature_values_scope,
}
}
}
-/// Own the request's family and the feature values it names until the boundary transfers them
-/// into the prepared table.
+/// A hash of the identities of the values `request` names and of its scalars, which the cache
+/// finds its resolutions by.
+fn request_identity_hash(request: &FfiFontResolutionRequest) -> u64 {
+ use std::hash::{Hash, Hasher};
+ let mut hasher = crate::fast_hash::fast_hasher();
+ request.font_family.address.hash(&mut hasher);
+ for value in request.font_feature_values {
+ value.address.hash(&mut hasher);
+ }
+ FontRequestScalars::of(request).hash(&mut hasher);
+ hasher.finish()
+}
+
+/// The value a request names by `handle`, or none for a null one.
+fn requested_value(handle: FfiHostHandle) -> Option<&'static crate::css::style_value::StyleValueData> {
+ // SAFETY: A request names live style values for as long as it is asked about.
+ (!handle.as_pointer().is_null())
+ .then(|| unsafe { &*handle.as_pointer().cast::<crate::css::style_value::StyleValueData>() })
+}
+
+/// A hash of the content of the values a request names.
+fn request_content_hash(request: &FfiFontResolutionRequest) -> u64 {
+ let mut hash =
+ requested_value(request.font_family).map_or(0, crate::css::style_value::StyleValueData::content_hash);
+ for value in request.font_feature_values {
+ hash = hash.rotate_left(7)
+ ^ requested_value(value).map_or(0, crate::css::style_value::StyleValueData::content_hash);
+ }
+ hash
+}
+
+/// A request for a font, which holds the values it names alive for their identities, with its
+/// scalars and the generation of the font environment it was made for.
#[derive(Clone)]
pub(super) struct FontRequest {
- ffi: FfiFontResolutionRequest,
family: RetainedStyleValueData,
- feature_values: [Option<RetainedStyleValueData>; FONT_RESOLUTION_FEATURE_INPUT_COUNT],
+ /// The feature values, each empty where the property has its initial value, boxed only where
+ /// any is set: most requests name none.
+ feature_values: Option<Box<[RetainedStyleValueData; FONT_RESOLUTION_FEATURE_INPUT_COUNT]>>,
+ scalars: FontRequestScalars,
+ generation: u64,
}
+const _: () = assert!(size_of::<FontRequest>() <= 64);
+
impl FontRequest {
pub fn new(ffi: FfiFontResolutionRequest) -> Self {
- let retain = |handle: FfiHostHandle| unsafe {
- RetainedStyleValueData::from_retained_pointer(retain_style_value(handle.as_pointer().cast()))
+ let retain = |handle: FfiHostHandle| {
+ if handle.as_pointer().is_null() {
+ return RetainedStyleValueData::none();
+ }
+ // SAFETY: A request names live style values, a reference to which this takes.
+ unsafe { RetainedStyleValueData::from_retained_pointer(retain_style_value(handle.as_pointer().cast())) }
};
+ let names_feature_values = ffi
+ .font_feature_values
+ .iter()
+ .any(|value| !value.as_pointer().is_null());
Self {
- ffi,
family: retain(ffi.font_family),
- feature_values: ffi
- .font_feature_values
- .map(|value| (!value.as_pointer().is_null()).then(|| retain(value))),
+ feature_values: names_feature_values.then(|| Box::new(ffi.font_feature_values.map(retain))),
+ scalars: FontRequestScalars::of(&ffi),
+ generation: ffi.font_environment_generation,
+ }
+ }
+
+ /// The request, made for the font environment of `generation`.
+ pub fn for_generation(mut self, generation: u64) -> Self {
+ self.generation = generation;
+ self
+ }
+
+ /// The generation of the font environment the request was made for.
+ pub fn generation(&self) -> u64 {
+ self.generation
+ }
+
+ /// The request as the host resolves it, naming the values this holds.
+ fn ffi(&self) -> FfiFontResolutionRequest {
+ let handle = |value: &RetainedStyleValueData| FfiHostHandle::from_pointer(value.pointer().cast());
+ let scalars = self.scalars;
+ FfiFontResolutionRequest {
+ font_family: handle(&self.family),
+ font_feature_values: match &self.feature_values {
+ Some(values) => std::array::from_fn(|index| handle(&values[index])),
+ None => [FfiHostHandle::from_pointer(std::ptr::null()); FONT_RESOLUTION_FEATURE_INPUT_COUNT],
+ },
+ font_size_raw: scalars.font_size_raw,
+ font_slope: scalars.font_slope,
+ font_weight: f64::from_bits(scalars.font_weight),
+ font_width: f64::from_bits(scalars.font_width),
+ font_optical_sizing: scalars.font_optical_sizing,
+ font_size_adjust: scalars.font_size_adjust,
+ font_size_adjust_metric: scalars.font_size_adjust_metric,
+ font_size_adjust_value: f64::from_bits(scalars.font_size_adjust_value),
+ font_feature_values_scope: scalars.font_feature_values_scope,
+ font_environment_generation: self.generation,
}
}
+
+ /// The feature value at `index`, or none where the request names none.
+ fn feature_value(&self, index: usize) -> Option<&crate::css::style_value::StyleValueData> {
+ self.feature_values.as_ref()?[index].optional_data()
+ }
+
+ /// Whether the request names the values `request` names, by identity, and has its scalars:
+ /// it is the same request, whatever generation either was made for.
+ fn is(&self, request: &FfiFontResolutionRequest) -> bool {
+ self.scalars == FontRequestScalars::of(request)
+ && self.family.pointer() as usize == request.font_family.address
+ && (0..FONT_RESOLUTION_FEATURE_INPUT_COUNT).all(|index| {
+ self.feature_values
+ .as_ref()
+ .map_or(0, |values| values[index].pointer() as usize)
+ == request.font_feature_values[index].address
+ })
+ }
+
+ /// Whether the request names values equal to those `request` names, by whatever identities,
+ /// and has its scalars.
+ fn names_values_equal_to(&self, request: &FfiFontResolutionRequest) -> bool {
+ self.scalars == FontRequestScalars::of(request)
+ && self.family.optional_data() == requested_value(request.font_family)
+ && (0..FONT_RESOLUTION_FEATURE_INPUT_COUNT)
+ .all(|index| self.feature_value(index) == requested_value(request.font_feature_values[index]))
+ }
}
+/// One resolution: the request it answers and what the host resolved it to.
#[derive(Clone)]
-
-struct ResolvedFont {
- // Keep the family and feature values alive for the pointer identities in the cache key.
- _font_family: RetainedStyleValueData,
- _font_feature_values: [Option<RetainedStyleValueData>; FONT_RESOLUTION_FEATURE_INPUT_COUNT],
+struct FontResolution {
+ request: FontRequest,
ffi: FfiResolvedFont,
- /// The reference a fork's cache holds to the cascade, which the host's memo frees once the generation changes.
- _font_cascade_list: Option<HeldFontCascadeList>,
}
/// A reference to a cascade, which a cache only holds.
@@ -112,28 +212,94 @@ struct HeldFontCascadeList(#[allow(dead_code)] libgfx_rust::font::FontCascadeLis
unsafe impl Send for HeldFontCascadeList {}
unsafe impl Sync for HeldFontCascadeList {}
+/// The resolutions of one generation, with the indices a lookup finds them by.
+#[derive(Clone, Default)]
+struct FontResolutions {
+ /// Each holding its request once.
+ resolutions: Vec<FontResolution>,
+ /// The resolutions by the hash of their requests' identities.
+ by_identity: HashMap<u64, SmallVec<[u32; 1]>>,
+ /// The resolutions by the content of the values their requests name, for a request naming
+ /// equal values by other identities.
+ by_content: HashMap<u64, SmallVec<[u32; 1]>>,
+}
+
+impl FontResolutions {
+ fn heap_size(&self) -> usize {
+ use crate::heap_size::{map_bytes, small_vec_bytes, vec_bytes};
+ vec_bytes(&self.resolutions)
+ + self
+ .resolutions
+ .iter()
+ .filter(|resolution| resolution.request.feature_values.is_some())
+ .count()
+ * size_of::<[RetainedStyleValueData; FONT_RESOLUTION_FEATURE_INPUT_COUNT]>()
+ + map_bytes(&self.by_identity)
+ + self.by_identity.values().map(small_vec_bytes).sum::<usize>()
+ + map_bytes(&self.by_content)
+ + self.by_content.values().map(small_vec_bytes).sum::<usize>()
+ }
+
+ /// The resolution of `request`, made for its very values.
+ fn find(&self, request: &FfiFontResolutionRequest) -> Option<&FontResolution> {
+ self.by_identity
+ .get(&request_identity_hash(request))?
+ .iter()
+ .map(|&index| &self.resolutions[index as usize])
+ .find(|resolution| resolution.request.is(request))
+ }
+}
+
/// The resolutions this document has already been given, keyed by content and scoped to one
/// font-environment generation. This is retained engine state: an evaluation step reads it and
/// never calls the host.
///
/// It names the cascades it was given without holding a reference to any of them. The host's
-/// cascade memo keeps every cascade it resolves alive until the font environment generation
-/// changes, and a lookup answers only for the generation the cache was filled at. So the engine
-/// never gives up the last reference to a `Gfx::FontCascadeList`, whose destructor releases fonts
-/// into host caches, and nothing in the cache stops it from moving to another thread.
+/// cascade memo keeps every cascade it resolves alive until it publishes the font faces of a later
+/// generation, which empties the cache, and a lookup answers only for the generation the cache was
+/// filled at. So the engine never gives up the last reference to a `Gfx::FontCascadeList`, whose
+/// destructor releases fonts into host caches, and nothing in the cache stops it from moving to
+/// another thread.
///
-/// A fork of the render state sees no generation change, so its cache holds a reference to each
-/// cascade it names instead. See [`Self::start_over_for_fork`].
+/// A fork of the render state shares the resolutions until either side writes, and sees no
+/// publication, so its cache holds a reference of its own to each cascade they name instead. See
+/// [`Self::hold_cascades_for_fork`].
#[derive(Clone, Default)]
pub(super) struct FontResolutionCache {
generation: Option<u64>,
- cache: HashMap<FontResolutionKey, ResolvedFont>,
- holds_cascades: bool,
+ resolutions: ForkShared<FontResolutions>,
+ /// Whether a lookup finds a resolution made for equal values by other identities, which a
+ /// style pass needs: it computes the values its requests name anew each time.
+ matches_by_content: bool,
+ /// The references a fork's cache holds to the cascades its resolutions name, and none in the
+ /// cache of the render state the host writes.
+ held_cascades: Option<Vec<HeldFontCascadeList>>,
+ /// The requests the earlier generations resolved, which the next one is likely to be asked
+ /// for again.
+ carried: Vec<FontRequest>,
/// The shadow tree scopes whose own `@font-feature-values` the published table carries.
feature_values_shadow_scopes: Box<[TreeScopeID]>,
}
impl FontResolutionCache {
+ /// The bytes the cache holds on the heap, but for the values its requests name, which their
+ /// declarations and records hold too.
+ pub(super) fn heap_size(&self) -> usize {
+ use crate::heap_size::vec_bytes;
+ self.resolutions.heap_size()
+ + self.held_cascades.as_ref().map_or(0, vec_bytes)
+ + vec_bytes(&self.carried)
+ + size_of_val::<[TreeScopeID]>(&self.feature_values_shadow_scopes)
+ }
+
+ pub fn matches_by_content(&self) -> bool {
+ self.matches_by_content
+ }
+
+ pub fn set_matches_by_content(&mut self, matches_by_content: bool) {
+ self.matches_by_content = matches_by_content;
+ }
+
pub fn publish_feature_values_shadow_scopes(&mut self, scopes: Box<[TreeScopeID]>) {
self.feature_values_shadow_scopes = scopes;
}
@@ -142,44 +308,125 @@ impl FontResolutionCache {
&self.feature_values_shadow_scopes
}
- /// Empties the cache of a fork of the render state, which holds a reference to each cascade it names from here on:
- /// the host frees the cascades the copied entries name once the generation it resolves at changes, which the fork
- /// never sees.
- pub fn start_over_for_fork(&mut self) {
+ /// Has the cache of a fork of the render state hold a reference to each cascade it names, the shared resolutions'
+ /// and those it resolves from here on: the host frees the cascades of a generation once it publishes the next,
+ /// which the fork never sees. The fork resolves what the state it forked resolved as that state did, at the
+ /// generation of its inputs, whatever the host's font environment moved to since.
+ pub fn hold_cascades_for_fork(&mut self) {
+ if self.held_cascades.is_some() {
+ return;
+ }
+ let held = self
+ .resolutions
+ .resolutions
+ .iter()
+ .map(|resolution| {
+ // SAFETY: The host keeps the cascades of the generation the cache was filled at alive until it
+ // publishes the font faces of the next, which empties the cache first.
+ HeldFontCascadeList(unsafe {
+ libgfx_rust::font::FontCascadeListHandle::retain(resolution.ffi.font_cascade_list.as_pointer())
+ })
+ })
+ .collect();
+ self.held_cascades = Some(held);
+ }
+
+ /// Forget every resolution, as the host published the font faces of a later generation: it frees the cascades of
+ /// the earlier ones from here on.
+ pub fn forget_earlier_generations(&mut self) {
self.generation = None;
- self.cache.clear();
- self.holds_cascades = true;
+ self.carry_requests();
}
pub fn prepare(&mut self, generation: u64) {
if self.generation != Some(generation) {
- self.cache.clear();
+ self.carry_requests();
self.generation = Some(generation);
}
}
+ /// Forget every resolution, keeping the requests they answered.
+ fn carry_requests(&mut self) {
+ let resolutions = self.resolutions.take();
+ self.carried
+ .extend(resolutions.resolutions.into_iter().map(|resolution| resolution.request));
+ if let Some(held) = &mut self.held_cascades {
+ held.clear();
+ }
+ }
+
+ /// Take the requests the earlier generations resolved, which no resolution of this one
+ /// answers yet.
+ pub fn take_carried_requests(&mut self) -> Vec<FontRequest> {
+ // NB: A request carried over several generations is carried once for each, the latest last.
+ let mut taken: HashMap<u64, SmallVec<[usize; 1]>> = HashMap::default();
+ let mut requests: Vec<FontRequest> = Vec::new();
+ for request in std::mem::take(&mut self.carried).into_iter().rev() {
+ let ffi = request.ffi();
+ if self.resolutions.find(&ffi).is_some() {
+ continue;
+ }
+ let same = taken.entry(request_identity_hash(&ffi)).or_default();
+ if same.iter().any(|&index| requests[index].is(&ffi)) {
+ continue;
+ }
+ same.push(requests.len());
+ requests.push(request);
+ }
+ requests.reverse();
+ requests
+ }
+
pub fn lookup(&self, request: FfiFontResolutionRequest) -> Option<FfiResolvedFont> {
if self.generation != Some(request.font_environment_generation) {
return None;
}
- self.cache
- .get(&FontResolutionKey::new(request))
- .map(|resolved| resolved.ffi)
+ if let Some(resolution) = self.resolutions.find(&request) {
+ return Some(resolution.ffi);
+ }
+ if !self.matches_by_content {
+ return None;
+ }
+ // A family or feature value equal to one a resolution was made for resolves the same.
+ let candidates = self.resolutions.by_content.get(&request_content_hash(&request))?;
+ candidates.iter().find_map(|&index| {
+ let resolution = &self.resolutions.resolutions[index as usize];
+ resolution
+ .request
+ .names_values_equal_to(&request)
+ .then_some(resolution.ffi)
+ })
}
fn insert(&mut self, request: FontRequest, ffi: FfiResolvedFont, font_cascade_list: Option<HeldFontCascadeList>) {
// The host resolves every request, to the fallback font where nothing else matches, so the
// resolution always names a list.
debug_assert!(!ffi.font_cascade_list.is_none());
- self.cache.insert(
- FontResolutionKey::new(request.ffi),
- ResolvedFont {
- _font_family: request.family,
- _font_feature_values: request.feature_values,
- ffi,
- _font_cascade_list: font_cascade_list,
- },
- );
+ if let (Some(held), Some(font_cascade_list)) = (&mut self.held_cascades, font_cascade_list) {
+ held.push(font_cascade_list);
+ }
+ let request_ffi = request.ffi();
+ let identity_hash = request_identity_hash(&request_ffi);
+ let resolutions = &mut *self.resolutions;
+ let resolution = FontResolution { request, ffi };
+ let same_request = resolutions.by_identity.get(&identity_hash).and_then(|indices| {
+ indices
+ .iter()
+ .copied()
+ .find(|&index| resolutions.resolutions[index as usize].request.is(&request_ffi))
+ });
+ if let Some(index) = same_request {
+ resolutions.resolutions[index as usize] = resolution;
+ return;
+ }
+ let index = u32::try_from(resolutions.resolutions.len()).expect("a document resolves fewer than 2^32 fonts");
+ resolutions.resolutions.push(resolution);
+ resolutions.by_identity.entry(identity_hash).or_default().push(index);
+ resolutions
+ .by_content
+ .entry(request_content_hash(&request_ffi))
+ .or_default()
+ .push(index);
}
}
@@ -302,7 +549,7 @@ impl FontResolverHost {
Self::with_callbacks(web_css_resolve_font, web_css_resolve_font_for_fork, font_faces)
}
- fn with_callbacks(
+ pub(super) fn with_callbacks(
resolve: ResolveFontCallback,
resolve_for_fork: ResolveFontCallback,
font_faces: PublishedFontFaces,
@@ -323,8 +570,8 @@ impl FontResolverHost {
/// builds and freezes a cascade from the document's font face state. Pending web faces remain
/// in the returned cascade and retain the host's rendering-triggered loading behavior.
pub fn refill(&self, cache: &mut FontResolutionCache, request: FontRequest) {
- cache.prepare(request.ffi.font_environment_generation);
- let resolve = if cache.holds_cascades {
+ cache.prepare(request.generation);
+ let resolve = if cache.held_cascades.is_some() {
self.resolve_for_fork
} else {
self.resolve
@@ -333,11 +580,11 @@ impl FontResolverHost {
resolve(
self.font_faces.memo.as_ptr(),
self.font_faces.snapshot.as_ptr(),
- request.ffi,
+ request.ffi(),
)
};
// SAFETY: A fork's resolution hands over a reference to the cascade it names.
- let font_cascade_list = cache.holds_cascades.then(|| {
+ let font_cascade_list = cache.held_cascades.is_some().then(|| {
HeldFontCascadeList(unsafe {
libgfx_rust::font::FontCascadeListHandle::adopt(ffi.font_cascade_list.as_pointer())
})
@@ -433,7 +680,7 @@ mod tests {
}
#[test]
- fn a_forks_cache_resolves_its_own_cascades_and_holds_them() {
+ fn a_forks_cache_answers_what_it_copied_and_holds_the_cascades() {
let unrefs_before = font_cascade_list_unref_count();
let family = RetainedStyleValueData::from_owned(StyleValueData::Keyword { keyword: 2 });
let host = FontResolverHost::with_callbacks(resolve_font_uncounted, resolve_font_uncounted, unsafe {
@@ -458,11 +705,10 @@ mod tests {
host.refill(&mut resolver, FontRequest::new(request));
assert!(resolver.lookup(request).is_some());
- // The fork names none of the host's cascades, which the host frees once its generation changes.
+ // The fork answers what the cache it copied answered, holding a reference to each cascade, which the host frees
+ // once it publishes another generation.
let mut fork = resolver.clone();
- fork.start_over_for_fork();
- assert!(fork.lookup(request).is_none());
- host.refill(&mut fork, FontRequest::new(request));
+ fork.hold_cascades_for_fork();
assert!(fork.lookup(request).is_some());
assert_eq!(font_cascade_list_unref_count(), unrefs_before);
drop(fork);
diff --git a/Libraries/LibWeb/Rust/src/css/style/layout_style.rs b/Libraries/LibWeb/Rust/src/css/style/layout_style.rs
index bd5602fcaef..42de09f5669 100644
--- a/Libraries/LibWeb/Rust/src/css/style/layout_style.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/layout_style.rs
@@ -8,16 +8,11 @@
//! affected groups, and publishes final animated payloads as an independent base record.
use super::StyleEngine;
-use crate::css::computed_longhand_table::ComputedLonghandTable;
use crate::css::computed_value_types::*;
-use crate::css::computed_values::{
- InheritedBoxValues, clone_group_payload, default_group_payload, release_group_payload, retain_group_payload,
-};
use crate::css::css_enums::{
display_inside, display_internal, display_outside, flex_direction, justify_content, vertical_align,
};
use crate::css::display::FfiDisplay;
-use crate::css::host_shared::{HostShared, SharedPayload};
use crate::css::table_group_builder::group_index;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -44,10 +39,19 @@ pub(crate) struct AnonymousStyleOverrides {
pub columns_from_parent: bool,
}
+/// What an anonymous box derives its record from as it is styled again: the record it held, its parent's, and the one
+/// it takes its column properties from, if any.
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
+pub(crate) struct Reinheritance {
+ record: u64,
+ parent: u64,
+ column_source: Option<u64>,
+}
+
#[derive(Clone, Copy)]
pub(crate) struct DerivedStyleRecord {
pub record: u64,
- pub payloads: crate::layout::node_data::StylePayloadsRef,
+ pub payloads: crate::layout::node_data::LayoutStyleRef,
}
impl DerivedStyleRecord {
@@ -59,7 +63,7 @@ impl DerivedStyleRecord {
.expect("a layout style record is live");
Self {
record,
- payloads: crate::layout::node_data::StylePayloadsRef::new(payloads.as_ptr().cast()),
+ payloads: crate::layout::node_data::LayoutStyleRef::of_groups(payloads),
}
}
}
@@ -76,38 +80,126 @@ macro_rules! groups {
groups! {
BoxValues => BOX,
- InheritedBoxValues => INHERITED_BOX,
AlignmentValues => ALIGNMENT,
SurroundValues => SURROUND,
SizingValues => SIZING,
GridValues => GRID,
- MiscResetValues => MISC_RESET,
+ MiscLayoutValues => MISC_LAYOUT,
+ MiscInteractionValues => MISC_INTERACTION,
EffectsValues => EFFECTS,
AnchorValues => ANCHOR,
+ BorderValues => BORDER,
+ InheritedTextValues => INHERITED_TEXT,
}
-pub(crate) struct LayoutStyle {
- payloads: [SharedPayload; group_index::COUNT],
- longhand_table: HostShared<ComputedLonghandTable>,
- changed: bool,
+/// A style for layout's own use, which no record holds: a base style's groups, with those an edit
+/// wrote replaced by copies. It is never interned or installed.
+#[cfg(test)]
+pub(crate) struct LayoutScratchStyle(crate::css::computed_values::StyleGroups);
+
+#[cfg(test)]
+impl LayoutScratchStyle {
+ /// `base`, with the groups `edit` writes replaced, the rest shared.
+ pub(crate) fn over(
+ base: crate::css::computed_value_views::ComputedValuesView<'_>,
+ edit: impl FnOnce(&mut ScratchGroups),
+ ) -> Self {
+ let mut groups = ScratchGroups {
+ groups: base.record_groups().0.clone(),
+ written: [false; group_index::COUNT],
+ };
+ edit(&mut groups);
+ Self(groups.groups)
+ }
+
+ /// The default groups, with the groups `edit` writes replaced.
+ pub(crate) fn over_defaults(edit: impl FnOnce(&mut ScratchGroups)) -> Self {
+ let defaults = crate::css::computed_values::DefaultGroups::default();
+ Self::over(
+ crate::css::computed_value_views::ComputedValuesView::of(defaults.groups()),
+ edit,
+ )
+ }
+
+ /// The style, for a row to read while this stays in place.
+ pub(crate) fn style(&self) -> crate::layout::node_data::LayoutStyleRef {
+ crate::layout::node_data::LayoutStyleRef::of_groups(&self.0)
+ }
}
-const _: () = assert!(group_index::COUNT == crate::layout::node_data::STYLE_GROUP_COUNT);
+/// The groups of a [`LayoutScratchStyle`] being written: each group is copied the first time it is
+/// written, and the copy is the scratch style's own.
+#[cfg(test)]
+pub(crate) struct ScratchGroups {
+ groups: crate::css::computed_values::StyleGroups,
+ written: [bool; group_index::COUNT],
+}
-impl Drop for LayoutStyle {
- fn drop(&mut self) {
- for (index, payload) in self.payloads.iter().copied().enumerate() {
- release_group_payload(index, payload.as_ptr());
- }
- if !self.longhand_table.is_null() {
- // SAFETY: The constructor retained this frozen table for the builder.
- unsafe {
- crate::css::computed_longhand_table::rust_computed_longhand_table_release(
- self.longhand_table.cast_mut(),
- );
- };
+#[cfg(test)]
+impl ScratchGroups {
+ fn group_mut<T: LayoutStyleGroup>(&mut self) -> &mut T {
+ if !self.written[T::INDEX] {
+ // SAFETY: The private trait pairs each type with its registered group index.
+ unsafe { self.groups.write_group::<T>(T::INDEX, |_| {}) };
+ self.written[T::INDEX] = true;
}
+ // SAFETY: The group is a copy only these groups hold, written through `&mut self` alone, and
+ // the private trait pairs each type with its registered group index.
+ unsafe { &mut *self.groups[T::INDEX].as_ptr().cast_mut().cast::<T>() }
+ }
+
+ pub(crate) fn box_mut(&mut self) -> &mut BoxValues {
+ self.group_mut()
+ }
+
+ pub(crate) fn sizing_mut(&mut self) -> &mut SizingValues {
+ self.group_mut()
+ }
+
+ pub(crate) fn surround_mut(&mut self) -> &mut SurroundValues {
+ self.group_mut()
}
+
+ pub(crate) fn alignment_mut(&mut self) -> &mut AlignmentValues {
+ self.group_mut()
+ }
+
+ pub(crate) fn border_mut(&mut self) -> &mut BorderValues {
+ self.group_mut()
+ }
+
+ pub(crate) fn set_white_space_collapse(&mut self, collapse: u8) {
+ let mut values = self.groups.inherited_values();
+ values.bits = values
+ .bits
+ .with(crate::css::computed_values::StyleBitField::WhiteSpaceCollapse, collapse);
+ self.groups.set_inherited_values(values);
+ }
+
+ pub(crate) fn set_writing_mode(&mut self, writing_mode: u8) {
+ let mut values = self.groups.inherited_values();
+ values.bits = values
+ .bits
+ .with(crate::css::computed_values::StyleBitField::WritingMode, writing_mode);
+ self.groups.set_inherited_values(values);
+ }
+
+ pub(crate) fn set_overflow(&mut self, x: u8, y: u8) {
+ use crate::css::computed_values::StyleBitField;
+ let reset = self
+ .groups
+ .reset_bits()
+ .with(StyleBitField::OverflowX, x)
+ .with(StyleBitField::OverflowY, y);
+ self.groups.set_reset_bits(reset);
+ }
+}
+
+pub(crate) struct LayoutStyle {
+ payloads: crate::css::computed_values::StyleGroups,
+ /// The record whose longhands the style carries, which is read only once the style is interned.
+ longhand_source: Option<u64>,
+ changed: bool,
}
impl LayoutStyle {
@@ -115,45 +207,27 @@ impl LayoutStyle {
let view = engine
.style_record_view(record)
.expect("layout style record must be live");
- let payloads = view
- .payloads
- .try_into()
- .expect("layout styles have every computed group");
- let mut style = Self {
- payloads,
- longhand_table: HostShared::from_option(view.longhand_table),
+ Self {
+ payloads: view.payloads.clone(),
+ longhand_source: Some(record),
changed: false,
- };
- for (index, payload) in style.payloads.iter().copied().enumerate() {
- retain_group_payload(index, payload.as_ptr());
- }
- if !style.longhand_table.is_null() {
- // SAFETY: The record owns a live, frozen table.
- style.longhand_table = HostShared::new(unsafe {
- crate::css::computed_longhand_table::rust_computed_longhand_table_retain(
- style.longhand_table.cast_mut(),
- )
- });
}
- style
}
fn inherited(engine: &StyleEngine, parent: u64) -> Self {
let parent = engine
.style_record_payloads(parent)
.expect("anonymous box parent style must be live");
- let payloads = std::array::from_fn(|index| {
- let payload = if index < super::computed::ENGINE_INHERITED_GROUP_COUNT {
- parent[index]
- } else {
- SharedPayload::new(default_group_payload(index))
- };
- retain_group_payload(index, payload.as_ptr());
- payload
- });
+ let mut payloads = engine.default_groups().groups().clone();
+ for index in
+ crate::css::computed_values::StyleGroupIndex::all().take(super::computed::ENGINE_INHERITED_GROUP_COUNT)
+ {
+ payloads.share_group(parent, index);
+ }
+ payloads.set_inherited_values(parent.inherited_values());
Self {
payloads,
- longhand_table: HostShared::null(),
+ longhand_source: None,
changed: false,
}
}
@@ -162,20 +236,17 @@ impl LayoutStyle {
let parent = engine
.style_record_payloads(parent)
.expect("anonymous box parent style must be live");
- for (index, payload) in parent
- .iter()
- .copied()
- .enumerate()
- .take(super::computed::ENGINE_INHERITED_GROUP_COUNT)
+ for index in
+ crate::css::computed_values::StyleGroupIndex::all().take(super::computed::ENGINE_INHERITED_GROUP_COUNT)
{
- retain_group_payload(index, payload.as_ptr());
- release_group_payload(index, std::mem::replace(&mut self.payloads[index], payload).as_ptr());
+ self.payloads.share_group(parent, index);
}
+ self.payloads.set_inherited_values(parent.inherited_values());
}
fn group<T: LayoutStyleGroup>(&self) -> &T {
// SAFETY: The private trait pairs each type with its registered group index.
- unsafe { self.payloads[T::INDEX].cast::<T>().deref() }
+ unsafe { &*self.payloads[T::INDEX].as_ptr().cast::<T>() }
}
fn edit<T: LayoutStyleGroup>(&mut self, update: impl FnOnce(&mut T)) {
@@ -185,13 +256,8 @@ impl LayoutStyle {
return;
}
self.changed = true;
- // SAFETY: The clone is uniquely owned and has the group type named by T.
- let payload = SharedPayload::new(unsafe { clone_group_payload(T::INDEX, self.payloads[T::INDEX].as_ptr()) });
- unsafe { *payload.cast::<T>().cast_mut() = value };
- release_group_payload(
- T::INDEX,
- std::mem::replace(&mut self.payloads[T::INDEX], payload).as_ptr(),
- );
+ // SAFETY: The private trait pairs each type with its registered group index.
+ unsafe { self.payloads.write_group::<T>(T::INDEX, |payload| *payload = value) };
}
/// Draws text in its color at half its alpha, i.e. `color-mix(in srgb, currentColor 50%, transparent)`, which
@@ -199,15 +265,13 @@ impl LayoutStyle {
fn fade_text_color(&mut self) {
let fade = |color: u32| (color >> 24).div_ceil(2) << 24 | (color & 0x00ff_ffff);
let index = group_index::INHERITED_TEXT;
- // SAFETY: The clone is uniquely owned and is the inherited text group.
- let payload = SharedPayload::new(unsafe { clone_group_payload(index, self.payloads[index].as_ptr()) });
- // SAFETY: As above; the colors are plain values the payload doesn't retain.
+ // SAFETY: The group is the inherited text group.
unsafe {
- let values = &mut *payload.cast::<InheritedTextValues>().cast_mut();
- values.color = fade(values.color);
- values.webkit_text_fill_color = fade(values.webkit_text_fill_color);
- }
- release_group_payload(index, std::mem::replace(&mut self.payloads[index], payload).as_ptr());
+ self.payloads.write_group::<InheritedTextValues>(index, |values| {
+ values.color = fade(values.color);
+ values.webkit_text_fill_color = fade(values.webkit_text_fill_color);
+ });
+ };
self.changed = true;
}
@@ -217,42 +281,40 @@ impl LayoutStyle {
/// The group payloads of this style, for a row's style reads to see in place of its record's, as a record's
/// payloads are named. They address the style where it is, so the caller keeps it in place while reads see them.
- pub(crate) fn payloads_for_style_reads(&self) -> crate::layout::node_data::StylePayloadsRef {
- crate::layout::node_data::StylePayloadsRef::new(self.payloads.as_ptr().cast())
+ pub(crate) fn payloads_for_style_reads(&self) -> crate::layout::node_data::LayoutStyleRef {
+ crate::layout::node_data::LayoutStyleRef::of_groups(&self.payloads)
}
/// Builds the payloads of `groups` again from `table`, a longhand table holding the style's computed values with
/// some of them replaced.
/// The values `animated_overlay` samples over the table win over it where they do over the style's own table.
- pub(crate) fn replace_groups_from_table(
+ pub(crate) fn replace_groups_from_values(
&mut self,
- table: &ComputedLonghandTable,
- animated_overlay: Option<&crate::css::animated_overlay::AnimatedOverlay>,
+ values: &crate::css::computed_values::GroupValues<'_>,
groups: &[usize],
+ defaults: &crate::css::computed_values::DefaultGroups,
) {
+ let source = crate::css::table_group_builder::LonghandSource::Values { values, reads: None };
for &group in groups {
let current = self.payloads[group].as_ptr();
// SAFETY: The style holds a reference to its payload of every group.
let parent = unsafe { crate::css::computed_values::GroupPayloadRef::new(group, current) };
- let payload = crate::css::table_group_builder::rebuild_group_from_table_and_overlay(
- table,
- animated_overlay,
+ let payload = crate::css::table_group_builder::rebuild_group_from_source(
+ &source,
group,
- parent,
+ crate::css::computed_values::GroupShares::new(defaults, group, parent),
0,
0,
None,
)
- .expect("a group of the accepted @position-try properties builds from a longhand table");
- if payload == current {
- release_group_payload(group, payload);
+ .expect("a group of the accepted @position-try properties builds from its values");
+ // SAFETY: The rebuild hands over a reference to a payload of the group.
+ let payload = unsafe { crate::css::computed_values::HeldGroup::adopt(group, payload) };
+ if payload.as_ptr() == current {
continue;
}
self.changed = true;
- release_group_payload(
- group,
- std::mem::replace(&mut self.payloads[group], SharedPayload::new(payload)).as_ptr(),
- );
+ drop(self.payloads.replace(payload));
}
}
@@ -269,25 +331,55 @@ impl LayoutStyle {
}
pub(crate) fn set_overflow(&mut self, x: u8, y: u8) {
- self.edit::<BoxValues>(|values| {
- values.overflow_x = x;
- values.overflow_y = y;
- });
+ use crate::css::computed_values::StyleBitField;
+ let reset = self
+ .payloads
+ .reset_bits()
+ .with(StyleBitField::OverflowX, x)
+ .with(StyleBitField::OverflowY, y);
+ self.set_reset_bits(reset);
+ }
+
+ /// Puts `reset` in place of the style's reset bits.
+ fn set_reset_bits(&mut self, reset: crate::css::computed_value_types::ResetBits) {
+ if reset != self.payloads.reset_bits() {
+ self.changed = true;
+ self.payloads.set_reset_bits(reset);
+ }
+ }
+
+ /// The style's reset bits, with the codes of `source`'s position, float and clear.
+ fn with_position_float_clear_of(
+ &self,
+ source: crate::css::computed_value_types::ResetBits,
+ ) -> crate::css::computed_value_types::ResetBits {
+ use crate::css::computed_values::StyleBitField;
+ [StyleBitField::Position, StyleBitField::Float, StyleBitField::Clear]
+ .into_iter()
+ .fold(self.payloads.reset_bits(), |bits, field| {
+ bits.with(field, source.get(field))
+ })
}
pub(crate) fn set_writing_mode_and_direction(&mut self, writing_mode: u8, direction: u8) {
- self.edit::<InheritedBoxValues>(|values| {
- values.writing_mode = writing_mode;
- values.direction = direction;
- });
+ use crate::css::computed_values::StyleBitField;
+ let mut values = self.payloads.inherited_values();
+ values.bits = values
+ .bits
+ .with(StyleBitField::WritingMode, writing_mode)
+ .with(StyleBitField::Direction, direction);
+ if values != self.payloads.inherited_values() {
+ self.changed = true;
+ self.payloads.set_inherited_values(values);
+ }
}
pub(crate) fn set_scrollbar_width(&mut self, width: u8) {
- self.edit::<MiscResetValues>(|values| values.scrollbar_width = width);
+ self.edit::<MiscInteractionValues>(|values| values.scrollbar_width = width);
}
pub(crate) fn set_overscroll_behavior(&mut self, x: u8, y: u8) {
- self.edit::<MiscResetValues>(|values| {
+ self.edit::<MiscInteractionValues>(|values| {
values.overscroll_behavior_x = x;
values.overscroll_behavior_y = y;
});
@@ -311,20 +403,18 @@ impl LayoutStyle {
// NB: The wrapper is the box that gets positioned, so it keeps the display the table was given, which
// decides where an absolutely positioned table's static position is.
target.display_before_box_type_transformation = box_values.display_before_box_type_transformation;
- target.position = box_values.position;
- target.float_ = box_values.float_;
- target.clear = box_values.clear;
target.has_z_index = box_values.has_z_index;
target.z_index = box_values.z_index;
target.vertical_align = box_values.vertical_align.clone();
target.baseline_source = box_values.baseline_source;
});
- let misc_reset = source.group::<MiscResetValues>();
- self.edit::<MiscResetValues>(|target| {
- target.column_span = misc_reset.column_span;
- target.break_before = misc_reset.break_before;
- target.break_after = misc_reset.break_after;
- target.break_inside = misc_reset.break_inside;
+ self.set_reset_bits(self.with_position_float_clear_of(source.payloads.reset_bits()));
+ let misc_layout = source.group::<MiscLayoutValues>();
+ self.edit::<MiscLayoutValues>(|target| {
+ target.column_span = misc_layout.column_span;
+ target.break_before = misc_layout.break_before;
+ target.break_after = misc_layout.break_after;
+ target.break_inside = misc_layout.break_inside;
});
self.copy_table_properties(source);
}
@@ -336,12 +426,12 @@ impl LayoutStyle {
target.column_count_has_value = box_values.column_count_has_value;
target.column_width = box_values.column_width.clone();
});
- let misc_reset = source.group::<MiscResetValues>();
- self.edit::<MiscResetValues>(|target| {
- target.column_fill = misc_reset.column_fill;
- target.column_rule_style = misc_reset.column_rule_style;
- target.column_rule_width = misc_reset.column_rule_width;
- target.column_rule_color = misc_reset.column_rule_color;
+ let misc_layout = source.group::<MiscLayoutValues>();
+ self.edit::<MiscLayoutValues>(|target| {
+ target.column_fill = misc_layout.column_fill;
+ target.column_rule_style = misc_layout.column_rule_style;
+ target.column_rule_width = misc_layout.column_rule_width;
+ target.column_rule_color = misc_layout.column_rule_color;
});
let alignment = source.group::<AlignmentValues>();
self.edit::<AlignmentValues>(|target| target.column_gap = alignment.column_gap.clone());
@@ -379,21 +469,15 @@ impl LayoutStyle {
});
}
- pub(crate) fn reset_table_properties(&mut self) {
+ pub(crate) fn reset_table_properties(&mut self, defaults: &crate::css::computed_values::DefaultGroups) {
let defaults = Self {
- payloads: std::array::from_fn(|index| {
- let payload = SharedPayload::new(default_group_payload(index));
- retain_group_payload(index, payload.as_ptr());
- payload
- }),
- longhand_table: HostShared::null(),
+ payloads: defaults.groups().clone(),
+ longhand_source: None,
changed: false,
};
+ self.set_reset_bits(self.with_position_float_clear_of(crate::css::computed_value_types::ResetBits::INITIAL));
let initial = defaults.group::<BoxValues>();
self.edit::<BoxValues>(|target| {
- target.position = initial.position;
- target.float_ = initial.float_;
- target.clear = initial.clear;
target.has_z_index = initial.has_z_index;
target.z_index = initial.z_index;
target.vertical_align = initial.vertical_align.clone();
@@ -498,29 +582,72 @@ impl LayoutStyle {
}
pub(crate) fn intern(self, engine: &mut StyleEngine) -> DerivedStyleRecord {
- // SAFETY: The builder retains its table until publication has retained it in the record.
- let table = unsafe { self.longhand_table.as_ref() };
- let record = super::bridge::publish_computed_groups_from_inputs(
- engine,
- 0,
- u8::MAX,
- &self.payloads,
- super::computed::ENGINE_INHERITED_GROUP_COUNT,
- 0,
- false,
- 0,
- 0,
- std::ptr::null(),
- &[],
- table,
- std::ptr::null(),
- )
- .new_style_record;
- DerivedStyleRecord::pin(engine, record)
+ // A layout style holds the longhands of the record it was made from, or the initial ones
+ // where it only inherits its parent's groups.
+ let record = match self.longhand_source {
+ Some(source) => engine
+ .install_record_derived_from(
+ super::computed::FinalStyleRecordID::from_raw(source).expect("a layout style's source is a record"),
+ &self.payloads,
+ )
+ .expect("a layout style's source record is one the engine installed"),
+ None => engine.install_initial_derived_record(&self.payloads, 0),
+ };
+ DerivedStyleRecord::pin(engine, record.raw())
}
}
impl StyleEngine {
+ /// Has the installation of a style update's rows in the boxes of their elements remember the record each
+ /// anonymous box it styles again derives, until [`Self::end_reinheriting_for_install`]: the anonymous boxes under
+ /// elements styled alike derive the same record, which is then found rather than built and interned again.
+ pub(crate) fn begin_reinheriting_for_install(&mut self) {
+ debug_assert!(self.host.reinherited_records.is_none());
+ self.host.reinherited_records = Some(Default::default());
+ }
+
+ /// Ends what [`Self::begin_reinheriting_for_install`] began, letting go of the records it remembered.
+ pub(crate) fn end_reinheriting_for_install(&mut self) {
+ for (_, record) in self.host.reinherited_records.take().unwrap_or_default() {
+ self.unpin_layout_style_record(record);
+ }
+ }
+
+ /// The record an anonymous box holding `record` derives from `parent`, its parent's, taking the column properties
+ /// of `column_source` where it has one, pinned for the box.
+ pub(crate) fn reinherited_anonymous_style_record(
+ &mut self,
+ record: u64,
+ parent: u64,
+ column_source: Option<u64>,
+ ) -> DerivedStyleRecord {
+ let key = Reinheritance {
+ record,
+ parent,
+ column_source,
+ };
+ if let Some(&derived) = self
+ .host
+ .reinherited_records
+ .as_ref()
+ .and_then(|records| records.get(&key))
+ {
+ return DerivedStyleRecord::pin(self, derived);
+ }
+ let mut style = LayoutStyle::from_record(self, record);
+ style.inherit_from(self, parent);
+ if let Some(column_source) = column_source {
+ style.copy_column_properties(&LayoutStyle::from_record(self, column_source));
+ }
+ let derived = style.intern(self);
+ // NB: What is remembered stays pinned until the installation ends, as a box that took it may let go of it.
+ if let Some(records) = self.host.reinherited_records.as_mut() {
+ records.insert(key, derived.record);
+ self.pin_layout_style_record(derived.record);
+ }
+ derived
+ }
+
pub(crate) fn pin_layout_style_record(&mut self, record: u64) {
self.pin_style_record(record);
}
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/cascade.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/cascade.rs
new file mode 100644
index 00000000000..30b1b803734
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/cascade.rs
@@ -0,0 +1,737 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The cascade of one element: its matched rules and its own declaration blocks, ordered by cascade
+//! priority, with the first declaration of each longhand in that order winning.
+
+use super::super::animations::DeclarationScope;
+use super::super::*;
+use super::matching::ElementMatch;
+use super::rules::RuleIndex;
+use crate::css::computed_longhand_table::LONGHAND_COUNT;
+use crate::css::property_metadata::property_id::ANIMATION_NAME;
+use crate::css::property_metadata::{FIRST_LONGHAND_PROPERTY_ID, LAST_LONGHAND_PROPERTY_ID};
+use crate::css::selector::Specificity;
+use smallvec::SmallVec;
+
+const LONGHAND_WORDS: usize = LONGHAND_COUNT.div_ceil(64);
+
+/// The own declarations of an element no rule reaches and no style node holds the declarations
+/// of, such as one outside the document, with the facts its style adjusts by. Its cascade and
+/// computation take them in place of those of the node they are keyed by.
+pub(in crate::css::style) struct DeclaredOnly {
+ pub(in crate::css::style) declarations: super::super::element_declarations::ElementDeclarationRow,
+ pub(in crate::css::style) facts: u32,
+}
+
+/// The declaration that won one longhand.
+#[derive(Clone, Copy, Eq, Hash, PartialEq)]
+pub(in crate::css::style) struct Winner {
+ pub(super) property: u16,
+ pub(super) important: bool,
+ /// The block holding the declaration.
+ pub(super) source: WinnerSource,
+ /// The declaration's index in the block.
+ pub(super) index: usize,
+}
+
+/// What the cascade of the element could not decide yet.
+#[derive(Default)]
+pub(super) struct CascadeCounters {
+ pub(super) winners: u64,
+ pub(super) pending_substitutions: u64,
+}
+
+impl CascadeCounters {
+ pub(super) fn add(&mut self, other: &Self) {
+ self.winners += other.winners;
+ self.pending_substitutions += other.pending_substitutions;
+ }
+}
+
+/// How many blocks an element's cascade sorts into cascade order and walks, taking the first
+/// declaration of each longhand. Beyond that many, it offers them in any order instead, keeping
+/// the best declaration of each longhand, which saves sorting them all.
+const ORDERED_BLOCKS: usize = 16;
+
+/// The declarations of one block, with its custom property declarations and their written values.
+type BlockDeclarations<'a> = (
+ &'a [DeclarationEntry],
+ Option<(&'a [CustomDeclaration], &'a [RetainedStyleValueData])>,
+);
+
+/// The best declaration of one longhand so far, in a cascade offered blocks in any order.
+#[derive(Clone, Copy)]
+struct Candidate {
+ priority: CascadePriority,
+ important: bool,
+ source: WinnerSource,
+ index: usize,
+ /// The rule index entry the declaration's block is of, or `u32::MAX` for an element's own.
+ entry: u32,
+ /// The tree scope the block's rule decides from, as its match says.
+ scope: TreeScopeID,
+}
+
+/// A declaration of `revert` or `revert-layer`, by the priority of its block.
+type Reverting = (CascadePriority, CascadeOperator);
+
+/// Whether one of the declarations `reverted` rolls back past a declaration at `priority`.
+fn rolled_back(reverted: &[Reverting], priority: &CascadePriority) -> bool {
+ reverted
+ .iter()
+ .any(|(reverting, operator)| reverting.reverts_past(*operator, priority))
+}
+
+/// Whether a declaration of `operator` rolls the cascade back.
+fn is_revert(operator: CascadeOperator) -> bool {
+ matches!(operator, CascadeOperator::Revert | CascadeOperator::RevertLayer)
+}
+
+/// The best declaration of one custom property so far, in a cascade offered blocks in any order.
+struct CustomCandidate {
+ priority: CascadePriority,
+ declaration: CustomDeclaration,
+ written: RetainedStyleValueData,
+}
+
+/// Reusable scratch for cascading one element after another.
+pub(super) struct Cascade {
+ /// Each block with the rule index entry it is of, or `u32::MAX` for an element's own, and the
+ /// tree scope its rule decides from.
+ blocks: Vec<(CascadePriority, WinnerSource, bool, u32, TreeScopeID)>,
+ decided: [u64; LONGHAND_WORDS],
+ /// The best declaration of each longhand offered, by longhand, where `decided` says one was:
+ /// the others are never written, so a cascade touches only the room of the longhands offered.
+ best: Box<[std::mem::MaybeUninit<Candidate>]>,
+ /// The longhands with a declaration offered, in the order they were first.
+ offered: Vec<u16>,
+ custom_candidates: Vec<CustomCandidate>,
+ /// The declaration that won each decided longhand, highest priority first.
+ pub(super) winners: Vec<Winner>,
+ /// The custom property declaration that won each name, highest priority first, with the
+ /// value it was written with.
+ pub(super) custom_winners: Vec<(CustomDeclaration, RetainedStyleValueData)>,
+ decided_names: Vec<StyleAtomID>,
+ /// Each declaration of `revert` or `revert-layer` the ordered cascade met for a custom
+ /// property it had not decided, with the name.
+ reverting_names: Vec<(StyleAtomID, Reverting)>,
+ /// The pseudo-element kind an element backing one of its shadow host's pseudo-elements stands
+ /// for, which takes from the host's rules only the properties that pseudo-element supports, or
+ /// `u8::MAX`.
+ backed_kind: u8,
+ /// The pseudo-element kind the last cascade was for, which takes from the rules only the
+ /// properties that pseudo-element supports, or `u8::MAX` for the element itself.
+ pseudo_kind: u8,
+ /// The scope the winning `animation-name` was declared in, where the `@keyframes` it names
+ /// are looked for first.
+ pub(super) animation_name_scope: DeclarationScope,
+ pub(super) statistics: CascadeCounters,
+ /// The declarations a cascade of an element's own declarations alone takes in place of its
+ /// node's.
+ declared_only: Option<Box<DeclaredOnly>>,
+}
+
+impl Cascade {
+ /// The best declaration of the longhand in `slot` offered so far, which `decided` says there is.
+ fn best(&self, slot: usize) -> &Candidate {
+ assert!(
+ self.decided[slot / 64] & (1 << (slot % 64)) != 0,
+ "a longhand's best declaration is read once one was offered"
+ );
+ // SAFETY: A longhand is decided once its best declaration is written, and a cascade clears
+ // every decided longhand before it starts.
+ unsafe { self.best[slot].assume_init_ref() }
+ }
+
+ pub(super) fn new() -> Self {
+ Self {
+ blocks: Vec::new(),
+ decided: [0; LONGHAND_WORDS],
+ best: Box::new_uninit_slice(LONGHAND_COUNT),
+ offered: Vec::new(),
+ custom_candidates: Vec::new(),
+ winners: Vec::new(),
+ custom_winners: Vec::new(),
+ decided_names: Vec::new(),
+ reverting_names: Vec::new(),
+ backed_kind: u8::MAX,
+ pseudo_kind: u8::MAX,
+ animation_name_scope: DeclarationScope::Unscoped,
+ statistics: CascadeCounters::default(),
+ declared_only: None,
+ }
+ }
+
+ /// The cascade of `declared` alone, the own declarations of an element no rule reaches, keyed
+ /// by `node`, which holds no declarations of its own.
+ pub(super) fn of_declared_only(
+ state: &RetainedState,
+ index: &RuleIndex,
+ node: StyleNodeID,
+ declared: DeclaredOnly,
+ ) -> Self {
+ let mut cascade = Self::new();
+ cascade.declared_only = Some(Box::new(declared));
+ cascade.cascade(state, index, node, &[], u8::MAX);
+ cascade
+ }
+
+ /// The declarations the cascade takes in place of its node's, where it is of an element's own
+ /// declarations alone.
+ pub(super) fn declared_only(&self) -> Option<&DeclaredOnly> {
+ self.declared_only.as_deref()
+ }
+
+ /// Cascade the element's non-pseudo-element matches and element declarations into `winners`.
+ pub(super) fn cascade_element(
+ &mut self,
+ state: &RetainedState,
+ index: &RuleIndex,
+ node: StyleNodeID,
+ matches: &[ElementMatch],
+ ) {
+ self.backed_kind = u8::MAX;
+ self.cascade(state, index, node, matches, u8::MAX);
+ }
+
+ /// Cascade an element standing for its shadow host's pseudo-element of `kind`, such as the
+ /// element a `::placeholder` is: the host's matches for that pseudo-element, of which it takes
+ /// only the properties the pseudo-element supports, with the element's own declarations.
+ pub(super) fn cascade_backing_element(
+ &mut self,
+ state: &RetainedState,
+ index: &RuleIndex,
+ node: StyleNodeID,
+ host_matches: &[ElementMatch],
+ kind: u8,
+ ) {
+ self.backed_kind = kind;
+ self.cascade(state, index, node, host_matches, kind);
+ }
+
+ /// Whether a declaration of `property` by `source` takes part in the cascade: a rule's for a
+ /// pseudo-element where the pseudo-element supports the property.
+ fn takes(&self, source: WinnerSource, property: u16) -> bool {
+ self.pseudo_kind == u8::MAX
+ || !matches!(source, WinnerSource::Rule(_))
+ || crate::css::property_metadata::pseudo_element_supports_property(self.pseudo_kind, property)
+ }
+
+ /// Cascade the element's matches for its pseudo-element of `kind` into `winners`, as
+ /// [`Self::cascade_element`] does for the element: the element's own declarations style the
+ /// element alone.
+ pub(super) fn cascade_pseudo_element(
+ &mut self,
+ state: &RetainedState,
+ index: &RuleIndex,
+ node: StyleNodeID,
+ matches: &[ElementMatch],
+ kind: u8,
+ ) {
+ self.backed_kind = u8::MAX;
+ self.cascade(state, index, node, matches, kind);
+ }
+
+ fn cascade(
+ &mut self,
+ state: &RetainedState,
+ index: &RuleIndex,
+ node: StyleNodeID,
+ matches: &[ElementMatch],
+ pseudo_kind: u8,
+ ) {
+ self.pseudo_kind = pseudo_kind;
+ self.decided = [0; LONGHAND_WORDS];
+ self.winners.clear();
+ self.custom_winners.clear();
+ self.decided_names.clear();
+ self.reverting_names.clear();
+ self.blocks.clear();
+ self.animation_name_scope = DeclarationScope::Unscoped;
+
+ // Matches are in index order, so a rule's entries for one target are adjacent among the
+ // target's; its greatest specificity decides for the rule.
+ let mut targeted = matches
+ .iter()
+ .filter(|matched| matched.pseudo_kind == pseudo_kind)
+ .peekable();
+ while let Some(first) = targeted.next() {
+ let mut specificity: Specificity = first.specificity;
+ let mut scope_proximity = first.scope_proximity;
+ // A rule matched from several of the element's encapsulation contexts decides from each.
+ while let Some(next) = targeted.next_if(|next| next.rule == first.rule && next.scope == first.scope) {
+ specificity = specificity.max(next.specificity);
+ scope_proximity = scope_proximity.min(next.scope_proximity);
+ }
+ // NB: The entry is read in place, from the segment holding it where it is a bound one.
+ let entry = index.entries.view(first.entry as usize);
+ let placement = index.entries.placement_of(entry);
+ for important in [false, true] {
+ if important && !entry.declares_important() {
+ continue;
+ }
+ let priority = CascadePriority::new(PriorityInputs {
+ origin: placement.origin,
+ important,
+ context_depth: first.context_depth,
+ element_attachment: ElementAttachment::Rule,
+ layer_rank: placement.layer_rank,
+ specificity,
+ scope_proximity,
+ sheet_rank: placement.sheet_rank,
+ rule_rank: entry.rule_rank(),
+ });
+ self.blocks.push((
+ priority,
+ WinnerSource::Rule(first.rule),
+ important,
+ first.entry,
+ first.scope,
+ ));
+ }
+ }
+ let own = self.declared_only.as_deref();
+ let element_declares_custom_properties = custom_declarations_of(
+ state,
+ index,
+ own,
+ node,
+ WinnerSource::Element(ElementDeclarationKind::InlineStyle),
+ u32::MAX,
+ )
+ .is_some_and(|(declared, _)| !declared.is_empty());
+ // An element's own declarations style the element alone, which is what an element backing
+ // its host's pseudo-element is.
+ for kind in ElementDeclarationKind::ALL
+ .into_iter()
+ .filter(|_| pseudo_kind == u8::MAX || self.backed_kind != u8::MAX)
+ {
+ let declares_custom_properties =
+ kind == ElementDeclarationKind::InlineStyle && element_declares_custom_properties;
+ if block_declarations(state, own, node, WinnerSource::Element(kind)).is_empty()
+ && !declares_custom_properties
+ {
+ continue;
+ }
+ for important in [false, true] {
+ let priority = state.element_cascade_priority(node, kind, important);
+ self.blocks.push((
+ priority,
+ WinnerSource::Element(kind),
+ important,
+ u32::MAX,
+ TreeScopeID::DOCUMENT,
+ ));
+ }
+ }
+ if self.blocks.len() > ORDERED_BLOCKS {
+ self.cascade_unordered(state, index, node);
+ return;
+ }
+ self.blocks.sort_unstable_by_key(|block| std::cmp::Reverse(block.0));
+ let entries = &index.entries;
+
+ for &(priority, source, important, entry, scope) in &self.blocks {
+ // https://drafts.csswg.org/css-variables-2/#defining-variables
+ // A custom property cascades by its name, the way a longhand does.
+ if let Some((declared, written)) =
+ custom_declarations_of(state, index, self.declared_only.as_deref(), node, source, entry)
+ {
+ for (declaration, written) in declared.iter().zip(written) {
+ if declaration.important() != important
+ || self.decided_names.contains(&declaration.name)
+ || self.reverting_names.iter().any(|(name, (reverting, operator))| {
+ *name == declaration.name && reverting.reverts_past(*operator, &priority)
+ })
+ {
+ continue;
+ }
+ match declaration.operator() {
+ // https://drafts.csswg.org/css-cascade-5/#default
+ // `revert` and `revert-layer` roll the cascaded value back to what lower
+ // declarations they do not roll back past cascade to.
+ operator @ (CascadeOperator::Revert | CascadeOperator::RevertLayer) => {
+ self.reverting_names.push((declaration.name, (priority, operator)));
+ }
+ CascadeOperator::Declared => {
+ self.decided_names.push(declaration.name);
+ self.custom_winners.push((*declaration, written.clone()));
+ }
+ // A registered name's CSS-wide keywords take its registration's initial value, or
+ // the parent's value of one that does not inherit, which the store resolves
+ // from the keyword written.
+ CascadeOperator::Inherit | CascadeOperator::Unset | CascadeOperator::Initial
+ if state.custom_property_name_is_registered(declaration.name) =>
+ {
+ self.decided_names.push(declaration.name);
+ self.custom_winners.push((*declaration, written.clone()));
+ }
+ // https://drafts.csswg.org/css-variables-2/#defining-variables
+ // Custom properties are inherited, so these keep the inherited value.
+ CascadeOperator::Inherit | CascadeOperator::Unset => self.decided_names.push(declaration.name),
+ // The initial value of a custom property is the guaranteed-invalid value.
+ CascadeOperator::Initial => {
+ self.decided_names.push(declaration.name);
+ self.custom_winners.push((
+ *declaration,
+ RetainedStyleValueData::from_owned(
+ crate::css::style_value::StyleValueData::GuaranteedInvalid,
+ ),
+ ));
+ }
+ }
+ }
+ }
+ let declarations = block_declarations(state, self.declared_only.as_deref(), node, source);
+ // https://drafts.csswg.org/css-cascade-5/#cascade-order
+ // Within a block, the last declaration in document order wins. The winners keep that
+ // order, which is how the computation pairs a logical longhand with its physical
+ // counterpart: of the two, the one declared with higher priority decides both.
+ for (index, declaration) in declarations.iter().enumerate().rev() {
+ if declaration.important() != important {
+ continue;
+ }
+ // A shorthand declared whole waits on substitution, and its longhands are declared
+ // beside it, each pending the shorthand's value.
+ if !(FIRST_LONGHAND_PROPERTY_ID..=LAST_LONGHAND_PROPERTY_ID).contains(&declaration.property()) {
+ continue;
+ }
+ if !self.takes(source, declaration.property()) {
+ continue;
+ }
+ let slot = usize::from(declaration.property() - FIRST_LONGHAND_PROPERTY_ID);
+ let (word, bit) = (slot / 64, 1_u64 << (slot % 64));
+ if self.decided[word] & bit != 0 {
+ continue;
+ }
+ self.decided[word] |= bit;
+ if declaration.property() == ANIMATION_NAME {
+ self.animation_name_scope = declaration_scope(entries, entry, scope);
+ }
+ self.winners.push(Winner {
+ property: declaration.property(),
+ important: declaration.important(),
+ source,
+ index,
+ });
+ }
+ }
+ self.statistics.winners += self.winners.len() as u64;
+ }
+
+ /// Cascade the blocks gathered in any order, keeping the best declaration of each longhand and
+ /// custom property name.
+ fn cascade_unordered(&mut self, state: &RetainedState, index: &RuleIndex, node: StyleNodeID) {
+ self.offered.clear();
+ self.custom_candidates.clear();
+ for block in 0..self.blocks.len() {
+ let (priority, source, important, entry, scope) = self.blocks[block];
+ let (declarations, custom): BlockDeclarations<'_> = (
+ block_declarations(state, self.declared_only.as_deref(), node, source),
+ custom_declarations_of(state, index, self.declared_only.as_deref(), node, source, entry),
+ );
+ for (index, declaration) in declarations.iter().enumerate() {
+ if declaration.important() != important {
+ continue;
+ }
+ if !(FIRST_LONGHAND_PROPERTY_ID..=LAST_LONGHAND_PROPERTY_ID).contains(&declaration.property())
+ || !self.takes(source, declaration.property())
+ {
+ continue;
+ }
+ let slot = usize::from(declaration.property() - FIRST_LONGHAND_PROPERTY_ID);
+ let (word, bit) = (slot / 64, 1_u64 << (slot % 64));
+ let candidate = Candidate {
+ priority,
+ important,
+ source,
+ index,
+ entry,
+ scope,
+ };
+ if self.decided[word] & bit == 0 {
+ self.decided[word] |= bit;
+ self.best[slot].write(candidate);
+ self.offered.push(slot as u16);
+ continue;
+ }
+ let best = self.best(slot);
+ if priority > best.priority
+ || (priority == best.priority && source == best.source && index > best.index)
+ {
+ self.best[slot].write(candidate);
+ }
+ }
+ let Some((declared, written)) = custom else {
+ continue;
+ };
+ for (declaration, written) in declared.iter().zip(written) {
+ if declaration.important() != important {
+ continue;
+ }
+ match self
+ .custom_candidates
+ .iter_mut()
+ .find(|candidate| candidate.declaration.name == declaration.name)
+ {
+ Some(candidate) if priority > candidate.priority => {
+ candidate.priority = priority;
+ candidate.declaration = *declaration;
+ candidate.written = written.clone();
+ }
+ Some(_) => {}
+ None => self.custom_candidates.push(CustomCandidate {
+ priority,
+ declaration: *declaration,
+ written: written.clone(),
+ }),
+ }
+ }
+ }
+
+ // https://drafts.csswg.org/css-variables-2/#defining-variables
+ // A custom property cascades by its name, the way a longhand does.
+ self.custom_candidates
+ .sort_unstable_by_key(|candidate| std::cmp::Reverse(candidate.priority));
+ for mut candidate in std::mem::take(&mut self.custom_candidates) {
+ if is_revert(candidate.declaration.operator()) {
+ let mut reverted: SmallVec<[Reverting; 2]> =
+ smallvec::smallvec![(candidate.priority, candidate.declaration.operator())];
+ match self.custom_property_below(state, index, node, candidate.declaration.name, &mut reverted) {
+ Some(below) => candidate = below,
+ // Nothing below declares the name, which then inherits.
+ None => continue,
+ }
+ }
+ let declaration = candidate.declaration;
+ match declaration.operator() {
+ CascadeOperator::Declared => self.custom_winners.push((declaration, candidate.written)),
+ // A registered name's CSS-wide keywords take its registration's initial value, or
+ // the parent's value of one that does not inherit, which the store resolves from
+ // the keyword written.
+ CascadeOperator::Inherit | CascadeOperator::Unset | CascadeOperator::Initial
+ if state.custom_property_name_is_registered(declaration.name) =>
+ {
+ self.custom_winners.push((declaration, candidate.written));
+ }
+ // https://drafts.csswg.org/css-variables-2/#defining-variables
+ // Custom properties are inherited, so these keep the inherited value.
+ CascadeOperator::Inherit | CascadeOperator::Unset => {}
+ // The initial value of a custom property is the guaranteed-invalid value.
+ CascadeOperator::Initial => self.custom_winners.push((
+ declaration,
+ RetainedStyleValueData::from_owned(crate::css::style_value::StyleValueData::GuaranteedInvalid),
+ )),
+ CascadeOperator::Revert | CascadeOperator::RevertLayer => {
+ unreachable!("a reverting custom declaration rolls back above")
+ }
+ }
+ }
+
+ let animation_name_slot = usize::from(ANIMATION_NAME - FIRST_LONGHAND_PROPERTY_ID);
+ if self.offered.contains(&(animation_name_slot as u16)) {
+ let best = self.best(animation_name_slot);
+ self.animation_name_scope = declaration_scope(&index.entries, best.entry, best.scope);
+ }
+ let mut winners: SmallVec<[Candidate; 16]> =
+ self.offered.iter().map(|&slot| *self.best(usize::from(slot))).collect();
+ // Highest priority first, and a block's later declarations before its earlier ones, as the
+ // ordered cascade has them.
+ winners.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(b.index.cmp(&a.index)));
+ self.winners.extend(winners.iter().map(|candidate| {
+ let property = match candidate.source {
+ WinnerSource::Rule(rule) => state.rules.declared_properties_of(rule)[candidate.index].property(),
+ WinnerSource::Element(_) => {
+ block_declarations(state, self.declared_only.as_deref(), node, candidate.source)[candidate.index]
+ .property()
+ }
+ };
+ Winner {
+ property,
+ important: candidate.important,
+ source: candidate.source,
+ index: candidate.index,
+ }
+ }));
+ self.statistics.winners += self.winners.len() as u64;
+ }
+
+ /// The declaration of the longhand `property` the cascade rolls back to below the
+ /// declarations of `revert` and `revert-layer` in `reverted`: the highest one they do not roll
+ /// back past, where one that reverts in turn joins them. None where nothing below declares
+ /// the longhand.
+ fn longhand_below(
+ &self,
+ state: &RetainedState,
+ node: StyleNodeID,
+ property: u16,
+ reverted: &mut SmallVec<[Reverting; 2]>,
+ ) -> Option<(CascadePriority, Winner)> {
+ loop {
+ let mut best: Option<(CascadePriority, Winner, CascadeOperator)> = None;
+ for &(priority, source, important, _, _) in &self.blocks {
+ if best.is_some_and(|(best, ..)| best >= priority)
+ || rolled_back(reverted, &priority)
+ || !self.takes(source, property)
+ {
+ continue;
+ }
+ let declarations = block_declarations(state, self.declared_only.as_deref(), node, source);
+ // As in the cascade, the last declaration of the longhand in a block wins in it.
+ if let Some(at) = declarations
+ .iter()
+ .rposition(|declaration| declaration.property() == property && declaration.important() == important)
+ {
+ best = Some((
+ priority,
+ Winner {
+ property,
+ important,
+ source,
+ index: at,
+ },
+ declarations[at].operator(),
+ ));
+ }
+ }
+ let (priority, winner, operator) = best?;
+ if !is_revert(operator) {
+ return Some((priority, winner));
+ }
+ reverted.push((priority, operator));
+ }
+ }
+
+ /// What [`Self::longhand_below`] says for the custom property `name`.
+ fn custom_property_below(
+ &self,
+ state: &RetainedState,
+ index: &RuleIndex,
+ node: StyleNodeID,
+ name: StyleAtomID,
+ reverted: &mut SmallVec<[Reverting; 2]>,
+ ) -> Option<CustomCandidate> {
+ loop {
+ let mut best: Option<CustomCandidate> = None;
+ for &(priority, source, important, entry, _) in &self.blocks {
+ if best.as_ref().is_some_and(|best| best.priority >= priority) || rolled_back(reverted, &priority) {
+ continue;
+ }
+ let Some((declared, written)) =
+ custom_declarations_of(state, index, self.declared_only.as_deref(), node, source, entry)
+ else {
+ continue;
+ };
+ if let Some(at) = declared
+ .iter()
+ .rposition(|declaration| declaration.name == name && declaration.important() == important)
+ {
+ best = Some(CustomCandidate {
+ priority,
+ declaration: declared[at],
+ written: written[at].clone(),
+ });
+ }
+ }
+ let best = best?;
+ if !is_revert(best.declaration.operator()) {
+ return Some(best);
+ }
+ reverted.push((best.priority, best.declaration.operator()));
+ }
+ }
+}
+
+/// The declarations of one of an element's cascade blocks.
+fn block_declarations<'a>(
+ state: &'a RetainedState,
+ own: Option<&'a DeclaredOnly>,
+ node: StyleNodeID,
+ source: WinnerSource,
+) -> &'a [DeclarationEntry] {
+ match (source, own) {
+ (WinnerSource::Rule(rule), _) => state.rules.declared_properties_of(rule),
+ (WinnerSource::Element(kind), Some(own)) => own.declarations.declarations(kind).declared(),
+ (WinnerSource::Element(kind), None) => state.element_declarations.declared_properties(node, kind),
+ }
+}
+
+/// The custom property declarations of one of an element's cascade blocks, with the values they
+/// were written with.
+fn custom_declarations_of<'a>(
+ state: &'a RetainedState,
+ index: &'a RuleIndex,
+ own: Option<&'a DeclaredOnly>,
+ node: StyleNodeID,
+ source: WinnerSource,
+ entry: u32,
+) -> Option<(&'a [CustomDeclaration], &'a [RetainedStyleValueData])> {
+ match source {
+ WinnerSource::Rule(_) if !index.entries.view(entry as usize).declares_custom_properties() => None,
+ WinnerSource::Rule(rule) => Some((
+ state.rules.custom_declarations_of(rule),
+ state.rules.custom_written_values_of(rule),
+ )),
+ WinnerSource::Element(ElementDeclarationKind::InlineStyle) => match own {
+ Some(own) => own.declarations.custom(),
+ None => state.element_declarations.custom(node),
+ }
+ .map(|declarations| (declarations.declared(), declarations.written_values())),
+ _ => None,
+ }
+}
+
+/// The scope a declaration of the block of the rule index entry `entry`, deciding from the tree
+/// scope `scope`, was declared in, or of an element's own block where `entry` is `u32::MAX`: an
+/// author rule's is the tree scope of the sheet attachment it decides from, and no other
+/// declaration has a scope of its own.
+pub(super) fn declaration_scope(
+ entries: &super::rules::IndexEntries,
+ entry: u32,
+ scope: TreeScopeID,
+) -> DeclarationScope {
+ let Some(view) = entries.try_view(entry as usize) else {
+ return DeclarationScope::Unscoped;
+ };
+ match (entries.placement_of(view).origin, scope) {
+ (CascadeOrigin::Author, scope) if scope != TreeScopeID::DOCUMENT => DeclarationScope::Shadow(scope),
+ _ => DeclarationScope::Unscoped,
+ }
+}
+
+/// The last cascade of one element, which a winner of `revert` or `revert-layer`, declared or
+/// substituted, rolls back through.
+pub(super) struct CascadeBelow<'a> {
+ pub(super) cascade: &'a Cascade,
+ pub(super) state: &'a RetainedState,
+ pub(super) node: StyleNodeID,
+}
+
+impl super::compute::CascadeBelow for CascadeBelow<'_> {
+ fn priority_of(&self, source: WinnerSource, important: bool) -> CascadePriority {
+ self.cascade
+ .blocks
+ .iter()
+ .find(|block| block.1 == source && block.2 == important)
+ .expect("a winner's block is in its cascade")
+ .0
+ }
+
+ fn winner_below(
+ &self,
+ property: u16,
+ reverted: &[(CascadePriority, CascadeOperator)],
+ ) -> Option<(CascadePriority, Winner)> {
+ let mut reverted: SmallVec<[Reverting; 2]> = reverted.into();
+ self.cascade
+ .longhand_below(self.state, self.node, property, &mut reverted)
+ }
+
+ fn declared_only(&self) -> Option<&DeclaredOnly> {
+ self.cascade.declared_only()
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/cold_pass.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/cold_pass.rs
new file mode 100644
index 00000000000..9836831487f
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/cold_pass.rs
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! A pass styling the whole document from scratch, for a test to read what it measures and whether
+//! what the engine holds differs from what it computes. Nothing it computes is installed.
+
+use super::super::{RetainedState, StyleEngine, StyleNodeID};
+use super::self_check;
+
+/// What the last cold pass measured, by `ReportField`.
+pub(in super::super) type Report = [u64; ReportField::COUNT];
+
+#[derive(Clone, Copy)]
+#[repr(u32)]
+pub(in super::super) enum ReportField {
+ Elements,
+ IndexedEntries,
+ IndexNanoseconds,
+ StyleNanoseconds,
+ Threads,
+ Candidates,
+ BloomRejections,
+ Evaluations,
+ Matches,
+ Winners,
+ ComputedElements,
+ DirectlyComputedElements,
+ SharedElements,
+ ReusedElements,
+ PseudoElements,
+ Differences,
+}
+
+impl ReportField {
+ pub(in super::super) const COUNT: usize = Self::Differences as usize + 1;
+}
+
+impl StyleEngine {
+ /// Style the document tree under `root` from scratch on `threads` threads, or as many as the
+ /// machine has for none, count what differs from what the engine holds when asked to, and
+ /// report the time the styling took in nanoseconds.
+ pub(in super::super) fn run_cold_pass(&mut self, root: StyleNodeID, verify: bool, threads: u32) -> u64 {
+ let Some(pass) = self_check::reference_pass(self, root, true, threads) else {
+ return 0;
+ };
+ let statistics = &pass.statistics;
+ let outcomes = &statistics.outcomes;
+ let mut report = [0_u64; ReportField::COUNT];
+ let mut set = |field: ReportField, value: u64| report[field as usize] = value;
+ set(ReportField::Elements, outcomes.elements());
+ set(ReportField::IndexedEntries, pass.indexed_entries);
+ set(ReportField::IndexNanoseconds, pass.index_nanoseconds);
+ set(ReportField::StyleNanoseconds, pass.style_nanoseconds);
+ set(ReportField::Threads, pass.threads);
+ set(ReportField::Candidates, statistics.match_counters.candidates);
+ set(ReportField::BloomRejections, statistics.match_counters.bloom_rejections);
+ set(ReportField::Evaluations, statistics.match_counters.evaluations);
+ set(ReportField::Matches, statistics.match_counters.matches);
+ set(ReportField::Winners, statistics.cascade_counters.winners);
+ set(ReportField::ComputedElements, outcomes.styled());
+ set(ReportField::DirectlyComputedElements, outcomes.computed_directly());
+ set(ReportField::SharedElements, outcomes.shared());
+ set(ReportField::ReusedElements, outcomes.reused());
+ set(
+ ReportField::PseudoElements,
+ self.retained
+ .projection
+ .style_preorder(root)
+ .map(|node| pass.records.pseudo_element_records(node).len() as u64)
+ .sum(),
+ );
+ let nanoseconds = pass.index_nanoseconds + pass.style_nanoseconds;
+ if verify {
+ report[ReportField::Differences as usize] = self.self_check_failures(root, None).len() as u64;
+ }
+ self.retained.cold_pass_report = report;
+ nanoseconds
+ }
+}
+
+impl RetainedState {
+ /// The value of one field of the last cold pass's report, or zero past the last field.
+ pub(in super::super) fn cold_pass_report(&self, index: u32) -> u64 {
+ self.cold_pass_report.get(index as usize).copied().unwrap_or(0)
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/compute.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/compute.rs
new file mode 100644
index 00000000000..2a7ff75ece6
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/compute.rs
@@ -0,0 +1,2431 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The engine's computation of one element's style from the winners its cascade decided.
+
+use super::super::publication::pseudo_kind;
+use super::super::*;
+use super::cascade::Winner;
+use super::drive::{self, Drive, Suspension, Unanswered, drive_font_metric};
+use super::winner_store::{self, WinnerDeclaration, WinnerStore, WinnerValue, shorthand_longhand_data};
+use crate::css::computed_longhand_table::FONT_METRICS_DEPEND_ON_VIEWPORT_METRICS;
+use crate::css::computed_values::{GroupValueLayout, GroupValues, GroupValuesWriter, StyleGroupMasks};
+use crate::css::style::input_types::StyleEnvironment;
+use crate::css::style_compute::RootFontReads;
+use crate::css::style_value::ShorthandPayload;
+use crate::css::style_value::{RetainedStyleValueData, StyleValueData};
+
+/// Root-relative computation reads these inputs independently of its inheritance parent.
+/// Bitwise keys keep equality exact without using an invalidation generation as a substitute
+/// for the values. The viewport-dependence bit matters even when today's metrics agree.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub(in crate::css::style) struct RootFontInputs {
+ metrics: [u64; 5],
+ depends_on_viewport: bool,
+ /// https://drafts.csswg.org/css-viewport/#effective-zoom
+ /// The bits of the effective zoom of the document element, which the metrics are zoomed by.
+ effective_zoom: u64,
+}
+
+impl RootFontInputs {
+ /// What of these inputs moved from `previous`, as the least a style must read of the root
+ /// element's font to resolve its lengths again: a load of a face into the root element's font
+ /// moves its metrics alone, which a `rem` does not read.
+ pub(in crate::css::style) fn moved_from(self, previous: Self) -> RootFontReads {
+ if self.metrics[0] != previous.metrics[0]
+ || self.depends_on_viewport != previous.depends_on_viewport
+ || self.effective_zoom != previous.effective_zoom
+ {
+ return RootFontReads::FontSize;
+ }
+ match self == previous {
+ true => RootFontReads::None,
+ false => RootFontReads::Metrics,
+ }
+ }
+
+ /// The metrics a `rem` resolves against, and whether they read the viewport.
+ pub(in crate::css::style) fn font_metrics(self) -> (crate::css::style_compute::FfiFontMetrics, bool) {
+ let [font_size, x_height, cap_height, zero_advance, line_height] = self.metrics.map(f64::from_bits);
+ (
+ crate::css::style_compute::FfiFontMetrics {
+ font_size,
+ x_height,
+ cap_height,
+ zero_advance,
+ line_height,
+ },
+ self.depends_on_viewport,
+ )
+ }
+
+ /// https://drafts.csswg.org/css-viewport/#effective-zoom
+ pub(in crate::css::style) fn effective_zoom(self) -> f64 {
+ f64::from_bits(self.effective_zoom)
+ }
+
+ pub(in crate::css::style) fn apply_to(self, inputs: &mut bridge::FfiDocumentStyleComputationInputs) {
+ inputs.root_font_size = f64::from_bits(self.metrics[0]);
+ inputs.root_font_x_height = f64::from_bits(self.metrics[1]);
+ inputs.root_font_cap_height = f64::from_bits(self.metrics[2]);
+ inputs.root_font_zero_advance = f64::from_bits(self.metrics[3]);
+ inputs.root_line_height = f64::from_bits(self.metrics[4]);
+ inputs.root_font_metrics_depend_on_viewport_metrics = self.depends_on_viewport;
+ inputs.root_effective_zoom = f64::from_bits(self.effective_zoom);
+ }
+
+ /// The inputs a document element's computed groups and dependency flags give.
+ pub(in crate::css::style) fn from_payloads(
+ payloads: &crate::css::computed_values::StyleGroups,
+ dependency_flags: u8,
+ ) -> Self {
+ use crate::css::table_group_builder::group_index;
+ // SAFETY: The payloads are a record's live font group.
+ let font = unsafe {
+ payloads[group_index::FONT]
+ .cast::<crate::css::computed_value_types::FontValues>()
+ .deref()
+ };
+ let first_available = font.first_available_font_metrics();
+ Self {
+ metrics: [
+ font.font_size.to_double().to_bits(),
+ drive_font_metric(first_available.x_height).to_bits(),
+ drive_font_metric(first_available.ascent).to_bits(),
+ drive_font_metric(first_available.zero_advance).to_bits(),
+ font.line_height_used().to_double().to_bits(),
+ ],
+ depends_on_viewport: dependency_flags & FONT_METRICS_DEPEND_ON_VIEWPORT_METRICS != 0,
+ effective_zoom: f64::from(payloads.inherited_values().effective_zoom()).to_bits(),
+ }
+ }
+
+ pub(in crate::css::style) fn from_document(inputs: &bridge::FfiDocumentStyleComputationInputs) -> Self {
+ Self {
+ metrics: [
+ inputs.root_font_size.to_bits(),
+ inputs.root_font_x_height.to_bits(),
+ inputs.root_font_cap_height.to_bits(),
+ inputs.root_font_zero_advance.to_bits(),
+ inputs.root_line_height.to_bits(),
+ ],
+ depends_on_viewport: inputs.root_font_metrics_depend_on_viewport_metrics,
+ effective_zoom: inputs.root_effective_zoom.to_bits(),
+ }
+ }
+}
+
+impl RetainedState {
+ /// The engine: the computed initial values, as an element with no declarations and no parent
+ /// computes them, with the groups they assemble into, each holding one reference, and the
+ /// color they resolve. Every table is seeded from this one, and an element whose
+ /// declarations move none of a non-inherited group's longhands shares the initial group. A
+ /// drive that waits on a font names the request to refill before trying again.
+ pub(in crate::css::style) fn initial_style(
+ &self,
+ root: StyleNodeID,
+ ) -> Result<ComputedInitialStyle, Option<Box<font_resolution::FontRequest>>> {
+ let subject = DriveSubject {
+ target: computed::ComputedStyleTarget::new(root, u8::MAX),
+ parent: None,
+ facts: 0,
+ };
+ let store = WinnerStore::new(Vec::new());
+ let inputs = self.document_style_computation_inputs;
+ let mut font_scratch = drive::FontDriveScratch::default();
+ // The initial values compute from nothing: from the default groups, which hold no values.
+ crate::css::computed_values::with_default_seed(&self.process_style.default_groups, |seed| {
+ let writer = GroupValuesWriter::seeded_for_child(
+ seed,
+ seed,
+ std::iter::empty(),
+ crate::css::computed_longhand_table::LonghandTableFlags::empty(),
+ 0,
+ );
+ match self.engine_full_drive(subject, writer, &store, &inputs, &mut font_scratch) {
+ Ok(drive::DrivenValues {
+ writer,
+ length,
+ font: Some(font),
+ }) => {
+ let (values, flags, dependency_flags) = writer.finish(&[]);
+ let source = crate::css::table_group_builder::LonghandSource::Values {
+ values: &values,
+ reads: None,
+ };
+ let color_inputs =
+ crate::css::table_group_builder::assembly_color_inputs_from_source(&source, &length);
+ let mut payloads = [std::ptr::null(); crate::css::table_group_builder::group_index::COUNT];
+ for (group, payload) in payloads.iter_mut().enumerate() {
+ // SAFETY: The values were driven for an element with no parent.
+ *payload = unsafe {
+ crate::css::table_group_builder::assemble_group_from_source(
+ &source,
+ group,
+ Some(&font),
+ crate::css::computed_values::GroupShares::new(
+ &self.process_style.default_groups,
+ group,
+ None,
+ ),
+ color_inputs,
+ &length,
+ )
+ };
+ }
+ // The initial groups hold the initial values, each group in its own allocation.
+ // SAFETY: Each payload is a live payload of its group, whose reference the style takes.
+ unsafe { values.put_into(&mut payloads) };
+ let initial_font = super::traversal::InitialFont {
+ first_available_font: font.first_available_font as usize,
+ font_cascade_list: font.font_cascade_list as usize,
+ };
+ Ok(ComputedInitialStyle {
+ payloads,
+ value_facts: values.into_facts(),
+ flags,
+ dependency_flags,
+ color: color_inputs.1,
+ font: initial_font,
+ })
+ }
+ Err(Unanswered::Suspended(Suspension::Font)) => {
+ Err(Some(Box::new(font_scratch.take_suspended_request())))
+ }
+ _ => Err(None),
+ }
+ })
+ }
+
+ /// The engine: compute the record of `node` from the cascade winners it decided, against the
+ /// records `records` holds for its ancestors, into a table seeded from `initial` and the
+ /// inherited values of the parent's table. A winner the engine computes directly absolutizes
+ /// against the element's context; the others go through the longhand drive, which then
+ /// evaluates only them and the inputs every drive evaluates. An element whose winners all
+ /// compute directly does not run the drive. Only the groups the winners move are assembled
+ /// into `payloads`; the others share the parent's payload or the initial one. Each payload
+ /// holds one reference the caller releases. A winner is the property it decides, whether it
+ /// is important, and where it was declared: its source and its index in the source's block,
+ /// highest priority first. Answers the frozen table, the element's resolved current color,
+ /// and whether the element ran no drive.
+ /// The engine: whether the `content` the pseudo-element of `kind` cascades to lets it generate a
+ /// box: `none` generates nothing for every kind, and `normal`, the initial value, nothing for a
+ /// `::before` or `::after`.
+ pub(in crate::css::style) fn pseudo_content_generates(&self, winners: &[Winner], kind: u8) -> bool {
+ use crate::css::property_metadata::property_id as prop;
+ use crate::css::style_compute::keyword;
+ let generated = matches!(kind, pseudo_kind::BEFORE | pseudo_kind::AFTER);
+ let Some(&Winner { source, index, .. }) = winners.iter().find(|winner| winner.property == prop::CONTENT) else {
+ return !generated;
+ };
+ let WinnerSource::Rule(rule) = source else {
+ return true;
+ };
+ match self
+ .rules
+ .written_values_of(rule)
+ .get(index)
+ .and_then(RetainedStyleValueData::optional_data)
+ {
+ Some(crate::css::style_value::StyleValueData::Keyword { keyword }) => {
+ *keyword != keyword::NONE && (*keyword != keyword::NORMAL || !generated)
+ }
+ _ => true,
+ }
+ }
+
+ #[allow(clippy::too_many_arguments, clippy::too_many_lines)]
+ pub(in crate::css::style) fn drive_element(
+ &self,
+ records: &impl drive::DriveRecords,
+ node: StyleNodeID,
+ parent: Option<(StyleNodeID, u32)>,
+ initial: &super::traversal::InitialStyle,
+ winners: &[Winner],
+ cascade: &dyn CascadeBelow,
+ suspended_font: &mut Option<font_resolution::FontRequest>,
+ random_requests: &mut Vec<super::random_bases::RandomBaseRequest>,
+ custom_properties: super::custom_properties::CustomPropertyStores<'_>,
+ group_cache: &mut GroupCache,
+ absolutized: &mut crate::css::style_compute::AbsolutizedValues,
+ target_pseudo_kind: u8,
+ root_font: Option<RootFontInputs>,
+ group_seeds: GroupSeeds<'_>,
+ ) -> Drive<ComputedElement> {
+ use crate::css::property_metadata::{FIRST_LONGHAND_PROPERTY_ID, LONGHAND_WORD_COUNT, property_id as prop};
+ use crate::css::style_compute::{
+ DIRECTION_COUNT, LOGICAL_ALIAS_BIT, PHYSICAL_TO_LOGICAL_BIT, WRITING_MODE_COUNT,
+ map_logical_alias_to_physical, map_physical_to_logical_alias, table_row_bits,
+ };
+ use crate::css::table_group_builder::group_index;
+
+ // Root-relative lengths resolve against the font of the document element's record as the
+ // pass has it, where the pass knows one, rather than the inputs installed before.
+ let mut inputs = self.document_style_computation_inputs;
+ if let Some(root_font) = root_font {
+ root_font.apply_to(&mut inputs);
+ }
+ let GroupSeeds {
+ seeds,
+ parent: seeded_parent,
+ } = group_seeds;
+ let parent_view = match parent {
+ Some((parent, _)) => Some(records.assigned_record_view(parent).ok_or(Unanswered::AwaitsParent)?),
+ None => None,
+ };
+ let parent_longhands = parent_view.as_ref().map(computed::StyleRecordView::longhands);
+ let parent_overlay = parent_view.as_ref().and_then(|view| view.animated_overlay);
+ // A pseudo-element's computation reads only the facts about its element's markup language.
+ let is_pseudo_element = target_pseudo_kind != u8::MAX;
+ let declared_only = cascade.declared_only();
+ let facts = declared_only.map_or_else(|| self.projection.adjustment_facts(node), |own| own.facts);
+ let facts = match is_pseudo_element {
+ true => facts & PSEUDO_ELEMENT_ADJUSTMENT_FACTS,
+ false => facts,
+ };
+
+ // Which winners compute directly, with their values, and which need the drive.
+ let element_declarations = [
+ ElementDeclarationKind::InlineStyle,
+ ElementDeclarationKind::PresentationalHint,
+ ElementDeclarationKind::SvgPresentationAttribute,
+ ]
+ .map(|kind| {
+ match declared_only {
+ Some(own) => Some(own.declarations.declarations(kind)),
+ None => self.element_declarations.declarations(node, kind),
+ }
+ .map(|declarations| (kind, declarations))
+ });
+ // The written values of the declarations live for the pass, so only substituted and
+ // defaulted ones are held here.
+ let mut easy: smallvec::SmallVec<[DirectWinner<'_>; 24]> = smallvec::SmallVec::new();
+ let mut hard: smallvec::SmallVec<[u16; 24]> = smallvec::SmallVec::new();
+ // The font longhands that compute natively, where the element resolves its font without
+ // a drive.
+ let mut native_font: smallvec::SmallVec<[(u16, std::borrow::Cow<'_, RetainedStyleValueData>); 8]> =
+ smallvec::SmallVec::new();
+ // The winners computing directly, with whether each takes the value its parent computed.
+ let mut direct_inheritance: smallvec::SmallVec<[(u16, bool); 24]> = smallvec::SmallVec::new();
+ // What each winner substituted to, where its value waited on substitution.
+ let mut substituted: smallvec::SmallVec<[Option<RetainedStyleValueData>; 24]> = smallvec::SmallVec::new();
+ // The winners that decide anything, with what each substituted to where its value waited
+ // on substitution.
+ let mut deciding: smallvec::SmallVec<[Winner; 24]> = smallvec::SmallVec::new();
+ // Whether a winner computes against the element itself rather than only its context.
+ let mut element_dependent = false;
+ // The style groups of the properties that do not inherit whose value the winners take from the
+ // parent.
+ let mut parent_reset_groups = 0u32;
+ // Whether a winner computes against the element's place among its siblings.
+ let mut reads_sibling_position = false;
+ // How much of the root element's font a winner resolves lengths against.
+ let mut reads_root_font = RootFontReads::None;
+ // Whether a winner resolves a length against a metric of a first available font.
+ let mut reads_font_metric_lengths = false;
+ // What the winners compute from of the document's environment.
+ let mut environment_reads = StyleEnvironment::default();
+ // What the winners' substitutions read beyond the element's custom properties.
+ let mut substitution_reads = 0;
+ // The custom properties the winners substitute, and whether one may read others.
+ let mut custom_property_reads = Vec::new();
+ let mut reads_unnamed_custom_properties = false;
+ // A parent's computed value: its record's, or its table's with the animated value it hands
+ // down where its animations compose.
+ let parent_value = |property: u16| {
+ let parent_longhands = parent_longhands?;
+ parent_longhands
+ .overlay_value(parent_overlay, property)
+ .or_else(|| parent_longhands.handle(property))
+ };
+ // https://drafts.csswg.org/css-logical/#box
+ // A logical alias computes as its physical counterpart for the element's writing mode and
+ // direction, which an element declaring neither has from its parent.
+ let parent_flow =
+ match winners
+ .iter()
+ .any(|winner| winner.property == prop::WRITING_MODE || winner.property == prop::DIRECTION)
+ {
+ true => None,
+ false => parent_value(prop::WRITING_MODE).zip(parent_value(prop::DIRECTION)).map(
+ |(writing_mode, direction)| {
+ crate::css::style_compute::writing_mode_and_direction_of(Some(writing_mode), Some(direction))
+ },
+ ),
+ };
+ // The logical aliases declared with a CSS-wide keyword that compute directly, with the
+ // physical longhand each computes as and whether it takes the parent's value.
+ let mut keyword_aliases: smallvec::SmallVec<[(u16, u16, bool); 8]> = smallvec::SmallVec::new();
+ // Each winner's classification, with the declaration it decides with and, where it rolled
+ // back below a revert, the place of that declaration and of the revert.
+ let mut resolved: smallvec::SmallVec<[(_, _, Option<RolledBack>); 24]> = smallvec::SmallVec::new();
+ let mut rolled_below = false;
+ for (position, &winner) in winners.iter().enumerate() {
+ // https://drafts.csswg.org/css-cascade-5/#default
+ // `revert` and `revert-layer`, declared or substituted, roll the property back below
+ // the declaration that held them, to a lower declaration that is substituted in turn.
+ // The declarations it rolled back, with the keyword of each.
+ let mut reverted: smallvec::SmallVec<[(CascadePriority, CascadeOperator); 2]> = smallvec::SmallVec::new();
+ let (mut priority, mut winner) = (None, winner);
+ let classified = loop {
+ let Winner {
+ property,
+ important,
+ source,
+ index,
+ } = winner;
+ let mut classified =
+ self.classify_winner(&element_declarations, custom_properties, property, source, index);
+ // A declaration that rolls back still decides where it does.
+ custom_property_reads.append(&mut classified.reads.custom_properties);
+ reads_unnamed_custom_properties |= classified.reads.unnamed_custom_properties;
+ let operator = match &classified.value {
+ ResolvedWinnerValue::Substituted(value) => value
+ .optional_data()
+ .map(crate::css::declaration_block::declaration_operator),
+ _ => classified.reads.css_wide_keyword,
+ };
+ let Some(operator @ (CascadeOperator::Revert | CascadeOperator::RevertLayer)) = operator else {
+ break Some(classified);
+ };
+ reverted.push((
+ priority.unwrap_or_else(|| cascade.priority_of(source, important)),
+ operator,
+ ));
+ // What the property rolls back to is decided by declarations the winners do not name.
+ element_dependent = true;
+ match cascade.winner_below(property, &reverted) {
+ Some((lower_priority, lower)) => (priority, winner) = (Some(lower_priority), lower),
+ // Nothing below declares the property, which is undeclared and computes as the
+ // element's seed holds it.
+ // https://drafts.csswg.org/css-logical/#box
+ // A logical or physical counterpart declared before the revert, which the revert
+ // rolls back past as well, leaves the group's value as if it were not declared
+ // either: the property computes as `unset` in the place of the revert.
+ None if !winners[position + 1..].iter().any(
+ |&Winner {
+ property: other,
+ important: other_important,
+ source: other_source,
+ ..
+ }| {
+ is_logical_counterpart(property, other)
+ && reverted[0]
+ .0
+ .reverts_past(reverted[0].1, &cascade.priority_of(other_source, other_important))
+ },
+ ) =>
+ {
+ break None;
+ }
+ None => {
+ // The revert decides in its own place.
+ winner = winners[position];
+ priority = None;
+ break Some(ClassifiedWinner {
+ value: ResolvedWinnerValue::Substituted(RetainedStyleValueData::from_owned(
+ crate::css::style_value::StyleValueData::Keyword {
+ keyword: crate::css::style_compute::keyword::UNSET,
+ },
+ )),
+ computation: WinnerComputation::Full,
+ reads: WinnerReads {
+ element: true,
+ parent_reset_value: !crate::css::property_metadata::property_is_inherited(property),
+ css_wide_keyword: Some(CascadeOperator::Unset),
+ sibling_position: false,
+ substitution: 0,
+ ..WinnerReads::default()
+ },
+ });
+ }
+ }
+ };
+ let rolled_back = priority.map(|priority| RolledBack {
+ place: (priority, winner.index),
+ revert: (reverted[0].0, winners[position].index),
+ operator: reverted[0].1,
+ });
+ rolled_below |= rolled_back.is_some();
+ resolved.push((winner, classified, rolled_back));
+ }
+ // https://drafts.csswg.org/css-logical/#box
+ // Of a logical property and its physical counterpart, the one declared with higher priority
+ // decides both. A property rolled back below a revert decides at the place of the
+ // declaration it rolled back to, unless the revert is above a counterpart that does not
+ // roll back and rolls back past it as well: the group's value is then as if the
+ // counterpart were not declared either, and the property decides at the place of the
+ // revert.
+ if rolled_below {
+ // The longhand of each winner, the place it decides at, and whether it rolled back.
+ type Place = (u16, (CascadePriority, usize), bool);
+ let places: smallvec::SmallVec<[Place; 24]> = resolved
+ .iter()
+ .map(|&(winner, _, ref rolled_back)| match rolled_back {
+ Some(rolled_back) => (winner.property, rolled_back.place, true),
+ None => (
+ winner.property,
+ (cascade.priority_of(winner.source, winner.important), winner.index),
+ false,
+ ),
+ })
+ .collect();
+ let key = |position: usize, rolled_back: &Option<RolledBack>| match rolled_back {
+ Some(rolled_back)
+ if places.iter().any(|&(property, counterpart, rolled)| {
+ !rolled
+ && is_logical_counterpart(places[position].0, property)
+ && rolled_back.revert > counterpart
+ && rolled_back.revert.0.reverts_past(rolled_back.operator, &counterpart.0)
+ }) =>
+ {
+ rolled_back.revert
+ }
+ _ => places[position].1,
+ };
+ let mut keyed: smallvec::SmallVec<[_; 24]> = resolved
+ .into_iter()
+ .enumerate()
+ .map(|(position, entry)| (key(position, &entry.2), entry))
+ .collect();
+ keyed.sort_by(|(a, _), (b, _)| b.cmp(a));
+ resolved = keyed.into_iter().map(|(_, entry)| entry).collect();
+ }
+ for (winner, classified, _) in resolved {
+ let Some(ClassifiedWinner {
+ value,
+ computation,
+ reads,
+ }) = classified
+ else {
+ continue;
+ };
+ substitution_reads |= reads.substitution;
+ let property = winner.property;
+ element_dependent |= reads.element;
+ if reads.parent_reset_value {
+ parent_reset_groups |= crate::css::property_metadata::property_style_group_index(property)
+ .map_or(u32::MAX, |group| 1 << group);
+ }
+ reads_sibling_position |= reads.sibling_position;
+ reads_root_font = reads_root_font.max(reads.root_font);
+ reads_font_metric_lengths |= reads.font_metrics;
+ environment_reads |= reads.environment | property_environment_reads(property);
+ let Some(written) = value.value() else {
+ continue;
+ };
+ // https://drafts.csswg.org/css-cascade-5/#defaulting-keywords
+ // A CSS-wide keyword's computed value is the initial value or the parent's computed
+ // value, which computes directly as any computed value does.
+ let mut inherits_keyword = false;
+ let is_logical_alias = table_row_bits(property) & LOGICAL_ALIAS_BIT != 0;
+ // The longhand whose parent's value the winner inherits: a logical alias inherits its
+ // physical counterpart's.
+ let mut inherited_property = property;
+ let keyword_value = reads.css_wide_keyword.and_then(|keyword| {
+ if is_logical_alias {
+ let (writing_mode, direction) = parent_flow?;
+ inherited_property = map_logical_alias_to_physical(property, writing_mode, direction);
+ }
+ let inherits = match keyword {
+ CascadeOperator::Inherit => true,
+ CascadeOperator::Initial => false,
+ CascadeOperator::Unset => crate::css::property_metadata::property_is_inherited(property),
+ _ => return None,
+ };
+ inherits_keyword = inherits;
+ match (inherits, parent_longhands.is_some()) {
+ (true, true) => parent_value(inherited_property),
+ // NB: Both longhands of a logical pair take the alias's initial value, where a
+ // drive gives each its own.
+ _ => {
+ let initial_value = |property| {
+ Some(initial.longhand(crate::css::computed_values::LonghandID::new(property)))
+ .filter(|value| !value.pointer().is_null())
+ };
+ initial_value(property).filter(|value| initial_value(inherited_property) == Some(*value))
+ }
+ }
+ .filter(|value| {
+ value.optional_data().is_some_and(|data| {
+ crate::css::style_compute::value_computes_directly(property, data, Some(Default::default()))
+ })
+ })
+ .cloned()
+ });
+ if is_logical_alias {
+ if keyword_value.is_some() {
+ keyword_aliases.push((property, inherited_property, inherits_keyword));
+ }
+ } else if matches!(computation, WinnerComputation::Direct(_)) || keyword_value.is_some() {
+ direct_inheritance.push((property, keyword_value.is_some() && inherits_keyword));
+ }
+ let font_computes_natively = !is_logical_alias
+ && matches!(computation, WinnerComputation::Full)
+ && reads.css_wide_keyword.is_none()
+ && written
+ .optional_data()
+ .is_some_and(|data| crate::css::style_compute::font_value_computes_natively(property, data));
+ match (computation, keyword_value) {
+ (_, Some(value)) => easy.push((property, std::borrow::Cow::Owned(value), Some(Default::default()))),
+ (WinnerComputation::Direct(dependencies), None) => easy.push((
+ property,
+ match &value {
+ ResolvedWinnerValue::Written(written) => std::borrow::Cow::Borrowed(*written),
+ _ => std::borrow::Cow::Owned(written.clone()),
+ },
+ dependencies,
+ )),
+ (WinnerComputation::Full, None) if font_computes_natively => native_font.push((
+ property,
+ match &value {
+ ResolvedWinnerValue::Written(written) => std::borrow::Cow::Borrowed(*written),
+ _ => std::borrow::Cow::Owned(written.clone()),
+ },
+ )),
+ (WinnerComputation::Full, None) => hard.push(property),
+ }
+ deciding.push(winner);
+ substituted.push(value.into_substituted());
+ }
+ // Both longhands of a logical pair take their value from the one declared with higher
+ // priority, so where the alias's physical counterpart is declared as well, the alias's
+ // keyword computes directly only where the two inherit alike, and so mark the pair alike.
+ keyword_aliases.retain(|&mut (alias, physical, inherits)| {
+ let alike = direct_inheritance
+ .iter()
+ .all(|&(property, inherited)| property != physical || inherited == inherits);
+ if !alike {
+ easy.retain(|(property, ..)| *property != alias);
+ hard.push(alias);
+ }
+ alike
+ });
+ let winners = &deciding[..];
+ let mut groups = 0_u32;
+ for winner in winners {
+ groups |= moved_longhand_groups(winner.property);
+ }
+ // A drive evaluates the box inputs itself, so with a drive they are the drive's.
+ // A zoom scales the computed values of longhands the element does not declare, such as the
+ // font size it inherits or the initial widths of its borders, so an element declaring one
+ // or inheriting a zoom other than one has every longhand driven.
+ // https://drafts.csswg.org/css-pseudo-4/#highlight-cascade
+ // A highlight pseudo-element inherits from another one than its element, which only a drive
+ // of every longhand reads.
+ // https://drafts.csswg.org/css-color-adjust-1/#color-scheme-effect
+ // The root's initial values, such as the `canvastext` of color, resolve against the color
+ // scheme it uses, which the initial values the seed holds were not computed under.
+ let drives_everything = parent_view.is_none()
+ || pseudo_kind::is_highlight(target_pseudo_kind)
+ || winners.iter().any(|winner| winner.property == prop::ZOOM)
+ || parent_longhands.is_some_and(|longhands| longhands.effective_zoom() != 1.0);
+ // A drive of every longhand computes the color scheme and the widths of borders it does
+ // not declare against the document's environment.
+ if drives_everything {
+ environment_reads |= StyleEnvironment::COLOR_SCHEME | StyleEnvironment::DEVICE_PIXEL_RATIO;
+ }
+ // The used line height the font group holds reads a line-height computing natively.
+ if !native_font.is_empty() {
+ groups |= 1 << group_index::FONT;
+ }
+ // The document element builds every group, its font group against the document's initial
+ // font.
+ let builds_font = groups & (1 << group_index::FONT) != 0 || parent_view.is_none();
+ // An element whose font group moves resolves its font itself where its font longhands
+ // compute natively against its parent's font, which reads no viewport, and nothing
+ // zooms the sizes.
+ // NB: The line-height the adjustments of an input or a select element settle, which its
+ // font group holds, is a drive's.
+ let resolves_font = builds_font
+ && parent_view
+ .as_ref()
+ .is_none_or(|view| view.dependency_flags & FONT_METRICS_DEPEND_ON_VIEWPORT_METRICS == 0)
+ && !(inputs.root_effective_zoom > 0.0 && inputs.root_effective_zoom != 1.0)
+ && facts
+ & (bridge::element_adjustment_fact::CHECK_INPUT_LINE_HEIGHT
+ | bridge::element_adjustment_fact::FORCE_LINE_HEIGHT_NORMAL)
+ == 0;
+ let runs_drive = drives_everything || !hard.is_empty() || (builds_font && !resolves_font);
+ // A drive maps a logical alias by the writing mode and direction it computes, and marks
+ // the pair itself.
+ if runs_drive {
+ // NB: The drive builds the font group from the table as it ends its font phases, so
+ // the longhands the font group carries compute in it rather than after it.
+ hard.extend(native_font.drain(..).map(|(property, _)| property));
+ easy.retain(|(property, ..)| {
+ let is_input = crate::css::style_compute::is_required_driver_input(*property)
+ || property_feeds_box_type_transformation(*property)
+ || font_group_carries_longhand(*property)
+ || keyword_aliases.iter().any(|&(alias, ..)| alias == *property);
+ if is_input {
+ hard.push(*property);
+ }
+ !is_input
+ });
+ } else {
+ for &(alias, physical, inherits) in &keyword_aliases {
+ direct_inheritance.push((alias, inherits));
+ direct_inheritance.push((physical, inherits));
+ }
+ direct_inheritance.extend(native_font.iter().map(|&(property, _)| (property, false)));
+ }
+ // https://drafts.csswg.org/css-backgrounds-3/#layering
+ // The background layer longhands repeat to as many layers as background-image has, which
+ // the drive coordinates them to as it computes background-image.
+ if hard.contains(&prop::BACKGROUND_IMAGE) {
+ easy.retain(|(property, ..)| {
+ let is_layer = crate::css::style_compute::BACKGROUND_LAYER_LONGHANDS.contains(property);
+ if is_layer {
+ hard.push(*property);
+ }
+ !is_layer
+ });
+ }
+
+ let mut selected = [0_u64; LONGHAND_WORD_COUNT];
+ let mut select = |property: u16, groups: &mut u32| {
+ let index = usize::from(property - FIRST_LONGHAND_PROPERTY_ID);
+ selected[index / 64] |= 1 << (index % 64);
+ *groups |= moved_longhand_groups(property);
+ };
+ for &property in &hard {
+ select(property, &mut groups);
+ let bits = table_row_bits(property);
+ if bits & (LOGICAL_ALIAS_BIT | PHYSICAL_TO_LOGICAL_BIT) != 0 {
+ for writing_mode in 0..WRITING_MODE_COUNT as u8 {
+ for direction in 0..DIRECTION_COUNT as u8 {
+ let counterpart = if bits & LOGICAL_ALIAS_BIT != 0 {
+ map_logical_alias_to_physical(property, writing_mode, direction)
+ } else {
+ map_physical_to_logical_alias(property, writing_mode, direction)
+ };
+ select(counterpart, &mut groups);
+ }
+ }
+ }
+ // A line's width computes to zero when its style is `none` or `hidden`.
+ let partner = match property {
+ prop::BORDER_TOP_STYLE => prop::BORDER_TOP_WIDTH,
+ prop::BORDER_RIGHT_STYLE => prop::BORDER_RIGHT_WIDTH,
+ prop::BORDER_BOTTOM_STYLE => prop::BORDER_BOTTOM_WIDTH,
+ prop::BORDER_LEFT_STYLE => prop::BORDER_LEFT_WIDTH,
+ prop::OUTLINE_STYLE => prop::OUTLINE_WIDTH,
+ prop::COLUMN_RULE_STYLE => prop::COLUMN_RULE_WIDTH,
+ _ => continue,
+ };
+ select(partner, &mut groups);
+ }
+
+ // The animated values a parent whose animations compose hands down over the values of its
+ // record.
+ let inherited_overrides =
+ |seeded: &'_ std::sync::Arc<super::pipeline::Record>| -> Vec<(u16, RetainedStyleValueData)> {
+ computed::ViewLonghands::of_record(seeded)
+ .inherited_overrides(parent_overlay)
+ .collect()
+ };
+ // The element's values start from its parent's groups where those hold the values of the
+ // parent's record, with the animated values the parent hands down, and the document
+ // element's from the initial ones. The values of a parent no record of the pass holds are
+ // written over the initial groups. The drive and the direct computation both write into
+ // them.
+ let flags = match parent_view {
+ Some(_) => crate::css::computed_longhand_table::LonghandTableFlags::of_child_seed(&initial.flags),
+ None => crate::css::computed_longhand_table::LonghandTableFlags::of_drive_copy(&initial.flags),
+ };
+ let mut writer = match (parent_view.as_ref(), seeded_parent) {
+ (None, None) => GroupValuesWriter::seeded_for_child(
+ seeds[0],
+ seeds[1],
+ std::iter::empty(),
+ flags,
+ initial.dependency_flags,
+ ),
+ (Some(_), Some(seeded)) if parent_longhands.is_some_and(|longhands| longhands.are_of_record(seeded)) => {
+ GroupValuesWriter::seeded_for_child(
+ seeds[0],
+ seeds[1],
+ inherited_overrides(seeded).into_iter(),
+ flags,
+ initial.dependency_flags,
+ )
+ }
+ _ => {
+ let parent_longhands = parent_longhands.expect("the style engine answers every row");
+ let inherited = crate::css::computed_values::GroupValueLayout::inherited_longhands()
+ .filter_map(|property| Some((property, parent_longhands.handle(property)?.clone())))
+ .chain(parent_longhands.inherited_overrides(parent_overlay));
+ let mut writer =
+ GroupValuesWriter::seeded_for_child(seeds[1], seeds[1], inherited, flags, initial.dependency_flags);
+ writer.set_effective_zoom(parent_longhands.effective_zoom());
+ writer.set_effective_color_scheme(parent_longhands.effective_color_scheme());
+ writer
+ }
+ };
+
+ // The inputs every drive evaluates move their groups only when their values do.
+ let seeded_bits = writer.bits();
+
+ let box_type_input = self.box_type_transformation_input_with(
+ records,
+ facts,
+ match is_pseudo_element {
+ true => crate::css::style_compute::StyleAdjustmentTarget::PseudoElement,
+ false => crate::css::style_compute::StyleAdjustmentTarget::Element,
+ },
+ parent.map(|(parent, _)| parent),
+ );
+ let is_th_element = facts & bridge::element_adjustment_fact::IS_TH != 0;
+ // A container-relative length never computes directly, so only a drive resolves one.
+ let mut container_units = 0;
+ let (mut writer, length, font, author_disables_native_appearance) = if runs_drive {
+ let store = WinnerStore::new(
+ winners
+ .iter()
+ .zip(&substituted)
+ .rev()
+ .map(
+ |(
+ &Winner {
+ property,
+ important,
+ source,
+ index,
+ },
+ substituted,
+ )| {
+ let value = match (substituted, source, declared_only) {
+ (Some(value), ..) => WinnerValue::Substituted {
+ value: value.clone(),
+ source,
+ },
+ // No node holds the declarations of an element no rule reaches.
+ (None, WinnerSource::Element(kind), Some(own)) => WinnerValue::Substituted {
+ value: own.declarations.declarations(kind).written(index).clone(),
+ source,
+ },
+ (None, ..) => WinnerValue::Written { node, source, index },
+ };
+ let origin = cascade.priority_of(source, important).cascade_origin();
+ WinnerDeclaration::new(property, important, value, origin)
+ },
+ )
+ .collect(),
+ );
+ container_units = store.container_unit_mask(self);
+ // https://drafts.csswg.org/css-values-5/#random-caching
+ // A random function computes against the base value its random caching key draws
+ // once. The keys not drawn yet are drawn between passes, and the element waits.
+ let undrawn = store.undrawn_random_keys(self, node);
+ if !undrawn.is_empty() {
+ random_requests.extend(undrawn);
+ return Err(Unanswered::Suspended(Suspension::RandomBaseValues));
+ }
+ let subject = DriveSubject {
+ target: computed::ComputedStyleTarget::new(node, target_pseudo_kind),
+ parent: parent.map(|(parent, _)| parent),
+ facts,
+ };
+ let mut font_scratch = drive::FontDriveScratch::default();
+ let driven = self.engine_drive_with(
+ records,
+ subject,
+ writer,
+ (!drives_everything).then_some(&selected[..]),
+ &store,
+ &inputs,
+ &mut font_scratch,
+ );
+ if matches!(driven, Err(Unanswered::Suspended(Suspension::Font))) {
+ *suspended_font = Some(font_scratch.take_suspended_request());
+ }
+ let drive::DrivenValues {
+ mut writer,
+ length,
+ font,
+ } = driven?;
+ let font = font.expect("the style engine answers every row");
+ let scheme = u8::try_from(writer.effective_color_scheme()).ok();
+ // A drive of every longhand computed the winners that compute directly too.
+ if !drives_everything
+ && !crate::css::style_compute::compute_declared_values(
+ &mut writer,
+ easy.iter()
+ .map(|(property, value, dependencies)| (*property, &**value, *dependencies)),
+ &length,
+ scheme,
+ &box_type_input,
+ is_th_element,
+ false,
+ Some(&selected),
+ absolutized,
+ self.document_style_computation_inputs.device_pixels_per_css_pixel,
+ )
+ {
+ unreachable!("the style engine answers every row");
+ }
+ let author_disables_native_appearance =
+ crate::css::style_compute::has_author_value_disabling_native_appearance(&store.view(self));
+ (writer, length, Some(font), author_disables_native_appearance)
+ } else {
+ // https://drafts.csswg.org/css-fonts/#font-size-prop
+ // NB: The document element's font resolves against the document's initial font, as in
+ // the font phase of a drive.
+ let parent_length = match parent_view.as_ref() {
+ Some(parent_view) => {
+ Self::length_from_parent_font(&inputs, parent_view).expect("the style engine answers every row")
+ }
+ None => Self::length_from_initial_font(&inputs),
+ };
+ let parentless_font_size = parent_view
+ .is_none()
+ .then(|| crate::css::css_pixels::CssPixels::from_raw(inputs.initial_font_size_raw));
+ let scheme = u8::try_from(writer.effective_color_scheme()).ok();
+ // The font longhands compute against the parent's font, line-height against the
+ // element's own font, and the other values against the element's own font and line
+ // height.
+ let compute_font =
+ |values: &mut GroupValuesWriter<'_>,
+ line_height: bool,
+ length: &crate::css::style_compute::FfiLengthResolutionContext| {
+ crate::css::style_compute::compute_font_values(
+ values,
+ native_font
+ .iter()
+ .filter(|&&(property, _)| (property == prop::LINE_HEIGHT) == line_height)
+ .map(|(property, value)| (*property, &**value)),
+ length,
+ inputs.default_font_size_raw,
+ parentless_font_size,
+ )
+ };
+ if !compute_font(&mut writer, false, &parent_length) {
+ unreachable!("the style engine answers every row");
+ }
+ // The element's font, where it resolves one, and the length context of its values.
+ let (font, length) = match resolves_font {
+ false => (None, parent_length),
+ true => {
+ let (font, length) = self.resolve_own_font(
+ node,
+ &mut writer,
+ &inputs,
+ &parent_length,
+ parent_view.is_none(),
+ |values, length| compute_font(values, true, length),
+ suspended_font,
+ )?;
+ (Some(font), length)
+ }
+ };
+ if !crate::css::style_compute::compute_declared_values(
+ &mut writer,
+ easy.iter()
+ .map(|(property, value, dependencies)| (*property, &**value, *dependencies)),
+ &length,
+ scheme,
+ &box_type_input,
+ is_th_element,
+ true,
+ None,
+ absolutized,
+ self.document_style_computation_inputs.device_pixels_per_css_pixel,
+ ) {
+ unreachable!("the style engine answers every row");
+ }
+ // NB: None of these winners reverts, so each is the cascaded value of its property.
+ let author_disables_native_appearance = winners.iter().any(|winner| {
+ crate::css::style_compute::PROPERTIES_DISABLING_NATIVE_APPEARANCE.contains(&winner.property)
+ && matches!(
+ cascade.priority_of(winner.source, winner.important).cascade_origin(),
+ crate::css::cascaded_properties::CascadeOrigin::Author
+ | crate::css::cascaded_properties::CascadeOrigin::AuthorPresentationalHint
+ )
+ });
+ (writer, length, font, author_disables_native_appearance)
+ };
+ // https://drafts.csswg.org/css-ui/#appearance-disabling-properties
+ // NB: Only an element whose appearance is not none can have a native appearance to disable. Leaving the flag
+ // clear for every other element keeps their author backgrounds and borders from splitting style groups.
+ let appearance_is_none = matches!(
+ writer.get(prop::APPEARANCE).map(RetainedStyleValueData::data),
+ Some(StyleValueData::Keyword { keyword }) if *keyword == crate::css::style_compute::keyword::NONE
+ );
+ writer.set_native_appearance_disabled(!appearance_is_none && author_disables_native_appearance);
+ let required_moved = crate::css::style_compute::REQUIRED_DRIVER_INPUTS
+ .iter()
+ .filter(|&&property| writer.moved_from_seed(property, seeded_bits))
+ .fold(0, |groups, &property| groups | moved_longhand_groups(property));
+ let (values, mut flags, dependency_flags) = writer.finish(&seeds);
+ // NB: The flags keep the cascaded font size, which the monospace recascade of a
+ // descendant reads, as a drive's table does.
+ if let Some((_, font_size)) = native_font.iter().find(|&&(property, _)| property == prop::FONT_SIZE) {
+ flags.set_raw_cascaded_font_size(Some(font_size.clone().into_owned()));
+ }
+ // NB: A value computed after it was inherited, such as an overflow keyword the other
+ // overflow longhand turns or a display the box adjustments change, is no longer
+ // inherited, as in a drive.
+ let computed_value = |property: u16| values.value(property);
+ // NB: Only a winner taking its parent's value is compared with it: no other is inherited.
+ for &(property, inherits) in &direct_inheritance {
+ let inherited = inherits
+ && (table_row_bits(property) & LOGICAL_ALIAS_BIT != 0
+ || computed_value(property).optional_data()
+ == parent_value(property).and_then(RetainedStyleValueData::optional_data));
+ flags.set_inherited(property, inherited);
+ }
+ // NB: An important declaration wins over the animations of its property, which read from
+ // the table whether it won. A drive marks the longhands it evaluated; the ones computing
+ // directly are marked here.
+ for &Winner {
+ property, important, ..
+ } in winners
+ {
+ if important && table_row_bits(property) & LOGICAL_ALIAS_BIT == 0 {
+ flags.set_important(property, true);
+ }
+ }
+ groups |= required_moved;
+
+ let parent_in_display_none_subtree = parent_view.as_ref().is_some_and(|view| {
+ view.dependency_flags & crate::css::computed_longhand_table::IN_DISPLAY_NONE_SUBTREE != 0
+ });
+ let display_is_none = crate::css::style_compute::display_of(values.value(prop::DISPLAY)).is_none();
+ let facts = super::pipeline::RecordFacts::of_values(
+ |property| values.value(property),
+ dependency_flags,
+ parent_in_display_none_subtree || display_is_none,
+ );
+ // Every group but the font group builds from the element's group values.
+ let group_values = crate::css::table_group_builder::LonghandSource::Values {
+ values: &values,
+ reads: None,
+ };
+ let color_inputs = crate::css::table_group_builder::assembly_color_inputs_from_source(&group_values, &length);
+ let current_color = color_inputs.1;
+ // Groups holding colors resolved against `currentcolor` resolve again where the element's
+ // color differs from the one their shared payload resolved against.
+ let current_color_groups = computed::ComputedGroupSets::specified_value_dependency_mask_of(
+ values
+ .facts()
+ .inheritance_dependent_values()
+ .filter(|(property, value)| {
+ !crate::css::table_group_builder::group_holds_current_color_for_its_reader(
+ *property,
+ value.optional_data(),
+ )
+ }),
+ crate::css::style_value::retained_value_depends_on_current_color,
+ )
+ | crate::css::table_group_builder::groups_reading_current_color_through_inherited_values(|property| {
+ values.value(property).optional_data()
+ });
+ let inherited_groups = (1_u32 << ENGINE_INHERITED_GROUP_COUNT) - 1;
+ let parent_color = parent.map_or(initial.color, |(_, color)| color);
+ if parent_color != current_color {
+ groups |= current_color_groups & inherited_groups;
+ }
+ if initial.color != current_color {
+ groups |= current_color_groups & !inherited_groups;
+ }
+ // NB: The misc layout group holds whether an author declaration disables the native appearance, which no
+ // longhand's value says.
+ if values.facts().native_appearance_disabled() {
+ groups |= 1 << group_index::MISC_LAYOUT;
+ }
+ // The document element's groups all build against no parent.
+ if parent_view.is_none() || drives_everything {
+ groups = (1 << group_index::COUNT) - 1;
+ }
+ // Without a drive, the element's font is its parent's.
+ if font.is_none() {
+ groups &= !(1 << group_index::FONT);
+ }
+
+ // NB: A group that is not built and whose values are the shared group's own is the parent's
+ // or the initial one, taken without a reference of its own: a record sharing its set
+ // needs none, and one that does not counts it as it makes its own set.
+ let shared_payload = |group: usize| match group < ENGINE_INHERITED_GROUP_COUNT {
+ true => parent_view
+ .as_ref()
+ .map_or(std::ptr::null(), |view| view.payloads[group].as_ptr()),
+ false => initial.payloads[group].as_ptr(),
+ };
+ let borrowed = crate::css::computed_values::BorrowedGroups::of_groups_where(|group| {
+ let shared = shared_payload(group);
+ groups & (1 << group) == 0 && !shared.is_null() && values.hold_the_seed(group, shared)
+ });
+ // The lookups of the groups assembled anew, which the cache takes the groups for once they
+ // hold their values.
+ let mut assembled: smallvec::SmallVec<[GroupLookup<'_>; 4]> = smallvec::SmallVec::new();
+ let mut payloads = [std::ptr::null(); group_index::COUNT];
+ for (group, payload) in payloads.iter_mut().enumerate() {
+ let parent_payload = parent_view
+ .as_ref()
+ .map_or(std::ptr::null(), |view| view.payloads[group].as_ptr());
+ *payload = if groups & (1 << group) != 0 {
+ let key = (group != group_index::FONT && group_cache.worth_looking_for(group)).then(|| {
+ // A group holding plain `currentcolor` for its reader is the same whatever the
+ // element's color.
+ let reads_current_color = current_color_groups & (1 << group) != 0
+ || crate::css::table_group_builder::GROUPS_HOLDING_CURRENT_COLOR_FOR_THEIR_READER
+ & (1 << group)
+ == 0;
+ GroupCache::key(&values, group, color_inputs, reads_current_color, &length)
+ });
+ let found = key.as_ref().and_then(|key| group_cache.find(key));
+ if key.is_some() {
+ match found {
+ Some(_) => group_cache.hits[group] += 1,
+ None => group_cache.misses[group] += 1,
+ }
+ }
+ match found {
+ // SAFETY: The cache holds the payload, which is a live background group.
+ Some(payload) if group == crate::css::table_group_builder::group_index::BACKGROUND => unsafe {
+ crate::css::table_group_builder::patch_background_color(
+ &group_values,
+ payload,
+ crate::css::computed_values::GroupShares::new(
+ &self.process_style.default_groups,
+ group,
+ crate::css::computed_values::GroupPayloadRef::new(group, parent_payload),
+ ),
+ color_inputs,
+ &length,
+ )
+ },
+ Some(payload) => {
+ crate::css::computed_values::retain_group_payload(group, payload);
+ payload
+ }
+ None => {
+ // SAFETY: The parent payloads are live for the parent's record.
+ let payload = unsafe {
+ crate::css::table_group_builder::assemble_group_from_source(
+ &group_values,
+ group,
+ font.as_ref(),
+ crate::css::computed_values::GroupShares::new(
+ &self.process_style.default_groups,
+ group,
+ crate::css::computed_values::GroupPayloadRef::new(group, parent_payload),
+ ),
+ color_inputs,
+ &length,
+ )
+ };
+ assembled.extend(key);
+ payload
+ }
+ }
+ } else {
+ let shared = match group < ENGINE_INHERITED_GROUP_COUNT && !parent_payload.is_null() {
+ true => parent_payload,
+ false => initial.payloads[group].as_ptr(),
+ };
+ if !borrowed.contains(group) {
+ crate::css::computed_values::retain_group_payload(group, shared);
+ }
+ shared
+ };
+ }
+ if self.process_style.verifies_reads {
+ Self::verify_value_built_groups(
+ &values,
+ &payloads,
+ groups,
+ color_inputs,
+ &length,
+ &self.process_style.default_groups,
+ );
+ }
+ let before = payloads;
+ // SAFETY: Each payload is a live payload of its group holding a reference for the element,
+ // but the borrowed ones, whose values are the very values the element holds.
+ unsafe { values.put_into(&mut payloads) };
+ for group in (0..group_index::COUNT).filter(|&group| borrowed.contains(group)) {
+ assert_eq!(
+ payloads[group], before[group],
+ "a borrowed group holds the element's values"
+ );
+ }
+ for lookup in &assembled {
+ group_cache.insert(lookup, payloads[lookup.group]);
+ }
+ drop(assembled);
+ let style_bits = values.style_bits();
+ let value_facts = values.into_facts();
+ Ok(ComputedElement {
+ flags,
+ facts,
+ value_facts,
+ // SAFETY: Each payload holds a reference for the element but the borrowed ones, which
+ // are groups of the parent's or the initial style the element shares.
+ groups: unsafe {
+ crate::css::computed_values::ComputedGroups::new(payloads, style_bits, current_color, borrowed)
+ },
+ directly: !runs_drive,
+ element_dependent,
+ custom_property_reads: super::custom_property_cascade::LonghandCustomPropertyReads::new(
+ custom_property_reads,
+ reads_unnamed_custom_properties,
+ ),
+ reads: super::records::ComputationReads {
+ parent_reset_groups,
+ reads_sibling_position,
+ reads_root_font,
+ reads_font_metric_lengths,
+ environment_reads,
+ reads_attributes: false,
+ container_units,
+ },
+ length: crate::css::style_compute::FfiLengthResolutionContext {
+ resolved_viewport_relative_length: std::ptr::null_mut(),
+ ..length
+ },
+ substitution_reads,
+ })
+ }
+
+ /// Checks that each group `groups` names, as the element takes it, shared, found in the cache
+ /// or assembled, is the group its values build anew, reading only what the cache keys cover.
+ /// This is what LIBWEB_VERIFY_STYLE_CHUNKS asks of every element.
+ fn verify_value_built_groups(
+ values: &GroupValues<'_>,
+ payloads: &[*const std::ffi::c_void; crate::css::table_group_builder::group_index::COUNT],
+ groups: u32,
+ (used_color_scheme, current_color): (u8, u32),
+ length: &crate::css::style_compute::FfiLengthResolutionContext,
+ defaults: &crate::css::computed_values::DefaultGroups,
+ ) {
+ use crate::css::table_group_builder::{LonghandSource, group_index, rebuild_group_from_source};
+ for group in (0..group_index::COUNT).filter(|group| groups & (1 << group) != 0) {
+ // The payload handles holding values hold the very values the element computed.
+ // SAFETY: The element's payloads are live groups of their indices.
+ let payload = unsafe { crate::css::computed_values::GroupPayloadRef::new(group, payloads[group]) }
+ .expect("an element holds a group of each index");
+ for (property, place) in GroupValueLayout::handles_of(group) {
+ let (held, computed) = (
+ crate::css::computed_values::value_at(payload, place),
+ values.value(property),
+ );
+ if held.pointer() != computed.pointer() && held != computed {
+ eprintln!(
+ "style group {group} holds another value of longhand {property} than the element computed"
+ );
+ std::process::abort();
+ }
+ }
+ // NB: The font group builds from platform font resources besides the values.
+ let source = LonghandSource::Values {
+ values,
+ reads: Some(GroupValueLayout::get().reads_of(group)),
+ };
+ let Some(built) = rebuild_group_from_source(
+ &source,
+ group,
+ crate::css::computed_values::GroupShares::new(defaults, group, None),
+ current_color,
+ used_color_scheme,
+ Some(length),
+ ) else {
+ continue;
+ };
+ // SAFETY: Both payloads are live payloads of the group.
+ let equal =
+ unsafe { crate::css::computed_values::style_group_payloads_equal(group, built, payloads[group]) };
+ crate::css::computed_values::release_group_payload(group, built);
+ if !equal {
+ eprintln!("style group {group} as the element takes it differs from the one its values build");
+ std::process::abort();
+ }
+ }
+ }
+
+ /// The one value the engine substitutes a font longhand to, so that the font resolver, which
+ /// knows a family and its feature values by their values' identities, finds what it resolved
+ /// for them before.
+ fn canonical_font_value(&self, property: u16, value: RetainedStyleValueData) -> RetainedStyleValueData {
+ let mut values = self
+ .substituted_font_values
+ .lock()
+ .expect("no thread panicked while holding the font values");
+ if let Some((_, canonical)) = values
+ .iter()
+ .find(|(held_property, held)| *held_property == property && held.optional_data() == value.optional_data())
+ {
+ return canonical.clone();
+ }
+ values.push((property, value.clone()));
+ value
+ }
+
+ /// What the engine computes a winner from: its written value, or what that substitutes to where
+ /// it waits on substitution, and, where the value computes directly from a plain declaration
+ /// of a longhand the engine computes directly, the value's external dependencies.
+ #[allow(clippy::too_many_arguments)]
+ fn classify_winner<'a>(
+ &'a self,
+ element_declarations: &[Option<(
+ ElementDeclarationKind,
+ crate::css::style::element_declarations::ElementDeclarations<'a>,
+ )>; 3],
+ custom_properties: super::custom_properties::CustomPropertyStores<'_>,
+ property: u16,
+ source: WinnerSource,
+ index: usize,
+ ) -> ClassifiedWinner<'a> {
+ let (declaration, written, checks) = match source {
+ WinnerSource::Rule(rule) => (
+ *self
+ .rules
+ .declared_properties_of(rule)
+ .get(index)
+ .expect("the style engine answers every row"),
+ self.rules
+ .written_values_of(rule)
+ .get(index)
+ .expect("the style engine answers every row"),
+ self.rules.written_value_checks(rule, index),
+ ),
+ WinnerSource::Element(kind) => {
+ let (_, declarations) = element_declarations
+ .iter()
+ .flatten()
+ .find(|(declarations_kind, _)| *declarations_kind == kind)
+ .expect("the style engine answers every row");
+ (
+ *declarations
+ .declared_property(index)
+ .expect("the style engine answers every row"),
+ declarations.written(index),
+ declarations.checks(index),
+ )
+ }
+ };
+ if checks.waits_on_substitution() {
+ use crate::css::style_value::StyleValueData;
+ let value = match written.data() {
+ // A longhand pending its shorthand's substitution takes its part of the substituted
+ // shorthand.
+ StyleValueData::PendingSubstitution {
+ original_shorthand,
+ original_shorthand_value,
+ } => {
+ let (shorthand, shorthand_written) =
+ written_shorthand_of_pending(*original_shorthand, original_shorthand_value);
+ let resolved = self.substitute_value(custom_properties, shorthand, shorthand_written);
+ match resolved.data() {
+ StyleValueData::GuaranteedInvalid => resolved,
+ _ => expanded_longhand_value(shorthand, property, &resolved)
+ .unwrap_or_else(|| RetainedStyleValueData::from_owned(StyleValueData::GuaranteedInvalid)),
+ }
+ }
+ _ => self.substitute_value(custom_properties, property, written),
+ };
+ // https://drafts.csswg.org/css-variables-2/#invalid-at-computed-value-time
+ // A declaration invalid at computed-value time computes as if `unset`, which the
+ // element's seed already holds for every longhand it does not decide.
+ // What `attr()`, `if()`, `inherit()` or a custom function substitutes is the element's
+ // alone.
+ let reads_subject = super::custom_property_cascade::value_reads_substitution_subject(written.data())
+ || super::custom_property_cascade::value_reads_inherited_values(written.data());
+ let substitution = super::custom_property_cascade::substitution_reads(written.data());
+ let mut custom_properties = Vec::new();
+ let unnamed_custom_properties = !super::custom_property_cascade::append_named_custom_property_reads(
+ written.data(),
+ &mut custom_properties,
+ );
+ if matches!(value.optional_data(), Some(StyleValueData::GuaranteedInvalid)) {
+ return ClassifiedWinner {
+ value: ResolvedWinnerValue::Unset,
+ computation: WinnerComputation::Full,
+ reads: WinnerReads {
+ element: reads_subject,
+ substitution,
+ custom_properties,
+ unnamed_custom_properties,
+ ..WinnerReads::default()
+ },
+ };
+ }
+ // https://drafts.csswg.org/css-cascade-5/#defaulting-keywords
+ // A substitution that produces a CSS-wide keyword takes the keyword's value, as a
+ // declaration of the keyword itself does.
+ let operator = value
+ .optional_data()
+ .map(crate::css::declaration_block::declaration_operator);
+ if let Some(operator @ (CascadeOperator::Inherit | CascadeOperator::Initial | CascadeOperator::Unset)) =
+ operator
+ {
+ let parent_reset_value = operator != CascadeOperator::Initial
+ && !crate::css::property_metadata::property_is_inherited(property);
+ return ClassifiedWinner {
+ value: ResolvedWinnerValue::Substituted(value),
+ computation: WinnerComputation::Full,
+ reads: WinnerReads {
+ element: reads_subject,
+ parent_reset_value,
+ css_wide_keyword: Some(operator),
+ sibling_position: false,
+ root_font: RootFontReads::None,
+ font_metrics: false,
+ environment: StyleEnvironment::default(),
+ substitution,
+ custom_properties,
+ unnamed_custom_properties,
+ },
+ };
+ }
+ let value = match crate::css::style_compute::computes_in_font_phases(property) {
+ true => self.canonical_font_value(property, value),
+ false => value,
+ };
+ let computation = match declaration.operator() == CascadeOperator::Declared
+ && value
+ .optional_data()
+ .is_some_and(|data| crate::css::style_compute::value_computes_directly(property, data, None))
+ {
+ true => WinnerComputation::Direct(None),
+ false => WinnerComputation::Full,
+ };
+ let substituted_dependencies = value
+ .optional_data()
+ .map(crate::css::style_compute::try_external_value_dependencies);
+ let element_dependent = reads_subject || substituted_dependencies.is_none_or(depends_on_element);
+ let sibling_position = substituted_dependencies.is_none_or(reads_sibling_position);
+ let root_font = reads_root_font(value.optional_data(), substituted_dependencies.flatten());
+ let font_metrics = reads_font_metrics(value.optional_data(), substituted_dependencies.flatten());
+ let environment = environment_reads(value.optional_data(), substituted_dependencies.flatten());
+ let parent_reset_value = !crate::css::property_metadata::property_is_inherited(property)
+ && value
+ .optional_data()
+ .is_some_and(crate::css::style_compute::value_is_css_wide_keyword);
+ return ClassifiedWinner {
+ value: ResolvedWinnerValue::Substituted(value),
+ computation,
+ reads: WinnerReads {
+ element: element_dependent,
+ parent_reset_value,
+ css_wide_keyword: None,
+ sibling_position,
+ root_font,
+ font_metrics,
+ environment,
+ substitution,
+ custom_properties,
+ unnamed_custom_properties,
+ },
+ };
+ }
+ let value = match written.data() {
+ data @ crate::css::style_value::StyleValueData::Shorthand { .. } => {
+ shorthand_longhand_data(property, data).expect("the style engine answers every row")
+ }
+ _ => written,
+ };
+ if declaration.operator() != CascadeOperator::Declared {
+ let parent_reset_value = declaration.operator() == CascadeOperator::Inherit
+ && !crate::css::property_metadata::property_is_inherited(property);
+ return ClassifiedWinner {
+ value: ResolvedWinnerValue::Written(value),
+ computation: WinnerComputation::Full,
+ reads: WinnerReads {
+ element: false,
+ parent_reset_value,
+ css_wide_keyword: Some(declaration.operator()),
+ sibling_position: false,
+ substitution: 0,
+ ..WinnerReads::default()
+ },
+ };
+ }
+ let prepared = checks.dependencies();
+ let dependencies =
+ (prepared & winner_store::DEPENDENCIES_COMPUTED != 0).then(|| winner_store::unpack_dependencies(prepared));
+ let computation = match value
+ .optional_data()
+ .is_some_and(|data| crate::css::style_compute::value_computes_directly(property, data, dependencies))
+ {
+ true => WinnerComputation::Direct(dependencies),
+ false => WinnerComputation::Full,
+ };
+ let value_dependencies = value
+ .optional_data()
+ .map(|data| dependencies.or_else(|| crate::css::style_compute::try_external_value_dependencies(data)));
+ let element_dependent = value_dependencies.is_none_or(depends_on_element);
+ let sibling_position = value_dependencies.is_none_or(reads_sibling_position);
+ let root_font = reads_root_font(value.optional_data(), dependencies);
+ let font_metrics = reads_font_metrics(value.optional_data(), dependencies);
+ let environment = environment_reads(value.optional_data(), dependencies);
+ ClassifiedWinner {
+ value: ResolvedWinnerValue::Written(value),
+ computation,
+ reads: WinnerReads {
+ element: element_dependent,
+ parent_reset_value: false,
+ css_wide_keyword: None,
+ sibling_position,
+ root_font,
+ font_metrics,
+ environment,
+ substitution: 0,
+ ..WinnerReads::default()
+ },
+ }
+ }
+
+ /// The font of an element whose font longhands computed natively into `values`, resolved as a
+ /// drive resolves it, as its font group builds from it, with the length context of the
+ /// element's own font and line height, the parent's being `parent_length`. Its line-height
+ /// computes into `values` by `compute_line_height` in between. Suspends on a font the
+ /// document's resolver has not resolved yet.
+ #[allow(clippy::too_many_arguments)]
+ fn resolve_own_font(
+ &self,
+ node: StyleNodeID,
+ values: &mut GroupValuesWriter<'_>,
+ inputs: &bridge::FfiDocumentStyleComputationInputs,
+ parent_length: &crate::css::style_compute::FfiLengthResolutionContext,
+ is_document_element: bool,
+ compute_line_height: impl FnOnce(
+ &mut GroupValuesWriter<'_>,
+ &crate::css::style_compute::FfiLengthResolutionContext,
+ ) -> bool,
+ suspended_font: &mut Option<font_resolution::FontRequest>,
+ ) -> Drive<(
+ crate::css::table_group_builder::FfiFontGroupBuildInputs,
+ crate::css::style_compute::FfiLengthResolutionContext,
+ )> {
+ let request = engine_sample::font_resolution_request(
+ |property| values.get(property),
+ inputs,
+ || self.font_feature_values_scope(node),
+ );
+ let Some(resolved) = self
+ .font_resolution
+ .as_ref()
+ .and_then(|resolutions| resolutions.lookup(request))
+ else {
+ *suspended_font = Some(font_resolution::FontRequest::new(request));
+ return Err(Unanswered::Suspended(Suspension::Font));
+ };
+ let own_length = |line_height: f64| {
+ let font_metrics = crate::css::style_compute::FfiFontMetrics {
+ font_size: request.font_size(),
+ x_height: drive::drive_font_metric(resolved.x_height),
+ cap_height: drive::drive_font_metric(resolved.ascent),
+ zero_advance: drive::drive_font_metric(resolved.zero_advance),
+ line_height,
+ };
+ // NB: The document element's root-relative lengths resolve against its own font, as
+ // in the line-height and remaining phases of a drive.
+ crate::css::style_compute::FfiLengthResolutionContext {
+ font_metrics,
+ root_font_metrics: match is_document_element {
+ true => font_metrics,
+ false => parent_length.root_font_metrics,
+ },
+ root_font_metrics_depend_on_viewport_metrics: match is_document_element {
+ true => parent_length.font_metrics_depend_on_viewport_metrics,
+ false => parent_length.root_font_metrics_depend_on_viewport_metrics,
+ },
+ ..*parent_length
+ }
+ };
+ // NB: Line-height computes against the element's own font and its parent's line height,
+ // as in the line-height phase of a drive.
+ if !compute_line_height(values, &own_length(parent_length.font_metrics.line_height)) {
+ unreachable!("the style engine answers every row");
+ }
+ let line_height = engine_sample::used_line_height(|property| values.get(property), &request, &resolved);
+ Ok((
+ engine_sample::font_group_build_inputs(|property| values.get(property), &request, line_height, &resolved),
+ own_length(line_height),
+ ))
+ }
+
+ /// The length context the document element's font resolves against: the document's initial
+ /// font, as its own and the root font.
+ fn length_from_initial_font(
+ inputs: &bridge::FfiDocumentStyleComputationInputs,
+ ) -> crate::css::style_compute::FfiLengthResolutionContext {
+ let initial_metrics = crate::css::style_compute::FfiFontMetrics {
+ font_size: inputs.initial_font_size,
+ x_height: inputs.initial_font_x_height,
+ cap_height: inputs.initial_font_cap_height,
+ zero_advance: inputs.initial_font_zero_advance,
+ line_height: inputs.initial_line_height,
+ };
+ crate::css::style_compute::FfiLengthResolutionContext {
+ viewport_width: inputs.viewport_width,
+ viewport_height: inputs.viewport_height,
+ font_metrics: initial_metrics,
+ root_font_metrics: initial_metrics,
+ font_metrics_depend_on_viewport_metrics: false,
+ root_font_metrics_depend_on_viewport_metrics: false,
+ has_container_width_basis: false,
+ has_container_height_basis: false,
+ container_width_basis: 0.0,
+ container_height_basis: 0.0,
+ container_width_basis_depends_on_viewport_metrics: false,
+ container_height_basis_depends_on_viewport_metrics: false,
+ subject_inline_axis_is_horizontal: true,
+ resolved_viewport_relative_length: std::ptr::null_mut(),
+ zoom: 1.0,
+ }
+ }
+
+ /// The length context of an element whose font is its parent's, which it is where it declares
+ /// no font longhand.
+ fn length_from_parent_font(
+ inputs: &bridge::FfiDocumentStyleComputationInputs,
+ parent_view: &computed::StyleRecordView<'_>,
+ ) -> Option<crate::css::style_compute::FfiLengthResolutionContext> {
+ use crate::css::computed_value_types::FontValues;
+ use crate::css::style_compute::{FfiFontMetrics, FfiLengthResolutionContext};
+ use crate::css::table_group_builder::group_index;
+
+ let parent_font_payload = parent_view.payloads[group_index::FONT].as_ptr();
+ if parent_font_payload.is_null() {
+ return None;
+ }
+ // SAFETY: The payload is the parent record's live font group.
+ let parent_font = unsafe { &*parent_font_payload.cast::<FontValues>() };
+ let first_available = parent_font.first_available_font_metrics();
+ Some(FfiLengthResolutionContext {
+ viewport_width: inputs.viewport_width,
+ viewport_height: inputs.viewport_height,
+ font_metrics: FfiFontMetrics {
+ font_size: parent_font.font_size.to_double(),
+ x_height: drive::drive_font_metric(first_available.x_height),
+ cap_height: drive::drive_font_metric(first_available.ascent),
+ zero_advance: drive::drive_font_metric(first_available.zero_advance),
+ line_height: parent_font.line_height_used().to_double(),
+ },
+ root_font_metrics: FfiFontMetrics {
+ font_size: inputs.root_font_size,
+ x_height: inputs.root_font_x_height,
+ cap_height: inputs.root_font_cap_height,
+ zero_advance: inputs.root_font_zero_advance,
+ line_height: inputs.root_line_height,
+ },
+ font_metrics_depend_on_viewport_metrics: parent_view.dependency_flags
+ & FONT_METRICS_DEPEND_ON_VIEWPORT_METRICS
+ != 0,
+ root_font_metrics_depend_on_viewport_metrics: inputs.root_font_metrics_depend_on_viewport_metrics,
+ has_container_width_basis: false,
+ has_container_height_basis: false,
+ container_width_basis: 0.0,
+ container_height_basis: 0.0,
+ container_width_basis_depends_on_viewport_metrics: false,
+ container_height_basis_depends_on_viewport_metrics: false,
+ subject_inline_axis_is_horizontal: parent_view.payloads.inherited_bits().writing_mode()
+ == crate::css::css_enums::writing_mode::HORIZONTAL_TB,
+ resolved_viewport_relative_length: std::ptr::null_mut(),
+ zoom: 1.0,
+ })
+ }
+}
+
+/// What the engine computes a winner from.
+/// The engine: the group payloads a thread assembled, by what each was assembled from, so an element
+/// whose values for a group are the ones another's were takes that payload rather than assembling
+/// its own. A group's payload is a function of the values of the longhands the group reads, which
+/// include every value the group holds, and of its color, color scheme, zoom, box display and
+/// length context; two values equal by content are the same value.
+#[derive(Default)]
+pub(in crate::css::style) struct GroupCache {
+ entries: HashMap<u64, smallvec::SmallVec<[GroupCacheEntry; 1]>>,
+ count: usize,
+ /// How often each group was found and missed since the counts last started over. A group
+ /// whose payloads are rarely the same, such as one holding each element's own inline style,
+ /// is assembled without looking for it until the counts start over.
+ hits: [u32; crate::css::table_group_builder::group_index::COUNT],
+ misses: [u32; crate::css::table_group_builder::group_index::COUNT],
+ lookups: u32,
+ /// The longhands and recorded specified values the groups of the entries read in place of
+ /// computed values, compared by identity, one run per entry, which the keys name by where it
+ /// starts. The entries hold them, as they outlive the pass they came from and no other value
+ /// may take their addresses. Most entries have none.
+ key_values: Vec<(u16, crate::css::style_value::RetainedStyleValueData)>,
+ /// The distinct inputs of the entries, which the keys name by index. The elements of a pass
+ /// mostly assemble their groups against the same ones.
+ key_inputs: Vec<[u64; 18]>,
+}
+
+struct GroupCacheEntry {
+ group: usize,
+ key: GroupKey,
+ payload: *const std::ffi::c_void,
+}
+
+/// How many groups' values a group's build reads at most, as the groups hold them today.
+const READ_GROUPS_INLINE: usize = 3;
+
+/// What an entry's payload was assembled from.
+struct GroupKey {
+ /// The values of the groups the group read any of, in group order, which the entry keeps.
+ groups: smallvec::SmallVec<[crate::css::computed_values::HeldGroup; READ_GROUPS_INLINE]>,
+ /// The recorded specified values the group read in place of computed values, as the run of
+ /// the cache's key values starting here and this long.
+ values_start: u32,
+ values_length: u32,
+ /// The index of the inputs in the cache's key inputs.
+ inputs: u32,
+}
+
+/// What a group's payload is looked for by: the element's values the group reads, which are only
+/// kept in a [`GroupKey`] where the payload goes into the cache.
+struct GroupLookup<'a> {
+ hash: u64,
+ group: usize,
+ values: &'a crate::css::computed_values::GroupValues<'a>,
+ reads: crate::css::computed_values::GroupReads,
+ inputs: [u64; 18],
+}
+
+impl GroupLookup<'_> {
+ /// The longhands and recorded specified values the group reads in place of computed values.
+ fn values_read_in_place(
+ &self,
+ ) -> impl Iterator<Item = (u16, &crate::css::style_value::RetainedStyleValueData)> + '_ {
+ self.values.facts().values_read_in_place(&self.reads)
+ }
+
+ fn matches(&self, group: usize, key: &GroupKey, cache: &GroupCache) -> bool {
+ let start = key.values_start as usize;
+ group == self.group
+ && cache.key_inputs[key.inputs as usize] == self.inputs
+ && self.values.holds_read_values(&self.reads, &key.groups)
+ && cache.key_values[start..start + key.values_length as usize]
+ .iter()
+ .map(|(property, value)| (*property, value.pointer()))
+ .eq(self
+ .values_read_in_place()
+ .map(|(property, value)| (property, value.pointer())))
+ }
+}
+
+// SAFETY: The cache holds counted references to immutable groups, which any thread may read and
+// release, and only the thread styling with it reaches it.
+unsafe impl Send for GroupCache {}
+
+impl GroupCache {
+ /// How many payloads a thread keeps before it starts over.
+ const CAPACITY: usize = 4096;
+
+ /// How many payloads a thread keeps from one pass to the next: what a restyle of a few
+ /// elements finds again, without a large page's groups outliving its pass.
+ const KEPT_ACROSS_PASSES: usize = 256;
+
+ /// Counts the cache's tables and the groups only it holds toward the worker caches.
+ pub(in crate::css::style) fn report_memory(&self, report: &mut crate::css::style::memory_report::MemoryReport) {
+ use crate::css::style::memory_report::MemoryOwner;
+ use crate::heap_size::{map_bytes, vec_bytes};
+ for entry in self.entries.values().flatten() {
+ if report.sizer.first_sight(entry.payload) {
+ let bytes = crate::css::computed_values::group_payload_allocation_bytes(entry.group, entry.payload);
+ report.add(MemoryOwner::WorkerCaches, bytes);
+ }
+ }
+ report.add(
+ MemoryOwner::WorkerCaches,
+ map_bytes(&self.entries) + vec_bytes(&self.key_values) + vec_bytes(&self.key_inputs),
+ );
+ }
+
+ /// This cache, as a thread keeps it for its next pass: as it is where it holds few payloads,
+ /// else empty.
+ pub(in crate::css::style) fn kept(mut self) -> Self {
+ if self.count > Self::KEPT_ACROSS_PASSES {
+ self.clear();
+ }
+ self
+ }
+
+ /// How many lookups the hit counts cover before they start over.
+ const COUNT_PERIOD: u32 = 4096;
+
+ /// Whether looking for a payload of `group` is worth its cost.
+ fn worth_looking_for(&mut self, group: usize) -> bool {
+ self.lookups += 1;
+ if self.lookups == Self::COUNT_PERIOD {
+ self.lookups = 0;
+ self.hits = Default::default();
+ self.misses = Default::default();
+ }
+ self.misses[group] < 32 || self.hits[group] * 4 >= self.misses[group]
+ }
+
+ fn key<'a>(
+ values: &'a crate::css::computed_values::GroupValues<'a>,
+ group: usize,
+ (scheme, current_color): (u8, u32),
+ reads_current_color: bool,
+ length: &crate::css::style_compute::FfiLengthResolutionContext,
+ ) -> GroupLookup<'a> {
+ use crate::css::computed_values::{GroupValueLayout, LonghandID};
+ use std::hash::{Hash, Hasher};
+ let metrics = |metrics: &crate::css::style_compute::FfiFontMetrics| {
+ [
+ metrics.font_size,
+ metrics.x_height,
+ metrics.cap_height,
+ metrics.zero_advance,
+ metrics.line_height,
+ ]
+ .map(f64::to_bits)
+ };
+ let [a, b, c, d, e] = metrics(&length.font_metrics);
+ let [f, g, h, i, j] = metrics(&length.root_font_metrics);
+ let facts = values.facts();
+ let inputs = [
+ u64::from(scheme),
+ if reads_current_color {
+ u64::from(current_color)
+ } else {
+ 0
+ },
+ u64::from(facts.display_before_box_type_transformation())
+ | (u64::from(facts.native_appearance_disabled()) << u32::BITS),
+ u64::from(facts.effective_zoom().to_bits()),
+ length.viewport_width.to_bits(),
+ length.viewport_height.to_bits(),
+ length.zoom.to_bits(),
+ u64::from(length.subject_inline_axis_is_horizontal),
+ a,
+ b,
+ c,
+ d,
+ e,
+ f,
+ g,
+ h,
+ i,
+ j,
+ ];
+ let mut reads = *GroupValueLayout::get().reads_of(group);
+ // A background group's payload for one element is another's with the background color
+ // patched, where the two hold the same values of every other longhand the group reads.
+ // The key of the group leaves the longhand out.
+ if group == crate::css::table_group_builder::group_index::BACKGROUND {
+ let color = GroupValueLayout::get().place(LonghandID::new(
+ crate::css::property_metadata::property_id::BACKGROUND_COLOR,
+ ));
+ reads[color.group()] &= !(1 << color.index());
+ }
+ let mut hasher = crate::fast_hash::fast_hasher();
+ group.hash(&mut hasher);
+ values.read_hash(&reads, &mut hasher);
+ for (property, value) in facts.values_read_in_place(&reads) {
+ hasher.write_u16(property);
+ hasher.write_usize(value.pointer() as usize);
+ }
+ inputs.hash(&mut hasher);
+ GroupLookup {
+ hash: hasher.finish(),
+ group,
+ values,
+ reads,
+ inputs,
+ }
+ }
+
+ /// The payload a group with `key` was assembled to, which the cache holds a reference to.
+ fn find(&self, lookup: &GroupLookup<'_>) -> Option<*const std::ffi::c_void> {
+ let entry = self
+ .entries
+ .get(&lookup.hash)?
+ .iter()
+ .find(|entry| lookup.matches(entry.group, &entry.key, self))?;
+ Some(entry.payload)
+ }
+
+ fn insert(&mut self, lookup: &GroupLookup<'_>, payload: *const std::ffi::c_void) {
+ if self.count == Self::CAPACITY {
+ self.clear();
+ }
+ let group = lookup.group;
+ crate::css::computed_values::retain_group_payload(group, payload);
+ if self.key_inputs.last() != Some(&lookup.inputs) {
+ self.key_inputs.push(lookup.inputs);
+ }
+ let values_start = self.key_values.len();
+ self.key_values.extend(
+ lookup
+ .values_read_in_place()
+ .map(|(property, value)| (property, value.clone())),
+ );
+ let key = GroupKey {
+ groups: lookup.values.held_read_groups(&lookup.reads).collect(),
+ values_start: values_start as u32,
+ values_length: (self.key_values.len() - values_start) as u32,
+ inputs: (self.key_inputs.len() - 1) as u32,
+ };
+ self.entries
+ .entry(lookup.hash)
+ .or_default()
+ .push(GroupCacheEntry { group, key, payload });
+ self.count += 1;
+ }
+
+ fn clear(&mut self) {
+ for entry in self.entries.drain().flat_map(|(_, entries)| entries) {
+ crate::css::computed_values::release_group_payload(entry.group, entry.payload);
+ }
+ self.key_values.clear();
+ self.key_inputs.clear();
+ self.count = 0;
+ }
+}
+
+impl Drop for GroupCache {
+ fn drop(&mut self) {
+ self.clear();
+ }
+}
+
+/// The engine: a winner computing directly, with its value and the external dependencies prepared
+/// for it.
+type DirectWinner<'a> = (
+ u16,
+ std::borrow::Cow<'a, RetainedStyleValueData>,
+ Option<crate::css::style_compute::ExternalValueDependencies>,
+);
+
+/// The engine: what an element's group values start from.
+#[derive(Clone, Copy)]
+pub(in crate::css::style) struct GroupSeeds<'a> {
+ /// The groups the element's values share where they hold the same values: its parent's, then
+ /// the initial ones.
+ pub(in crate::css::style) seeds: [crate::css::computed_values::GroupSeed<'a>; 2],
+ /// The record whose groups the first seed is, or none where it is the initial style's.
+ pub(in crate::css::style) parent: Option<&'a std::sync::Arc<super::pipeline::Record>>,
+}
+
+/// The initial values as a drive computes them, with a reference to each payload.
+pub(in crate::css::style) struct ComputedInitialStyle {
+ pub(in crate::css::style) payloads: [*const std::ffi::c_void; crate::css::table_group_builder::group_index::COUNT],
+ pub(in crate::css::style) value_facts: crate::css::computed_values::GroupValueFacts,
+ pub(in crate::css::style) flags: crate::css::computed_longhand_table::LonghandTableFlags,
+ pub(in crate::css::style) dependency_flags: u8,
+ pub(in crate::css::style) color: u32,
+ pub(in crate::css::style) font: super::traversal::InitialFont,
+}
+
+/// One element's computed style from the engine.
+pub(in crate::css::style) struct ComputedElement {
+ /// The flags the element's records keep beside its values.
+ pub(in crate::css::style) flags: crate::css::computed_longhand_table::LonghandTableFlags,
+ /// What the element's records read of its style without its longhand table.
+ pub(in crate::css::style) facts: super::pipeline::RecordFacts,
+ /// What the element's groups were built from beside their values, which its groups hold.
+ pub(in crate::css::style) value_facts: crate::css::computed_values::GroupValueFacts,
+ /// The element's groups, which its record takes, borrowing those of the sets of its parent's
+ /// or the initial style it shares.
+ pub(in crate::css::style) groups: crate::css::computed_values::ComputedGroups,
+ /// Whether every winner computed directly, without the longhand drive.
+ pub(in crate::css::style) directly: bool,
+ /// Whether a winner computed against the element itself, so the style is the element's alone.
+ pub(in crate::css::style) element_dependent: bool,
+ /// The custom properties the winners substitute.
+ pub(in crate::css::style) custom_property_reads: super::custom_property_cascade::LonghandCustomPropertyReads,
+ /// What else the computation read.
+ pub(in crate::css::style) reads: super::records::ComputationReads,
+ /// What the element's lengths resolve against.
+ pub(in crate::css::style) length: crate::css::style_compute::FfiLengthResolutionContext,
+ /// What the winners' substitutions read beyond the element's custom properties, as
+ /// `FfiNodeRecordReads` bits.
+ pub(in crate::css::style) substitution_reads: u8,
+}
+
+/// A winner with its value resolved, how that computes and what it reads.
+struct ClassifiedWinner<'a> {
+ value: ResolvedWinnerValue<'a>,
+ computation: WinnerComputation,
+ reads: WinnerReads,
+}
+
+/// How a winner's value computes.
+#[derive(Clone, Copy)]
+enum WinnerComputation {
+ /// With the rest of the element's values, in the full computation.
+ Full,
+ /// On its own, with the dependencies that were prepared for it, if any.
+ Direct(Option<crate::css::style_compute::ExternalValueDependencies>),
+}
+
+/// What a winner's computed value reads beyond the element's inherited context.
+#[derive(Default)]
+pub(in crate::css::style) struct WinnerReads {
+ /// Something of the element itself.
+ element: bool,
+ /// The CSS-wide keyword the winner was declared with.
+ css_wide_keyword: Option<CascadeOperator>,
+ /// The parent's value of a property that is not inherited.
+ parent_reset_value: bool,
+ /// The element's place among its siblings.
+ sibling_position: bool,
+ /// How much of the root element's font, through root-relative lengths.
+ root_font: RootFontReads,
+ /// A metric of a first available font, through a font-relative length.
+ font_metrics: bool,
+ /// What of the document's environment the winner's value resolves against.
+ environment: StyleEnvironment,
+ /// What the winner's substitution read beyond the element's custom properties, as
+ /// `FfiNodeRecordReads` bits.
+ substitution: u8,
+ /// The custom properties the winner's substitution read by name.
+ custom_properties: Vec<std::sync::Arc<[u16]>>,
+ /// Whether the winner's substitution may read custom properties it does not name.
+ unnamed_custom_properties: bool,
+}
+
+/// Whether a value computes against something of the element beyond its parent's style and its own
+/// declarations: its place among its siblings, its own random values or its containers. A value
+/// whose dependencies are unknown is taken to.
+/// Whether a value computes against the element's place among its siblings, through a
+/// tree-counting function. A value whose dependencies are unknown is taken to.
+fn reads_sibling_position(dependencies: Option<crate::css::style_compute::ExternalValueDependencies>) -> bool {
+ dependencies.is_none_or(|dependencies| dependencies.uses_tree_counting_function)
+}
+
+/// How much of the root element's font `value` resolves lengths against, by its `dependencies`
+/// where they are known. Root-relative lengths are found by walking the value, which needs no
+/// answer to whether the value is computationally independent.
+fn reads_root_font(
+ value: Option<&StyleValueData>,
+ dependencies: Option<crate::css::style_compute::ExternalValueDependencies>,
+) -> RootFontReads {
+ value.map_or(RootFontReads::None, |value| {
+ dependencies
+ .unwrap_or_else(|| crate::css::style_compute::collect_external_value_dependencies(value))
+ .root_font_reads
+ })
+}
+
+/// Whether `value` resolves a length against a metric of the first available font of the element or
+/// its parent, by its `dependencies` where they are known.
+fn reads_font_metrics(
+ value: Option<&StyleValueData>,
+ dependencies: Option<crate::css::style_compute::ExternalValueDependencies>,
+) -> bool {
+ value.is_some_and(|value| {
+ dependencies
+ .unwrap_or_else(|| crate::css::style_compute::collect_external_value_dependencies(value))
+ .font_metric_relative_length
+ })
+}
+
+/// What of the document's environment `value` resolves against, by its `dependencies` where they
+/// are known: the used color scheme, through `light-dark()` or a system color, the device pixel
+/// ratio, through `image-set()`, and the axes of the viewport its viewport-relative lengths
+/// resolve against.
+fn environment_reads(
+ value: Option<&StyleValueData>,
+ dependencies: Option<crate::css::style_compute::ExternalValueDependencies>,
+) -> StyleEnvironment {
+ let Some(value) = value else {
+ return StyleEnvironment::default();
+ };
+ let dependencies =
+ dependencies.unwrap_or_else(|| crate::css::style_compute::collect_external_value_dependencies(value));
+ let mut reads = StyleEnvironment::default();
+ if dependencies.color_scheme_dependent {
+ reads |= StyleEnvironment::COLOR_SCHEME;
+ }
+ if dependencies.device_pixel_ratio_dependent {
+ reads |= StyleEnvironment::DEVICE_PIXEL_RATIO;
+ }
+ if dependencies.viewport_axes & crate::css::style_compute::VIEWPORT_WIDTH_AXIS != 0 {
+ reads |= StyleEnvironment::VIEWPORT_WIDTH;
+ }
+ if dependencies.viewport_axes & crate::css::style_compute::VIEWPORT_HEIGHT_AXIS != 0 {
+ reads |= StyleEnvironment::VIEWPORT_HEIGHT;
+ }
+ reads
+}
+
+/// What of the document's environment the computed value of `property` reads whatever its value:
+/// `color-scheme` computes the used color scheme, and a border, outline or column rule width is
+/// snapped to device pixels.
+fn property_environment_reads(property: u16) -> StyleEnvironment {
+ use crate::css::property_metadata::property_id as prop;
+ if property == prop::COLOR_SCHEME {
+ return StyleEnvironment::COLOR_SCHEME;
+ }
+ if crate::css::style_compute::property_snaps_as_border_width(property) {
+ return StyleEnvironment::DEVICE_PIXEL_RATIO;
+ }
+ StyleEnvironment::default()
+}
+
+fn depends_on_element(dependencies: Option<crate::css::style_compute::ExternalValueDependencies>) -> bool {
+ dependencies.is_none_or(|dependencies| {
+ dependencies.uses_tree_counting_function
+ || dependencies.uses_random_function
+ || dependencies.container_relative_length_unit_mask != 0
+ })
+}
+
+/// What the engine's cascade of an element holds below its winners, for a winner whose substitution
+/// produces `revert` or `revert-layer`.
+pub(in crate::css::style) trait CascadeBelow {
+ /// The priority of the block a winner of the cascade came from.
+ fn priority_of(&self, source: WinnerSource, important: bool) -> CascadePriority;
+
+ /// The highest declaration of `property` in the cascade that none of the reverting declarations,
+ /// at their priorities with the keywords they substituted to, roll back past, with its priority.
+ fn winner_below(
+ &self,
+ property: u16,
+ reverted: &[(CascadePriority, CascadeOperator)],
+ ) -> Option<(CascadePriority, Winner)>;
+
+ /// The own declarations of an element no rule reaches, which its winners name in place of
+ /// those of the node they are keyed by, where the cascade is of those alone.
+ fn declared_only(&self) -> Option<&super::pipeline::DeclaredOnly>;
+}
+
+pub(in crate::css::style) enum ResolvedWinnerValue<'a> {
+ Written(&'a RetainedStyleValueData),
+ Substituted(RetainedStyleValueData),
+ /// The declaration is invalid at computed-value time.
+ Unset,
+}
+
+impl ResolvedWinnerValue<'_> {
+ fn value(&self) -> Option<&RetainedStyleValueData> {
+ match self {
+ Self::Written(value) => Some(value),
+ Self::Substituted(value) => Some(value),
+ Self::Unset => None,
+ }
+ }
+
+ fn into_substituted(self) -> Option<RetainedStyleValueData> {
+ match self {
+ Self::Written(_) | Self::Unset => None,
+ Self::Substituted(value) => Some(value),
+ }
+ }
+}
+
+/// Where a winner rolled back below a revert decides: at the declaration it rolled back to, by
+/// its block's priority and its index in the block, or at the revert, which rolled back as
+/// `operator`.
+struct RolledBack {
+ place: (CascadePriority, usize),
+ revert: (CascadePriority, usize),
+ operator: CascadeOperator,
+}
+
+/// Whether `other` is the logical or physical counterpart of `property` in some writing mode and
+/// direction.
+fn is_logical_counterpart(property: u16, other: u16) -> bool {
+ use crate::css::style_compute::{
+ DIRECTION_COUNT, LOGICAL_ALIAS_BIT, PHYSICAL_TO_LOGICAL_BIT, WRITING_MODE_COUNT, map_logical_alias_to_physical,
+ map_physical_to_logical_alias, table_row_bits,
+ };
+ let bits = table_row_bits(property);
+ if bits & (LOGICAL_ALIAS_BIT | PHYSICAL_TO_LOGICAL_BIT) == 0 {
+ return false;
+ }
+ (0..WRITING_MODE_COUNT as u8).any(|writing_mode| {
+ (0..DIRECTION_COUNT as u8).any(|direction| {
+ other
+ == match bits & LOGICAL_ALIAS_BIT != 0 {
+ true => map_logical_alias_to_physical(property, writing_mode, direction),
+ false => map_physical_to_logical_alias(property, writing_mode, direction),
+ }
+ })
+ })
+}
+
+/// What a drive computes for: the node whose record it inherits from (the flat-tree parent, or
+/// the originating element of a pseudo-element) and the element facts the computation's
+/// adjustments read.
+#[derive(Clone, Copy)]
+pub(in crate::css::style) struct DriveSubject {
+ /// What is being driven, element or pseudo-element. A drive that suspends to wait for a font
+ /// names it, so the suspended drive can only be resumed by the one it belongs to.
+ pub(in crate::css::style) target: computed::ComputedStyleTarget,
+ /// The flat-tree parent the element inherits from; the document element has none and
+ /// inherits from the initial values.
+ pub(in crate::css::style) parent: Option<StyleNodeID>,
+ pub(in crate::css::style) facts: u32,
+}
+
+/// The element facts a pseudo-element's computation reads: the C++ adjustments for what the
+/// originating element is stay off for its pseudo-elements, past the ones about its markup
+/// language.
+const PSEUDO_ELEMENT_ADJUSTMENT_FACTS: u32 = {
+ use bridge::element_adjustment_fact as fact;
+ fact::IS_MATHML
+ | fact::IS_MATHML_MTABLE
+ | fact::IS_MATHML_MTR
+ | fact::IS_MATHML_MTD
+ | fact::IS_TH
+ | fact::HAS_ANIMATIONS
+};
+
+/// The outermost shorthand a longhand pending substitution takes its part of, and the value that
+/// shorthand was written with. A shorthand nested in another, such as `border-width` in `border`,
+/// is itself pending the outer one.
+fn written_shorthand_of_pending(
+ shorthand: u16,
+ value: &crate::css::style_value::RetainedStyleValueData,
+) -> (u16, &crate::css::style_value::RetainedStyleValueData) {
+ match value.data() {
+ crate::css::style_value::StyleValueData::PendingSubstitution {
+ original_shorthand,
+ original_shorthand_value,
+ } => written_shorthand_of_pending(*original_shorthand, original_shorthand_value),
+ _ => (shorthand, value),
+ }
+}
+
+/// The longhand's part of a substituted shorthand value, as the cascade expands it.
+fn expanded_longhand_value(
+ shorthand: u16,
+ property: u16,
+ value: &crate::css::style_value::RetainedStyleValueData,
+) -> Option<crate::css::style_value::RetainedStyleValueData> {
+ let mut found = None;
+ crate::css::style_compute::expand_shorthands_with(shorthand, value, false, &mut |longhand, data, _| {
+ if longhand == property && found.is_none() {
+ found = Some(data.clone());
+ }
+ });
+ found
+}
+
+fn shorthand_longhand_value(
+ property: u16,
+ data: &crate::css::style_value::StyleValueData,
+) -> Option<crate::css::style_value::RetainedStyleValueData> {
+ let crate::css::style_value::StyleValueData::Shorthand(shorthand_payload) = data else {
+ return None;
+ };
+ let ShorthandPayload {
+ sub_properties, values, ..
+ } = &**shorthand_payload;
+ for (&sub_property, sub_value) in sub_properties.as_slice().iter().zip(values.as_slice()) {
+ if sub_property == property {
+ return Some(sub_value.clone());
+ }
+ if let Some(found) = shorthand_longhand_value(property, sub_value.data()) {
+ return Some(found);
+ }
+ }
+ None
+}
+
+/// Whether a longhand is read by the box-type transformation, which rewrites the computed display.
+/// A `-webkit-box` becomes a block container while its `-webkit-box-orient` and `continue` say
+/// that `-webkit-line-clamp` applies to it.
+fn property_feeds_box_type_transformation(property: u16) -> bool {
+ use crate::css::property_metadata::property_id as prop;
+ matches!(
+ property,
+ prop::DISPLAY | prop::POSITION | prop::FLOAT | prop::_WEBKIT_BOX_ORIENT | prop::CONTINUE
+ )
+}
+
+/// Whether a longhand's new value would start an animation or a transition in the C++
+/// computation, register anchor names there, or feed the counter-style environment identity it
+/// resolves.
+/// The longhands the drive's font resolution selects a font by, which its request carries.
+fn font_resolution_selects_by(property: u16) -> bool {
+ use crate::css::property_metadata::property_id as prop;
+ matches!(
+ property,
+ prop::FONT_FAMILY
+ | prop::FONT_STYLE
+ | prop::FONT_WEIGHT
+ | prop::FONT_WIDTH
+ | prop::FONT_OPTICAL_SIZING
+ | prop::FONT_SIZE_ADJUST
+ )
+}
+
+/// The computed style groups a moved longhand reaches. One the font group carries feeds no group of
+/// its own and reaches every value the font feeds, through the font group: a delta moving it is
+/// driven in full, as is one moving a longhand no registered group names.
+fn moved_longhand_groups(property: u16) -> u32 {
+ use crate::css::table_group_builder::group_index;
+ // NB: The computation writes a longhand the bits beside the groups hold into the bits
+ // themselves: it reaches only the groups other than the one its readers see it in.
+ if crate::css::computed_values::StyleBitField::of(property).is_some() {
+ return StyleGroupMasks::get().dependencies(property)
+ & !crate::css::computed_values::computed_group_output_mask(property).unwrap_or(0);
+ }
+ match StyleGroupMasks::get().dependencies(property) {
+ 0 if font_group_carries_longhand(property) => 1 << group_index::FONT,
+ 0 => (1 << crate::css::table_group_builder::group_index::COUNT) - 1,
+ groups => groups,
+ }
+}
+
+/// The font-phase longhands the font group carries without a group binding of their own.
+fn font_group_carries_longhand(property: u16) -> bool {
+ use crate::css::property_metadata::property_id as prop;
+ font_resolution_selects_by(property)
+ || matches!(
+ property,
+ prop::FONT_FEATURE_SETTINGS
+ | prop::FONT_KERNING
+ | prop::FONT_LANGUAGE_OVERRIDE
+ | prop::FONT_VARIANT_ALTERNATES
+ | prop::FONT_VARIANT_CAPS
+ | prop::FONT_VARIANT_EAST_ASIAN
+ | prop::FONT_VARIANT_EMOJI
+ | prop::FONT_VARIANT_LIGATURES
+ | prop::FONT_VARIANT_NUMERIC
+ | prop::FONT_VARIANT_POSITION
+ | prop::FONT_VARIATION_SETTINGS
+ | prop::MATH_DEPTH
+ | prop::MATH_SHIFT
+ | prop::MATH_STYLE
+ | prop::TEXT_RENDERING
+ )
+}
+
+/// Whether a value resolves against the element itself: a `random()` it draws, or a
+/// container-relative length its query containers measure.
+fn value_resolves_against_the_element(dependencies: &crate::css::style_compute::ExternalValueDependencies) -> bool {
+ dependencies.uses_random_function
+ || dependencies.has_unfixed_random_sharing
+ || dependencies.container_relative_length_unit_mask != 0
+}
+
+/// Whether a written value computes from the record, the parent and the document's computation
+/// inputs alone: no custom-property substitution, and none of the element or sheet facts the C++
+/// computation gathers per drive.
+fn value_computes_without_document_context(value: &StyleValueData) -> bool {
+ // A longhand a shorthand written with a substitution declares holds a pending substitution
+ // until the shorthand resolves.
+ !matches!(
+ value,
+ StyleValueData::Unresolved { .. } | StyleValueData::PendingSubstitution { .. }
+ ) && crate::css::style_compute::value_is_computationally_independent(value).is_some_and(|_| {
+ let dependencies = crate::css::style_compute::external_value_dependencies(value);
+ !value_resolves_against_the_element(&dependencies)
+ && !dependencies.needs_document_base_url
+ && !dependencies.may_need_style_sheet_resource_context
+ && !dependencies.uses_tree_counting_function
+ })
+}
+
+/// The proof that a record reads no resource context: no value its winners give it resolves a
+/// `url()` against a style sheet's or the document's base URL. The engine keeps only such records
+/// across transactions, so a move of those base URLs, which every `history.pushState()` makes
+/// without a `<base>`, leaves nothing it keeps to forget.
+#[derive(Clone, Copy)]
+pub(in crate::css::style) struct ReadsNoResourceContexts(pub(in crate::css::style) ());
+
+/// Static checks attached to the original declaration spelling at input preparation, in one word:
+/// the external dependencies of the value a longhand computes from, packed the way a winner
+/// memoizes them (bits 0-20 and 31), or zero for a value that waits on substitution; whether the
+/// whole value computes without document context (bit 21); and whether its longhand does (bit 22),
+/// where it does not wait on substitution (bit 23 clear).
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[repr(transparent)]
+pub(in crate::css::style) struct WrittenValueChecks(u32);
+
+const _: () = assert!(size_of::<WrittenValueChecks>() == 4);
+const _: () = assert!(
+ winner_store::DEPENDENCY_BITS
+ & (WrittenValueChecks::WHOLE_CONTEXT_FREE
+ | WrittenValueChecks::LONGHAND_CONTEXT_FREE
+ | WrittenValueChecks::WAITS_ON_SUBSTITUTION)
+ == 0
+);
+
+impl WrittenValueChecks {
+ const WHOLE_CONTEXT_FREE: u32 = 1 << 21;
+ const LONGHAND_CONTEXT_FREE: u32 = 1 << 22;
+ const WAITS_ON_SUBSTITUTION: u32 = 1 << 23;
+
+ /// The packed external dependencies of the value, when they were prepared.
+ pub(in crate::css::style) fn dependencies(self) -> u32 {
+ self.0 & winner_store::DEPENDENCY_BITS
+ }
+
+ /// Whether the value waits on `var()` or `attr()` substitution before it computes.
+ pub(in crate::css::style) fn waits_on_substitution(self) -> bool {
+ self.0 & Self::WAITS_ON_SUBSTITUTION != 0
+ }
+
+ pub(in crate::css::style) fn prepare(
+ property: u16,
+ value: &crate::css::style_value::RetainedStyleValueData,
+ ) -> Self {
+ use crate::css::style_value::StyleValueData;
+ let whole_context_free = value_computes_without_document_context(value.data());
+ let longhand_context_free = match value.data() {
+ StyleValueData::Unresolved { .. } | StyleValueData::PendingSubstitution { .. } => None,
+ StyleValueData::Shorthand { .. } => Some(
+ shorthand_longhand_value(property, value.data())
+ .is_some_and(|value| value_computes_without_document_context(value.data())),
+ ),
+ _ => Some(whole_context_free),
+ };
+ // The longhand a shorthand declared whole contributes is what a winner computes from.
+ let dependencies = match value.data() {
+ StyleValueData::Unresolved { .. } | StyleValueData::PendingSubstitution { .. } => 0,
+ StyleValueData::Shorthand { .. } => shorthand_longhand_value(property, value.data())
+ .filter(|value| !matches!(value.data(), StyleValueData::Unresolved { .. }))
+ .and_then(|value| crate::css::style_compute::try_external_value_dependencies(value.data()))
+ .map_or(0, winner_store::pack_dependencies),
+ data => crate::css::style_compute::try_external_value_dependencies(data)
+ .map_or(0, winner_store::pack_dependencies),
+ };
+ debug_assert_eq!(dependencies & !winner_store::DEPENDENCY_BITS, 0);
+ let mut bits = dependencies;
+ if whole_context_free {
+ bits |= Self::WHOLE_CONTEXT_FREE;
+ }
+ match longhand_context_free {
+ None => bits |= Self::WAITS_ON_SUBSTITUTION,
+ Some(true) => bits |= Self::LONGHAND_CONTEXT_FREE,
+ Some(false) => {}
+ }
+ Self(bits)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn pending_longhand_names_the_outermost_written_shorthand() {
+ use crate::css::property_metadata::property_id;
+ use crate::css::style_value::{RetainedStyleValueData, StyleValueData};
+
+ for (shorthand, nested_shorthand) in [
+ (property_id::BACKGROUND, property_id::BACKGROUND_POSITION),
+ (property_id::BORDER, property_id::BORDER_WIDTH),
+ (property_id::FONT, property_id::FONT_VARIANT),
+ ] {
+ let written = RetainedStyleValueData::from_owned(StyleValueData::Number { value: 1.0 });
+ let nested = RetainedStyleValueData::from_owned(StyleValueData::PendingSubstitution {
+ original_shorthand: shorthand,
+ original_shorthand_value: written.clone_retained(),
+ });
+ let (found_shorthand, found_value) = written_shorthand_of_pending(nested_shorthand, &nested);
+ assert_eq!(found_shorthand, shorthand);
+ assert!(std::ptr::eq(found_value.pointer(), written.pointer()));
+ let (found_shorthand, found_value) = written_shorthand_of_pending(shorthand, &written);
+ assert_eq!(found_shorthand, shorthand);
+ assert!(std::ptr::eq(found_value.pointer(), written.pointer()));
+ }
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/custom_properties.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/custom_properties.rs
new file mode 100644
index 00000000000..c33518c84ab
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/custom_properties.rs
@@ -0,0 +1,547 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The engine's custom property stores: the ones an element's custom declarations resolve to, and
+//! what its other declarations substitute against them.
+
+use super::super::custom_property_cascade::{
+ PreparedCustomFunctions, SubstitutionAttributes, SubstitutionInputs, engine_resolution_context,
+ substitute_against_stores, value_calls_custom_functions, value_reads_attributes, value_reads_conditions,
+ value_reads_inherited_values, value_reads_substitution_subject,
+};
+use super::super::*;
+use crate::css::cascaded_properties::resolve_declared_custom_properties;
+use crate::css::custom_properties::{CustomPropertyFinalization, CustomPropertyStore};
+use crate::css::style_value::RetainedStyleValueData;
+use std::ffi::c_void;
+use std::sync::Arc;
+
+/// A written value, a longhand and the identities of the values the value's references resolve to.
+type ReferencesKey = (usize, u16, smallvec::SmallVec<[usize; 4]>);
+
+/// What a written value substituted to against two stores, with the stores, which the entry keeps
+/// alive so that no other store takes the address the key names one of them by.
+struct StoresSubstitution {
+ substituted: RetainedStyleValueData,
+ _stores: [Option<Arc<CustomPropertyStore>>; 2],
+}
+
+/// What a style thread substituted each written value to, keyed by the value, the longhand and
+/// the stores it substituted against.
+#[derive(Default)]
+pub(in crate::css::style) struct SubstitutionCache {
+ /// By the value, the longhand and the identities of the two stores.
+ by_stores: HashMap<(usize, u16, usize, usize), StoresSubstitution>,
+ /// By the value, the longhand and the identities of the values the custom properties it
+ /// references resolve to, which elements holding stores of their own still share. Every
+ /// entry is made alongside one of `by_stores`, whose stores keep those values alive.
+ by_references: HashMap<ReferencesKey, RetainedStyleValueData>,
+}
+
+impl SubstitutionCache {
+ fn insert_by_stores(
+ &mut self,
+ key: (usize, u16, usize, usize),
+ stores: CustomPropertyStores<'_>,
+ substituted: RetainedStyleValueData,
+ ) {
+ self.by_stores.insert(
+ key,
+ StoresSubstitution {
+ substituted,
+ _stores: [stores.own.cloned(), stores.inherited.cloned()],
+ },
+ );
+ }
+}
+
+/// What the registered custom properties of a style element compute against once it computed:
+/// its lengths, place among its siblings and color scheme, and the element whose random caching
+/// keys its random functions draw from, with the keys not drawn yet.
+struct RegisteredValueContext<'a, 'r> {
+ length: &'a crate::css::style_compute::FfiLengthResolutionContext,
+ tree_counting: Option<(u64, u64)>,
+ color_scheme: u8,
+ node: StyleNodeID,
+ random_requests: &'a std::cell::RefCell<&'r mut Vec<super::random_bases::RandomBaseRequest>>,
+ /// Whether a random function drew a base value.
+ drew_random_base_values: &'a std::cell::Cell<bool>,
+}
+
+/// One custom property an element declares, as a store is cascaded from it: the name's identity and
+/// text, its importance, and the declared value.
+type DeclaredCustomProperty = (usize, bool, *const c_void);
+
+/// The stores a style thread resolved, keyed by the stores the parent hands down and holds and
+/// the declarations cascaded over them, each with the parent's stores kept alive so no key's
+/// address is reused.
+pub(in crate::css::style) type StoreCache = HashMap<(usize, usize, Vec<(usize, bool, usize)>), CachedStore>;
+
+/// A store a style thread resolved, after the stores of the parent it resolved over.
+type CachedStore = ([Option<Arc<CustomPropertyStore>>; 2], Option<Arc<CustomPropertyStore>>);
+
+/// The custom-property stores a style element substitutes against: its own and the one it
+/// inherits.
+#[derive(Clone, Copy)]
+pub(in crate::css::style) struct CustomPropertyStores<'a> {
+ pub(in crate::css::style) own: Option<&'a Arc<CustomPropertyStore>>,
+ pub(in crate::css::style) inherited: Option<&'a Arc<CustomPropertyStore>>,
+ pub(in crate::css::style) substitutions: &'a std::cell::RefCell<SubstitutionCache>,
+ pub(in crate::css::style) subject: &'a dyn SubstitutingSubject,
+}
+
+/// What a substitution reads of the element or pseudo-element it substitutes for,
+/// beyond its custom property stores: the attributes an `attr()` reads, what the conditions of an
+/// `if()` compute against, and the custom functions a call reaches.
+pub(in crate::css::style) trait SubstitutingSubject {
+ /// The element, and the kind of its pseudo-element the substitution is for, if any.
+ fn target(&self) -> (StyleNodeID, Option<u8>);
+
+ /// What the conditions of an `if()` compute against.
+ fn style_query_inputs(&self) -> Option<crate::css::cascaded_properties::StyleQueryInputs>;
+
+ /// The custom functions the element's calls reach, with the declarations their conditions
+ /// select for it.
+ fn custom_functions(&self) -> Option<PreparedCustomFunctions<'_>>;
+
+ /// Resolve the container-relative lengths of `length` against the element's query
+ /// containers.
+ fn apply_container_unit_bases(&self, length: &mut crate::css::style_compute::FfiLengthResolutionContext);
+}
+
+use super::records::HeldCustomProperties;
+
+/// What a drive of an element's longhands found of its registered custom properties.
+pub(in crate::css::style) struct DrivenWithRegisteredProperties {
+ pub(in crate::css::style) computed: super::compute::ComputedElement,
+ /// What `registered_custom_property_store` answered.
+ pub(in crate::css::style) registered: Option<(HeldCustomProperties, bool)>,
+ /// Whether the element's computation read a style of its own it did not hold yet.
+ pub(in crate::css::style) computes_again: bool,
+}
+
+/// Drives an element's longhands until its registered custom properties have settled, and answers
+/// them with the store they computed to, if they did, in place of the one the element substitutes
+/// before they did.
+///
+/// https://drafts.css-houdini.org/css-properties-values-api-1/#calculation-of-computed-values
+/// A registered custom property computes against the element's own lengths, which the drive
+/// settles, so the longhands substitute its value as parsed, which computes the same against the
+/// same lengths. A random function in it draws its base value as it computes, which the longhands
+/// substituting it read: they drive again against the computed values.
+pub(in crate::css::style) fn drive_with_registered_properties<E>(
+ mut drive: impl FnMut(Option<&HeldCustomProperties>) -> Result<DrivenWithRegisteredProperties, E>,
+) -> Result<(super::compute::ComputedElement, Option<HeldCustomProperties>), E> {
+ let mut computed_store = None;
+ loop {
+ let driven = drive(computed_store.as_ref())?;
+ match driven.registered {
+ Some((store, true)) if computed_store.is_none() => computed_store = Some(store),
+ _ if driven.computes_again => {}
+ Some((store, _)) => return Ok((driven.computed, Some(store))),
+ None => return Ok((driven.computed, None)),
+ }
+ }
+}
+
+impl RetainedState {
+ /// The engine: the custom-property store of an element whose custom declarations cascaded to
+ /// `cascaded`, resolved over the store its parent hands down, with `inherit` reading the
+ /// store the parent holds. The parent's store where the element declares nothing new. A
+ /// value of a custom property registered with a syntax stays as parsed, since the element's
+ /// own lengths are not known yet: see `registered_custom_property_store`. A value reading
+ /// `subject` itself, through `attr()`, `if()` or a custom function, makes the store the
+ /// element's alone.
+ pub(in crate::css::style) fn custom_property_store(
+ &self,
+ parent_store: Option<&Arc<CustomPropertyStore>>,
+ parent_held: Option<&Arc<CustomPropertyStore>>,
+ cascaded: &[(CustomDeclaration, RetainedStyleValueData)],
+ stores: &mut StoreCache,
+ subject: &dyn SubstitutingSubject,
+ ) -> Option<Option<Arc<CustomPropertyStore>>> {
+ if cascaded.is_empty() {
+ return Some(parent_store.cloned());
+ }
+ let values = self.declared_custom_properties(parent_store, cascaded)?;
+ if values.is_empty() {
+ return Some(parent_store.cloned());
+ }
+ // A store holding what the element's environment held before gives way to that environment's store, which the
+ // environment is named by.
+ let (node, pseudo) = subject.target();
+ let previous = |store: Option<Arc<CustomPropertyStore>>| {
+ store.map(|store| {
+ self.store_resolving_to_the_same_values(node, pseudo, &store)
+ .unwrap_or(store)
+ })
+ };
+ if cascaded
+ .iter()
+ .any(|(_, value)| value_reads_substitution_subject(value.data()))
+ {
+ let (store, _) = self.resolve_custom_property_store(parent_store, parent_held, values, None, Some(subject));
+ return Some(previous(store));
+ }
+ // What the store resolves to reads nothing of the element but these declarations and the
+ // parent's store, so elements declaring the same values under the same store share one.
+ let key = (
+ parent_store.map_or(0, |store| Arc::as_ptr(store) as usize),
+ parent_held.map_or(0, |store| Arc::as_ptr(store) as usize),
+ values
+ .iter()
+ .map(|(name, important, value)| (*name, *important, *value as usize))
+ .collect::<Vec<_>>(),
+ );
+ if let Some((_, store)) = stores.get(&key) {
+ return Some(previous(store.clone()));
+ }
+ let (resolved, _) = self.resolve_custom_property_store(parent_store, parent_held, values, None, None);
+ stores.insert(key, ([parent_store.cloned(), parent_held.cloned()], resolved.clone()));
+ Some(previous(resolved))
+ }
+
+ /// The engine: the store an element holds once it computed to `computed`, where its custom
+ /// declarations `cascaded` name a custom property registered with a syntax: the store
+ /// `custom_property_store` resolves, with each such value computed against the element's
+ /// own lengths, place among its siblings and color scheme, as its computed value is. What
+ /// those values read joins what `computed` reads. Answers the store with whether its values
+ /// drew random base values, which the element's longhands substituting them read. None where
+ /// they name no such property, and the element holds the store it substituted against.
+ #[allow(clippy::too_many_arguments)]
+ pub(in crate::css::style) fn registered_custom_property_store(
+ &self,
+ node: StyleNodeID,
+ parent_store: Option<&Arc<CustomPropertyStore>>,
+ parent_held: Option<&Arc<CustomPropertyStore>>,
+ cascaded: &[(CustomDeclaration, RetainedStyleValueData)],
+ computed: &mut super::compute::ComputedElement,
+ subject: &dyn SubstitutingSubject,
+ random_requests: &mut Vec<super::random_bases::RandomBaseRequest>,
+ ) -> Option<(Option<Arc<CustomPropertyStore>>, bool)> {
+ let inputs = &self.document_style_computation_inputs;
+ let registry = inputs.custom_property_registry();
+ if !registry.has_registrations()
+ || !cascaded.iter().any(|(declared, _)| {
+ self.declared_custom_property_name(declared.name)
+ .is_some_and(|name| name.with_fly_string(|name| registry.has_syntax(name)))
+ })
+ {
+ return None;
+ }
+ let values = self.declared_custom_properties(parent_store, cascaded)?;
+ if values.is_empty() {
+ return Some((parent_store.cloned(), false));
+ }
+ let tree_counting = self
+ .element_sibling_position(node)
+ .map(|(count, index)| (u64::from(count), u64::from(index)));
+ let color_scheme =
+ u8::try_from(computed.value_facts.effective_color_scheme()).unwrap_or(inputs.preferred_color_scheme);
+ // A container-relative length resolves against the element's query containers, which the
+ // element's own lengths read only where its longhands use one.
+ let mut length = computed.length;
+ subject.apply_container_unit_bases(&mut length);
+ let random_requests = std::cell::RefCell::new(random_requests);
+ let drew_random_base_values = std::cell::Cell::new(false);
+ let (store, reads) = self.resolve_custom_property_store(
+ parent_store,
+ parent_held,
+ values,
+ Some(RegisteredValueContext {
+ length: &length,
+ tree_counting,
+ color_scheme,
+ node,
+ random_requests: &random_requests,
+ drew_random_base_values: &drew_random_base_values,
+ }),
+ cascaded
+ .iter()
+ .any(|(_, value)| value_reads_substitution_subject(value.data()))
+ .then_some(subject),
+ );
+ // A value reading the element's place among its siblings or its containers is the
+ // element's alone.
+ computed.reads.reads_sibling_position |= reads.sibling_position;
+ computed.reads.container_units |= reads.container_unit_mask;
+ computed.reads.reads_root_font = computed.reads.reads_root_font.max(reads.root_font);
+ computed.reads.reads_font_metric_lengths |= reads.font_metrics;
+ if reads.color_scheme {
+ computed.reads.environment_reads |= crate::css::style::input_types::StyleEnvironment::COLOR_SCHEME;
+ }
+ if reads.viewport {
+ computed.reads.environment_reads |= crate::css::style::input_types::StyleEnvironment::VIEWPORT;
+ }
+ computed.element_dependent |= reads.sibling_position || reads.container_unit_mask != 0;
+ // A store holding what the element's environment held before gives way to that environment's store.
+ let (target, pseudo) = subject.target();
+ let store = store.map(|store| {
+ self.store_resolving_to_the_same_values(target, pseudo, &store)
+ .unwrap_or(store)
+ });
+ Some((store, drew_random_base_values.get()))
+ }
+
+ /// The engine: the custom properties `cascaded` declares over the store its element's parent
+ /// hands down, leaving out each value the parent already holds by identity.
+ fn declared_custom_properties(
+ &self,
+ parent_store: Option<&Arc<CustomPropertyStore>>,
+ cascaded: &[(CustomDeclaration, RetainedStyleValueData)],
+ ) -> Option<Vec<DeclaredCustomProperty>> {
+ let parent = parent_store.map(|store| &**store);
+ let mut values = Vec::with_capacity(cascaded.len());
+ for (declared, value) in cascaded {
+ let name = self.declared_custom_property_name(declared.name)?;
+ if parent.is_some_and(|parent| parent.value_is_identical(name.raw(), value.pointer().cast())) {
+ continue;
+ }
+ values.push((name.raw(), declared.important(), value.pointer().cast()));
+ }
+ Some(values)
+ }
+
+ /// Resolve the store of an element declaring `values`, with its registered values computed
+ /// against the element's lengths, place among its siblings and color scheme where `computed`
+ /// gives them, and left as parsed otherwise. Values substituting something of the element
+ /// itself read it from `subject`.
+ fn resolve_custom_property_store(
+ &self,
+ parent_store: Option<&Arc<CustomPropertyStore>>,
+ parent_held: Option<&Arc<CustomPropertyStore>>,
+ values: Vec<DeclaredCustomProperty>,
+ computed: Option<RegisteredValueContext<'_, '_>>,
+ subject: Option<&dyn SubstitutingSubject>,
+ ) -> (
+ Option<Arc<CustomPropertyStore>>,
+ crate::css::custom_properties::RegisteredValueReads,
+ ) {
+ let inputs = &self.document_style_computation_inputs;
+ // https://drafts.csswg.org/css-cascade-5/#inheriting
+ // `inherit` takes the parent's value even of a property that does not inherit.
+ let parent = parent_held.or(parent_store).map(|store| &**store);
+ // SAFETY: The values are the program's and the element's interned values, live for the call.
+ let cascaded_store = unsafe { CustomPropertyStore::cascaded_child(parent_store.cloned(), values) };
+ let registry = inputs.custom_property_registry();
+ let random_function_index = crate::css::parser::value_parser::RandomFunctionIndex::default();
+ let mut parse_context = registry.parse_context(&random_function_index);
+ parse_context.in_quirks_mode = inputs.in_quirks_mode;
+ let media_environment = self.document_media.environment();
+ // https://drafts.csswg.org/css-values-5/#attr-notation
+ // https://drafts.csswg.org/css-values-5/#if-notation
+ // https://drafts.csswg.org/css-mixins/#using-custom-functions
+ let attributes = subject.map(|subject| {
+ let (node, pseudo) = subject.target();
+ SubstitutionAttributes::of(
+ &self.projection,
+ self.substitution_attribute_element(node, pseudo),
+ self.html_element_namespace,
+ )
+ });
+ let style_query = subject.and_then(SubstitutingSubject::style_query_inputs);
+ let functions = subject.and_then(SubstitutingSubject::custom_functions);
+ let mut resolution_context = engine_resolution_context(
+ &parse_context,
+ Some(&cascaded_store),
+ parent,
+ registry,
+ attributes.as_ref(),
+ &media_environment,
+ style_query.as_ref(),
+ functions.as_ref(),
+ );
+ // https://drafts.csswg.org/css-values-5/#random-caching
+ // A random function in a registered value computes against the base value its random
+ // caching key draws once. The keys not drawn yet are drawn between passes, and the
+ // element waits.
+ let draw_random_base_value = |name: &[u16], element_shared: bool| {
+ let Some(context) = &computed else {
+ return 0.0;
+ };
+ context.drew_random_base_values.set(true);
+ self.drawn_random_base_value(context.node, name, element_shared)
+ .unwrap_or_else(|| {
+ context
+ .random_requests
+ .borrow_mut()
+ .push(super::random_bases::RandomBaseRequest {
+ node: context.node,
+ name: name.into(),
+ element_shared,
+ });
+ 0.0
+ })
+ };
+ let finalization = CustomPropertyFinalization {
+ length: computed.as_ref().map(|context| context.length),
+ tree_counting: computed.as_ref().and_then(|context| context.tree_counting),
+ random_base_values: &[],
+ color_scheme: computed.as_ref().map_or(0, |context| context.color_scheme),
+ draw_random_base_value: computed.is_some().then_some(&draw_random_base_value as _),
+ };
+ let (store, reads) = resolve_declared_custom_properties(
+ &cascaded_store,
+ parent_store,
+ parent_store.is_some(),
+ &mut resolution_context,
+ finalization,
+ );
+ (store.or_else(|| parent_store.cloned()), reads)
+ }
+
+ /// The engine: what the children of an element holding `store` inherit, where the element was
+ /// handed `handed_down`: the store without the custom properties a registration keeps from
+ /// inheriting.
+ pub(in crate::css::style) fn inheritable_custom_property_store<'store>(
+ &self,
+ store: Option<&'store Arc<CustomPropertyStore>>,
+ handed_down: Option<&'store Arc<CustomPropertyStore>>,
+ ) -> Option<std::borrow::Cow<'store, Arc<CustomPropertyStore>>> {
+ let store = store?;
+ // A store handed down holds only what inherits.
+ if handed_down.is_some_and(|handed_down| Arc::ptr_eq(handed_down, store)) {
+ return Some(std::borrow::Cow::Borrowed(store));
+ }
+ let registry = self.document_style_computation_inputs.custom_property_registry();
+ if !registry.has_non_inheriting_registrations() {
+ return Some(std::borrow::Cow::Borrowed(store));
+ }
+ let Some(inheritable) = store.inheritable(registry) else {
+ return Some(std::borrow::Cow::Borrowed(store));
+ };
+ // A store whose own values all stay with the element hands down what it was handed, which
+ // keeps one store through a chain of elements declaring only such values.
+ if inheritable.own_values.is_empty() {
+ return handed_down.map(std::borrow::Cow::Borrowed);
+ }
+ Some(std::borrow::Cow::Owned(inheritable))
+ }
+
+ /// The engine: what a written value that waits on substitution substitutes to for `property`,
+ /// against the element's custom-property store and the one it inherits.
+ pub(in crate::css::style) fn substitute_value(
+ &self,
+ stores: CustomPropertyStores<'_>,
+ property: u16,
+ written: &RetainedStyleValueData,
+ ) -> RetainedStyleValueData {
+ // A value reading the element itself substitutes for the element alone.
+ if value_reads_substitution_subject(written.data()) {
+ return self.substitute_for_subject(stores, property, written);
+ }
+ // A substitution reads nothing of the element but its stores, which its descendants
+ // mostly share, so each thread remembers what each value substituted to against them.
+ let key = (
+ std::ptr::from_ref(written.data()) as usize,
+ property,
+ stores.own.map_or(0, |store| Arc::as_ptr(store) as usize),
+ stores.inherited.map_or(0, |store| Arc::as_ptr(store) as usize),
+ );
+ if let Some(entry) = stores.substitutions.borrow().by_stores.get(&key) {
+ return entry.substituted.clone();
+ }
+ // What the value references, where every reference is visible and resolves to a value
+ // whose identity is all there is to it. An `inherit()` reads the inherited store too.
+ let references = (!value_reads_inherited_values(written.data()))
+ .then(|| crate::css::style_value::custom_property_references(written.data()))
+ .flatten()
+ .filter(|(_, all_visible)| *all_visible)
+ .and_then(|(names, _)| {
+ names
+ .iter()
+ .map(|name| {
+ stores.own.map_or(Some(0), |store| {
+ store.resolved_value_identity(&ak::Utf16FlyString::from_utf16(name))
+ })
+ })
+ .collect::<Option<smallvec::SmallVec<[usize; 4]>>>()
+ })
+ .map(|identities| (key.0, property, identities));
+ let found = references
+ .as_ref()
+ .and_then(|references| stores.substitutions.borrow().by_references.get(references).cloned());
+ if let Some(substituted) = found {
+ stores
+ .substitutions
+ .borrow_mut()
+ .insert_by_stores(key, stores, substituted.clone());
+ return substituted;
+ }
+ let substituted = self.substitute_uncached(
+ stores.own.map(Arc::as_ref),
+ stores.inherited.map(Arc::as_ref),
+ property,
+ written,
+ );
+ let mut substitutions = stores.substitutions.borrow_mut();
+ substitutions.insert_by_stores(key, stores, substituted.clone());
+ if let Some(references) = references {
+ substitutions.by_references.insert(references, substituted.clone());
+ }
+ substituted
+ }
+
+ fn substitute_uncached(
+ &self,
+ store: Option<&CustomPropertyStore>,
+ inheritance_store: Option<&CustomPropertyStore>,
+ property: u16,
+ written: &RetainedStyleValueData,
+ ) -> RetainedStyleValueData {
+ let inputs = SubstitutionInputs {
+ document: &self.document_style_computation_inputs,
+ media: &self.document_media,
+ attributes: None,
+ style_query: None,
+ style_query_references: None,
+ functions: None,
+ };
+ substitute_against_stores(store, inheritance_store, &inputs, property, &[], written)
+ }
+
+ /// The engine: what a written value reading the element itself through `attr()`, `if()` or a
+ /// custom function substitutes to for `property`, against the element's stores.
+ fn substitute_for_subject(
+ &self,
+ stores: CustomPropertyStores<'_>,
+ property: u16,
+ written: &RetainedStyleValueData,
+ ) -> RetainedStyleValueData {
+ let (node, pseudo) = stores.subject.target();
+ let functions = value_calls_custom_functions(written.data())
+ .then(|| stores.subject.custom_functions())
+ .flatten();
+ let reads_attributes = value_reads_attributes(written.data())
+ || functions.as_ref().is_some_and(|functions| functions.reads_attributes);
+ let attributes = reads_attributes.then(|| {
+ SubstitutionAttributes::of(
+ &self.projection,
+ self.substitution_attribute_element(node, pseudo),
+ self.html_element_namespace,
+ )
+ });
+ let style_query = (functions.is_some() || value_reads_conditions(written.data()))
+ .then(|| stores.subject.style_query_inputs())
+ .flatten();
+ let inputs = SubstitutionInputs {
+ document: &self.document_style_computation_inputs,
+ media: &self.document_media,
+ attributes: attributes.as_ref(),
+ style_query: style_query.as_ref(),
+ style_query_references: None,
+ functions: functions.as_ref(),
+ };
+ substitute_against_stores(
+ stores.own.map(Arc::as_ref),
+ stores.inherited.map(Arc::as_ref),
+ &inputs,
+ property,
+ &[],
+ written,
+ )
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/declared_only.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/declared_only.rs
new file mode 100644
index 00000000000..dac4c4788a1
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/declared_only.rs
@@ -0,0 +1,193 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The engine for an element no rule reaches, such as one outside the document: the cascade of its
+//! own declarations alone over the initial values, which no pass keeps and no element holds.
+
+use super::super::custom_property_cascade::PreparedCustomFunctions;
+use super::super::*;
+use super::cascade::{Cascade, CascadeBelow, DeclaredOnly};
+use super::custom_properties::{
+ CustomPropertyStores, DrivenWithRegisteredProperties, SubstitutingSubject, SubstitutionCache,
+ drive_with_registered_properties,
+};
+use super::drive::Drive;
+use super::records::Record;
+use std::sync::Arc;
+
+/// What a substitution in the declarations reads of the element: nothing of a tree, as the element
+/// is in none the engine knows, so its conditions compute against no parent and it has no query
+/// containers.
+struct DeclaredOnlySubject<'a> {
+ state: &'a RetainedState,
+ node: StyleNodeID,
+}
+
+impl SubstitutingSubject for DeclaredOnlySubject<'_> {
+ fn target(&self) -> (StyleNodeID, Option<u8>) {
+ (self.node, None)
+ }
+
+ fn style_query_inputs(&self) -> Option<crate::css::cascaded_properties::StyleQueryInputs> {
+ self.state.style_query_inputs_of(None, self.node)
+ }
+
+ fn custom_functions(&self) -> Option<PreparedCustomFunctions<'_>> {
+ self.state
+ .prepare_custom_functions(&self.state.document_functions, self.node, None)
+ }
+
+ fn apply_container_unit_bases(&self, _length: &mut crate::css::style_compute::FfiLengthResolutionContext) {}
+}
+
+impl StyleEngine {
+ /// The record of an element no rule reaches, such as one outside the document: the cascade of
+ /// its own declarations `declared` alone, in cascade order, over the initial values, with no
+ /// parent. The computation is keyed by `subject`, the document's style node, which names no
+ /// parent and no siblings. No element holds the record, which no slot takes either: the caller
+ /// holds it.
+ pub(in super::super) fn declared_only_record(
+ &mut self,
+ subject: StyleNodeID,
+ declared: DeclaredOnly,
+ ) -> Drive<Arc<Record>> {
+ let live = self
+ .retained
+ .live_style
+ .take()
+ .expect("the style engine answers every row");
+ let cascade = Cascade::of_declared_only(&self.retained, &live.index, subject, declared);
+ let answer = self.until_resolved(subject, |engine| {
+ let mut waits = super::Waits::default();
+ let computed = engine.retained.compute_declared_only(
+ &live,
+ &cascade,
+ subject,
+ &mut waits.fonts,
+ &mut waits.random_bases,
+ );
+ match waits.fonts.is_empty() && waits.random_bases.is_empty() {
+ true => Ok(computed),
+ false => Err(waits),
+ }
+ });
+ self.retained.live_style = Some(live);
+ let record = answer.expect("the style engine answers every row")?;
+ let custom_property_environment =
+ self.retained
+ .record_environment(subject, &record, None, 0, &mut HashMap::default());
+ let record = self
+ .retained
+ .record_in_environment(&record, custom_property_environment)
+ .into_owned();
+ record.settle_view_dependency_flags(computed::record_dependency_flags(&record.facts(), &record.payloads));
+ Ok(record)
+ }
+}
+
+impl RetainedState {
+ /// The record [`StyleEngine::declared_only_record`] computes from `cascade`, or why there is
+ /// none yet: the fonts and random base values it waits on are added to `font_requests` and
+ /// `random_requests`.
+ fn compute_declared_only(
+ &self,
+ live: &super::Live,
+ cascade: &Cascade,
+ node: StyleNodeID,
+ font_requests: &mut Vec<font_resolution::FontRequest>,
+ random_requests: &mut Vec<super::super::random_bases::RandomBaseRequest>,
+ ) -> Drive<Arc<Record>> {
+ let initial = &live.initial;
+ let subject = DeclaredOnlySubject { state: self, node };
+ let substitutions = std::cell::RefCell::new(SubstitutionCache::default());
+ let custom_properties = self
+ .custom_property_store(None, None, &cascade.custom_winners, &mut HashMap::default(), &subject)
+ .expect("the style engine answers every row");
+ let mut groups = super::compute::GroupCache::default();
+ let mut absolutized = crate::css::style_compute::AbsolutizedValues::default();
+ let (computed, registered) = drive_with_registered_properties(|computed_store| {
+ let mut suspended_font = None;
+ let substituted = computed_store.unwrap_or(&custom_properties);
+ let driven = self.drive_element(
+ self,
+ node,
+ None,
+ initial,
+ &cascade.winners,
+ &CascadeBelow {
+ cascade,
+ state: self,
+ node,
+ },
+ &mut suspended_font,
+ random_requests,
+ CustomPropertyStores {
+ own: substituted.as_ref(),
+ inherited: None,
+ substitutions: &substitutions,
+ subject: &subject,
+ },
+ &mut groups,
+ &mut absolutized,
+ u8::MAX,
+ None,
+ initial.group_seeds(None),
+ );
+ font_requests.extend(suspended_font);
+ let mut computed = driven?;
+ let registered = self.registered_custom_property_store(
+ node,
+ None,
+ None,
+ &cascade.custom_winners,
+ &mut computed,
+ &subject,
+ random_requests,
+ );
+ // NB: Where base values of random functions are still to be drawn, the caller draws them and asks again.
+ Ok(DrivenWithRegisteredProperties {
+ computed,
+ registered,
+ computes_again: false,
+ })
+ })?;
+ let custom_properties = registered.unwrap_or(custom_properties);
+ let value_of = |property| computed.groups.value(property);
+ let counter_style_environment_identity = self.values_counter_style_environment_identity(
+ computed::ComputedStyleTarget::new(node, u8::MAX),
+ |property| {
+ computed
+ .value_facts
+ .value_read_in_place(property)
+ .unwrap_or_else(|| value_of(property))
+ },
+ );
+ let table_flags = Arc::new(computed.flags);
+ Ok(Arc::new(Record {
+ header: super::records::RecordHeader::new(computed.facts),
+ payloads: computed
+ .groups
+ .adopt_sharing(&[Some(&initial.payloads)])
+ .with_rare_facts(
+ Arc::new(super::records::RareStyleFacts::of_computation(
+ super::records::InheritableCustomProperties::of(
+ custom_properties.as_ref(),
+ self.inheritable_custom_property_store(custom_properties.as_ref(), None),
+ ),
+ counter_style_environment_identity,
+ table_flags,
+ computed.value_facts,
+ computed.custom_property_reads,
+ computed.reads,
+ cascade.animation_name_scope,
+ )),
+ (!cascade.custom_winners.is_empty()).then(|| cascade.custom_winners.as_slice().into()),
+ &[],
+ )
+ .with_custom_properties(custom_properties.as_ref()),
+ }))
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/publication/drive.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/drive.rs
similarity index 52%
rename from Libraries/LibWeb/Rust/src/css/style/publication/drive.rs
rename to Libraries/LibWeb/Rust/src/css/style/pipeline/drive.rs
index 5e2b6623c2d..7e1712c870e 100644
--- a/Libraries/LibWeb/Rust/src/css/style/publication/drive.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/drive.rs
@@ -4,21 +4,44 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-use super::*;
+use super::super::publication::pseudo_kind;
+use super::super::*;
+use super::compute::DriveSubject;
+use super::winner_store::WinnerStore;
use crate::css::cascaded_properties::CascadedValues;
+use crate::css::computed_longhand_table::FONT_METRICS_DEPEND_ON_VIEWPORT_METRICS;
+use crate::css::computed_values::GroupValuesWriter;
+
+/// Where a drive reads the records of the elements it computes against: its inheritance parent's,
+/// and its ancestors' for the box-type transformation and the monospace font-size recascade.
+pub(in crate::css::style) trait DriveRecords:
+ super::super::container_queries::ContainerRecords
+{
+ fn assigned_record_view(&self, node: StyleNodeID) -> Option<computed::StyleRecordView<'_>>;
+
+ /// The record the highlight pseudo-element of `kind` of `node` inherits from: that of the same
+ /// pseudo-element of its nearest flat-tree ancestor holding one.
+ fn highlight_inheritance_parent_view(&self, node: StyleNodeID, kind: u8) -> Option<computed::StyleRecordView<'_>>;
+}
+
+impl DriveRecords for RetainedState {
+ fn assigned_record_view(&self, node: StyleNodeID) -> Option<computed::StyleRecordView<'_>> {
+ self.computed_group_sets
+ .assigned_style_record(node)
+ .and_then(|record| self.computed_group_sets.style_record_view(record.raw()))
+ }
-#[derive(Clone, Copy, PartialEq, Eq)]
-pub(super) enum FontDriveGoal {
- Complete,
- RootInputs,
+ fn highlight_inheritance_parent_view(&self, node: StyleNodeID, kind: u8) -> Option<computed::StyleRecordView<'_>> {
+ self.retained_highlight_inheritance_parent_style_record(node, kind)
+ .and_then(|record| self.computed_group_sets.style_record_view(record.raw()))
+ }
}
-/// Why a row has no record. A suspended row is not refused: it waits on a request the host
+/// Why a row has no record yet. A suspended row waits on a request the host
/// services between passes, and the same row resumes once that request is answered.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::css::style) enum Unanswered {
Suspended(Suspension),
- Refused,
/// The row inherits from a parent that holds no record yet: one the host styles in the same
/// update. The style pass settles the row in its next wave, once the host installed the rows
/// before it.
@@ -30,13 +53,15 @@ pub(in crate::css::style) enum Unanswered {
pub(in crate::css::style) enum Suspension {
/// The drive's font is not resolved yet; `FontDriveScratch::request` names it.
Font,
+ /// A random function's base value is not drawn yet; the drive named its random caching key.
+ RandomBaseValues,
}
/// A row's answer from the engine, or why there is none.
pub(in crate::css::style) type Drive<T> = Result<T, Unanswered>;
/// What the monospace font-size recascade answers for a drive target.
-pub(super) enum MonospaceRecascade {
+pub(in crate::css::style) enum MonospaceRecascade {
/// The font size the recascade reaches, and whether reaching it read the viewport.
Size(i32, bool),
/// A length in the ancestor chain resolves against the monospace font at the size reached so
@@ -44,54 +69,12 @@ pub(super) enum MonospaceRecascade {
AwaitsFont(bridge::FfiFontResolutionRequest),
}
-/// A missing value on the way to a record is the engine declining the row.
-pub(in crate::css::style) trait OrRefused<T> {
- fn or_refused(self) -> Drive<T>;
-}
-
-impl<T> OrRefused<T> for Option<T> {
- fn or_refused(self) -> Drive<T> {
- self.ok_or(Unanswered::Refused)
- }
-}
-
-/// A driven longhand table with the length context it was driven against, the longhand
-/// evaluations it took, the font a full drive resolved, and the non-inherited style groups it read
-/// straight from the parent through an explicit `inherit`, which C++ marks the parent with.
-pub(super) struct DrivenTable {
- pub(super) table: ComputedLonghandTable,
- pub(super) length: crate::css::style_compute::FfiLengthResolutionContext,
- pub(super) longhand_evaluations: u32,
- pub(super) font: Option<crate::css::table_group_builder::FfiFontGroupBuildInputs>,
- pub(super) explicitly_inherited_groups: u32,
-}
-
-/// What a partial drive answers besides a refusal.
-#[expect(
- clippy::large_enum_variant,
- reason = "the driven table moves by value, as it did in an `Option`"
-)]
-pub(super) enum PartialDrive {
- Driven(DrivenTable),
- /// An input the drive reads for properties it did not select moved with the selection, or the
- /// old record holds no table to copy them from: the caller drives the record in full instead.
- DriverInputMoved,
-}
-
-/// What a full drive answers besides a refusal or a suspension.
-#[expect(
- clippy::large_enum_variant,
- reason = "the driven table moves by value, as it did in an `Option`"
-)]
-pub(super) enum FullDrive {
- Driven(DrivenTable),
- /// The root-input probe finished the font and line-height phases; the drive is left pending
- /// for the root's own row.
- RootInputs(RootFontInputs),
- /// The drive settled the element's font and color scheme, which the registered custom
- /// properties it declares compute against; it is left pending until the caller resolves them
- /// against this context, substitutes its winners again, and drives once more without waiting.
- AwaitsRegisteredContext(custom_property_cascade::RegisteredValueContext),
+/// Driven values, with the length context they were driven against and the font a full drive
+/// resolved.
+pub(in crate::css::style) struct DrivenValues<'a> {
+ pub(in crate::css::style) writer: GroupValuesWriter<'a>,
+ pub(in crate::css::style) length: crate::css::style_compute::FfiLengthResolutionContext,
+ pub(in crate::css::style) font: Option<crate::css::table_group_builder::FfiFontGroupBuildInputs>,
}
#[derive(Clone, Default)]
@@ -114,15 +97,6 @@ impl FontDriveScratch {
Unanswered::Suspended(Suspension::Font)
}
- /// Whether the suspended drive belongs to this node's row, for the element itself or one of
- /// its pseudo-elements. A row resumes only its own drive: the one left behind by an element
- /// the record loop settled another way is not an answer to it.
- pub(in crate::css::style) fn is_pending_for(&self, node: StyleNodeID) -> bool {
- self.pending
- .as_ref()
- .is_some_and(|pending| pending.target.node() == node)
- }
-
/// The font request a drive suspended on.
pub(in crate::css::style) fn take_suspended_request(&mut self) -> font_resolution::FontRequest {
self.request
@@ -131,29 +105,6 @@ impl FontDriveScratch {
}
}
-/// An element's record, computed while one of its pseudo-elements waits for a font, held for the
-/// element's own row to resume. Its fields are private to the drive, so the record can only be
-/// taken back by naming the node it was computed for.
-#[derive(Clone)]
-pub(super) struct PendingElement {
- node: StyleNodeID,
- delta: RecordDelta,
-}
-
-impl PendingElement {
- pub(super) fn new(node: StyleNodeID, delta: RecordDelta) -> Self {
- Self { node, delta }
- }
-
- /// The record parked for `node`'s row. A row never takes up another's: the flush loop resumes
- /// a suspended row before it drives the next one.
- pub(super) fn take_for(slot: &mut Option<Self>, node: StyleNodeID) -> Option<RecordDelta> {
- let pending = slot.take()?;
- debug_assert!(pending.node == node, "a row resumed another row's pending element");
- (pending.node == node).then_some(pending.delta)
- }
-}
-
/// A drive left for its target's retry. No parent/context borrow survives refill; the caller
/// resumes the same subject before evaluating any later canonical element.
#[derive(Clone)]
@@ -167,78 +118,67 @@ struct PendingFontDrive {
progress: Option<DriveProgress>,
}
-/// The completed font phase owns its table.
+/// The completed font phase owns its values, holding a reference to each group they were seeded
+/// from.
#[derive(Clone)]
struct DriveProgress {
root_font_complete: bool,
/// Whether the color-scheme phase ran too, as it has for a drive awaiting its registered
/// context.
color_scheme_complete: bool,
- /// The monospace recascade's size the table already holds, which the remaining phases read.
+ /// The monospace recascade's size the values already hold, which the remaining phases read.
recascaded_font_size: Option<i32>,
- table: ComputedLonghandTable,
- results: crate::css::style_compute::FfiLonghandDriverResults,
+ writer: GroupValuesWriter<'static>,
+ results: crate::css::style_compute::LonghandDriverResults,
effective_color_scheme: i16,
resolved_viewport_relative_length: bool,
}
impl RetainedState {
- /// The font size the monospace recascade gives a drive target: the cascaded font-size of every
- /// ancestor it inherits from, root first, walked again from a 13px default. A pseudo-element
- /// inherits from its originating element. A length the walk cannot resolve from the document's
- /// inputs alone resolves against the monospace font at the size reached so far, the line
- /// height its ancestor inherits and the ancestor's query containers; a `calc()` is skipped as
- /// C++ skips it. `None` where a length still does not resolve, which it should not.
- pub(super) fn monospace_recascaded_font_size(
+ fn monospace_recascaded_font_size_with(
&self,
+ records: &impl DriveRecords,
target: computed::ComputedStyleTarget,
inputs: &bridge::FfiDocumentStyleComputationInputs,
) -> Option<MonospaceRecascade> {
- use crate::css::computed_value_types::{STYLE_GROUP_INDEX_FONT, STYLE_GROUP_INDEX_INHERITED_BOX};
use crate::css::css_pixels::CssPixels;
use crate::css::style_compute::{
- FfiFontMetrics, FfiFontSizeRecascadeDocumentInputs, FfiLengthResolutionContext, FontSizeRecascadeStatus,
+ FfiFontMetrics, FfiLengthResolutionContext, FontSizeRecascadeDocumentInputs, FontSizeRecascadeStatus,
recascade_font_size_batch,
};
+ use crate::css::table_group_builder::group_index;
let mut views = Vec::new();
let mut ancestor = match target.is_pseudo() {
true => Some(target.node()),
- false => self.tree.inheritance_parent(target.node()),
+ false => self.projection.inheritance_parent(target.node()),
};
while let Some(node) = ancestor {
- views.push((
- node,
- self.computed_group_sets
- .assigned_style_record(node)
- .and_then(|record| self.computed_group_sets.style_record_view(record.raw())),
- ));
- ancestor = self.tree.inheritance_parent(node);
+ views.push((node, records.assigned_record_view(node)));
+ ancestor = self.projection.inheritance_parent(node);
}
views.reverse();
let mut inherited_zoom = 1.0;
let zooms: Vec<_> = views
.iter()
.map(|(_, view)| {
- if let Some(table) = view.as_ref().and_then(|view| view.longhand_table) {
- inherited_zoom = f64::from(table.effective_zoom());
+ if let Some(view) = view {
+ inherited_zoom = f64::from(view.longhands().effective_zoom());
}
inherited_zoom
})
.collect();
let applies_zoom_at = |index: usize| {
- self.computed_group_sets.adjustment_facts(views[index].0) & bridge::element_adjustment_fact::IS_SVG_ELEMENT
- == 0
+ self.projection.adjustment_facts(views[index].0) & bridge::element_adjustment_fact::IS_SVG_ELEMENT == 0
};
let value_at = |index: usize| {
views[index]
.1
.as_ref()
- .and_then(|view| view.longhand_table)
- .and_then(ComputedLonghandTable::raw_cascaded_font_size_value)
+ .and_then(|view| view.longhands().raw_cascaded_font_size())
};
let default_size = CssPixels::from_integer(13).raw_value();
- let document_inputs = FfiFontSizeRecascadeDocumentInputs::from_document(inputs);
+ let document_inputs = FontSizeRecascadeDocumentInputs::from_document(inputs);
let mut batch = recascade_font_size_batch(
views.len(),
value_at,
@@ -296,23 +236,18 @@ impl RetainedState {
.and_then(|parent| views[parent].1.as_ref())
.map_or((inputs.initial_line_height, false), |view| {
let font = unsafe {
- view.payloads[STYLE_GROUP_INDEX_FONT]
+ view.payloads[group_index::FONT]
.cast::<crate::css::computed_value_types::FontValues>()
.deref()
};
(
- font.line_height_used.to_double() * own_zoom,
+ font.line_height_used().to_double() * own_zoom,
view.dependency_flags & FONT_METRICS_DEPEND_ON_VIEWPORT_METRICS != 0,
)
});
let (ancestor_node, ancestor_view) = &views[index];
let subject_inline_axis_is_horizontal = ancestor_view.as_ref().is_none_or(|view| {
- let inherited_box = unsafe {
- view.payloads[STYLE_GROUP_INDEX_INHERITED_BOX]
- .cast::<crate::css::computed_values::InheritedBoxValues>()
- .deref()
- };
- inherited_box.writing_mode == crate::css::css_enums::writing_mode::HORIZONTAL_TB
+ view.payloads.inherited_bits().writing_mode() == crate::css::css_enums::writing_mode::HORIZONTAL_TB
});
let mut context = FfiLengthResolutionContext {
viewport_width: inputs.viewport_width,
@@ -345,7 +280,8 @@ impl RetainedState {
zoom: if applies_zoom { zoom } else { 1.0 },
};
// The ancestor's container-relative font size resolves against its own containers.
- self.container_unit_bases(*ancestor_node, false).apply_to(&mut context);
+ self.container_unit_bases_with(records, *ancestor_node, false)
+ .apply_to(&mut context);
batch = recascade_font_size_batch(
views.len(),
value_at,
@@ -378,246 +314,16 @@ impl RetainedState {
.font_resolution
.as_ref()
.map_or(&[][..], |resolutions| resolutions.feature_values_shadow_scopes());
- let mut scope = self.tree.tree_scope(node);
+ let mut scope = self.projection.tree_scope(node);
while scope != TreeScopeID::DOCUMENT && !declaring.contains(&scope) {
- let Some(host) = self.scope_root(scope).and_then(|root| self.tree.host_of(root)) else {
+ let Some(host) = self.scope_root(scope).and_then(|root| self.projection.host_of(root)) else {
return TreeScopeID::DOCUMENT;
};
- scope = self.tree.tree_scope(host);
+ scope = self.projection.tree_scope(host);
}
scope
}
- /// Run the drive's remaining phase for the selected longhands over a copy of the node's
- /// current table, against the record's own font metrics, the document's computation inputs
- /// and the parent's record. The required driver inputs recompute on every drive and their
- /// post-compute adjustments read element facts this context does not carry, so the table
- /// stands only when they came out exactly as before.
- #[allow(clippy::too_many_arguments)]
- pub(super) fn engine_driven_table(
- &self,
- node: StyleNodeID,
- old_style_record: computed::FinalStyleRecordID,
- store: &WinnerStore,
- selected: &[u64],
- inputs: &bridge::FfiDocumentStyleComputationInputs,
- ) -> Drive<PartialDrive> {
- let random_base_values = store
- .drive_random_base_values(self, node)
- .or_refused()
- .inspect_err(|_| self.counters.bump(Counter::EngineComputedRecordBailValue))?;
- let resource_contexts = store.drive_resource_contexts(self);
- let reads_container_units = store.reads_container_units(self);
- let document_base_url = &self.document_resource_contexts.document_base_url;
- let store = store.view(self);
- use crate::css::computed_value_types::{STYLE_GROUP_INDEX_FONT, STYLE_GROUP_INDEX_INHERITED_BOX};
- use crate::css::style_compute::{
- FfiEffectiveColorSchemeInput, FfiFontMetrics, FfiLengthResolutionContext, FfiStyleComputationEnvironment,
- LONGHAND_DRIVE_PHASE_REMAINING, drive_property_computation, empty_longhand_driver_results,
- is_required_driver_input, parent_snapshot_for_style_record, property_computation_order_for_phase,
- };
-
- // The record being driven again has a view. Without one, what the selection leaves standing
- // is unknown: the caller drives in full.
- let Some(view) = self.computed_group_sets.style_record_view(old_style_record.raw()) else {
- debug_assert!(false, "the record being driven again has a view");
- return Ok(PartialDrive::DriverInputMoved);
- };
- if view.animated_overlay.is_some() {
- self.counters.bump(Counter::EngineComputedRecordBailRecordOverlay);
- return Err(Unanswered::Refused);
- }
- // A record holding no table has no slots to copy the unselected properties from, and one
- // under display:none may have kept values its moved ancestors no longer pass on: the caller
- // drives either in full.
- let Some(old_table) = (view.longhand_table).filter(|_| view.dependency_flags & IN_DISPLAY_NONE_SUBTREE == 0)
- else {
- return Ok(PartialDrive::DriverInputMoved);
- };
- let parent = self
- .record_inheritance_parent(node)
- .inspect_err(|_| self.counters.bump(Counter::EngineComputedRecordBailRecordParent))?;
- let snapshot = match parent.and_then(|parent| self.computed_group_sets.assigned_style_record(parent)) {
- None => None,
- Some(record) => {
- let Some(view) = self.computed_group_sets.style_record_view(record.raw()) else {
- debug_assert!(false, "an assigned parent record has a view");
- self.counters.bump(Counter::EngineComputedRecordBailRecordParent);
- return Err(Unanswered::Refused);
- };
- // A child inherits what the parent's animations sampled over its record.
- Some(parent_snapshot_for_style_record(
- self,
- record.raw(),
- view.animated_overlay,
- ))
- }
- };
- let font = unsafe {
- view.payloads[STYLE_GROUP_INDEX_FONT]
- .cast::<crate::css::computed_value_types::FontValues>()
- .deref()
- };
- let inherited_box = unsafe {
- view.payloads[STYLE_GROUP_INDEX_INHERITED_BOX]
- .cast::<crate::css::computed_values::InheritedBoxValues>()
- .deref()
- };
- let mut resolved_viewport_relative_length = false;
- let mut length = FfiLengthResolutionContext {
- viewport_width: inputs.viewport_width,
- viewport_height: inputs.viewport_height,
- font_metrics: FfiFontMetrics {
- font_size: font.font_size.to_double(),
- x_height: drive_font_metric(font.font_x_height),
- // The C++ metrics approximate the cap height with the ascent.
- cap_height: drive_font_metric(font.font_ascent),
- zero_advance: drive_font_metric(font.font_zero_advance),
- line_height: font.line_height_used.to_double(),
- },
- root_font_metrics: FfiFontMetrics {
- font_size: inputs.root_font_size,
- x_height: inputs.root_font_x_height,
- cap_height: inputs.root_font_cap_height,
- zero_advance: inputs.root_font_zero_advance,
- line_height: inputs.root_line_height,
- },
- font_metrics_depend_on_viewport_metrics: view.dependency_flags & FONT_METRICS_DEPEND_ON_VIEWPORT_METRICS
- != 0,
- root_font_metrics_depend_on_viewport_metrics: inputs.root_font_metrics_depend_on_viewport_metrics,
- has_container_width_basis: false,
- has_container_height_basis: false,
- container_width_basis: 0.0,
- container_height_basis: 0.0,
- container_width_basis_depends_on_viewport_metrics: false,
- container_height_basis_depends_on_viewport_metrics: false,
- subject_inline_axis_is_horizontal: inherited_box.writing_mode
- == crate::css::css_enums::writing_mode::HORIZONTAL_TB,
- resolved_viewport_relative_length: &raw mut resolved_viewport_relative_length,
- zoom: 1.0,
- };
- if reads_container_units {
- self.container_unit_bases(node, false).apply_to(&mut length);
- }
- // NB: Remaining-phase computation uses the current box-type inputs and compares its
- // required driver outputs with the retained record below. Font-phase and line-height
- // changes still take the full path.
- let sibling_position = self.sibling_position(node);
- let environment = FfiStyleComputationEnvironment {
- box_type_input: self.box_type_transformation_input(
- self.computed_group_sets.adjustment_facts(node),
- crate::css::style_compute::FfiStyleAdjustmentTarget::Element,
- parent,
- ),
- color_scheme_input: FfiEffectiveColorSchemeInput {
- preferred_color_scheme: 0,
- has_document_supported_schemes: false,
- document_supported_scheme_codes: std::ptr::null(),
- document_supported_scheme_count: 0,
- },
- is_th_element: false,
- has_new_font_size: false,
- has_tree_counting_context: sibling_position.is_some(),
- sibling_count: sibling_position.map_or(0, |position| u64::from(position.count)),
- sibling_index: sibling_position.map_or(0, |position| u64::from(position.index)),
- random_base_values: random_base_values.as_ptr(),
- random_base_value_count: random_base_values.len(),
- document_base_url: document_base_url.as_ptr(),
- document_base_url_length: document_base_url.len(),
- style_sheet_resource_contexts: resource_contexts.as_ptr(),
- style_sheet_resource_context_count: resource_contexts.len(),
- device_pixels_per_css_pixel: inputs.device_pixels_per_css_pixel,
- initial_font_size_raw: inputs.initial_font_size_raw,
- default_font_size_raw: inputs.default_font_size_raw,
- root_effective_zoom: inputs.root_effective_zoom,
- };
- let mut table = view.longhand_table_for_partial_drive();
- let mut results = empty_longhand_driver_results();
- let mut effective_color_scheme = old_table.effective_color_scheme();
- let input_line_height_metrics = crate::css::style_compute::FfiInputLineHeightMetrics {
- current_line_height: 0.0,
- minimum_line_height: 0.0,
- };
- unsafe {
- drive_property_computation(
- &mut table,
- &store,
- snapshot.as_ref(),
- None,
- &environment,
- Some(selected),
- LONGHAND_DRIVE_PHASE_REMAINING,
- Some(&length),
- Some(&input_line_height_metrics),
- &mut results,
- &mut effective_color_scheme,
- true,
- );
- }
- self.counters.bump(Counter::EnginePartialDrivesStarted);
-
- self.counters.add(
- Counter::EnginePhysicalLonghandEvaluations,
- u64::from(results.longhand_evaluations),
- );
- self.counters.add(
- Counter::EnginePartialLonghandEvaluations,
- u64::from(results.longhand_evaluations),
- );
- // A tree-counting value is admitted only where the retained tree places the element.
- if results.uses_tree_counting_function && sibling_position.is_none() {
- self.counters.bump(Counter::EngineComputedRecordBailDrive);
- return Err(Unanswered::Refused);
- }
- // An input the drive reads for properties it did not select moved with the selection: the
- // caller drives the record in full instead.
- if results.post_adjusted_longhands & crate::css::style_compute::POST_ADJUSTED_LINE_HEIGHT != 0
- || table.display_before_box_type_transformation() != old_table.display_before_box_type_transformation()
- {
- return Ok(PartialDrive::DriverInputMoved);
- }
- let old_values = old_table.value_pointers();
- for &property in property_computation_order_for_phase(LONGHAND_DRIVE_PHASE_REMAINING) {
- if !is_required_driver_input(property) {
- continue;
- }
- let slot = usize::from(property - crate::css::property_metadata::FIRST_LONGHAND_PROPERTY_ID);
- let old_value = old_values[slot];
- let new_value = table
- .get(property)
- .map_or(std::ptr::null(), |value| value.pointer().cast());
- if old_value == new_value {
- continue;
- }
- let equal = unsafe {
- match (
- old_value.cast::<StyleValueData>().as_ref(),
- new_value.cast::<StyleValueData>().as_ref(),
- ) {
- (Some(old_value), Some(new_value)) => old_value == new_value,
- _ => false,
- }
- };
- if !equal {
- return Ok(PartialDrive::DriverInputMoved);
- }
- table.copy_slot_from(old_table, property);
- }
- // The group builders resolve against the same context; they report no viewport dependence
- // of their own.
- let length = FfiLengthResolutionContext {
- resolved_viewport_relative_length: std::ptr::null_mut(),
- ..length
- };
- Ok(PartialDrive::Driven(DrivenTable {
- table,
- length,
- longhand_evaluations: results.longhand_evaluations,
- font: None,
- explicitly_inherited_groups: results.explicitly_inherited_non_inherited_style_groups,
- }))
- }
-
/// What the box-type transformation of a style reads besides its own display, position and
/// float: the facts the host published for the element and the display of `parent`, the
/// element it inherits from, past any display:contents ancestor, as its record composes it.
@@ -626,26 +332,35 @@ impl RetainedState {
pub(in crate::css::style) fn box_type_transformation_input(
&self,
facts: u32,
- target: crate::css::style_compute::FfiStyleAdjustmentTarget,
+ target: crate::css::style_compute::StyleAdjustmentTarget,
parent: Option<StyleNodeID>,
) -> crate::css::style_compute::FfiBoxTypeTransformationInput {
- use crate::css::style_compute::effective_display;
+ self.box_type_transformation_input_with(self, facts, target, parent)
+ }
+ pub(in crate::css::style) fn box_type_transformation_input_with(
+ &self,
+ records: &impl DriveRecords,
+ facts: u32,
+ target: crate::css::style_compute::StyleAdjustmentTarget,
+ parent: Option<StyleNodeID>,
+ ) -> crate::css::style_compute::FfiBoxTypeTransformationInput {
let mut parent_display = None;
let mut parent_writing_mode = crate::css::css_enums::writing_mode::HORIZONTAL_TB;
let mut ancestor = parent;
- while let Some(current) = ancestor
- && let Some(record) = self.computed_group_sets.assigned_style_record(current)
- && let Some(view) = self.computed_group_sets.style_record_view(record.raw())
- && let Some(table) = view.longhand_table
- {
- let display = effective_display(table, view.animated_overlay);
+ while let Some(current) = ancestor {
+ let Some(view) = records.assigned_record_view(current) else {
+ break;
+ };
+ let longhands = view.longhands();
+ let display = longhands.effective_display(view.animated_overlay);
+ let writing_mode = longhands.effective_writing_mode(view.animated_overlay);
if !display.is_contents() {
parent_display = Some(display);
- parent_writing_mode = crate::css::style_compute::effective_writing_mode(table, view.animated_overlay);
+ parent_writing_mode = writing_mode;
break;
}
- ancestor = self.tree.inheritance_parent(current);
+ ancestor = self.projection.inheritance_parent(current);
}
crate::css::style_compute::rust_box_type_transformation_input(
facts,
@@ -663,17 +378,17 @@ impl RetainedState {
node: StyleNodeID,
pseudo_kind: u8,
) -> crate::css::style_compute::FfiBoxTypeTransformationInput {
- use crate::css::style_compute::FfiStyleAdjustmentTarget;
+ use crate::css::style_compute::StyleAdjustmentTarget;
- let facts = self.computed_group_sets.adjustment_facts(node);
+ let facts = self.projection.adjustment_facts(node);
if pseudo_kind == crate::css::cascaded_properties::NO_PSEUDO_ELEMENT {
self.box_type_transformation_input(
facts,
- FfiStyleAdjustmentTarget::Element,
- self.tree.inheritance_parent(node),
+ StyleAdjustmentTarget::Element,
+ self.projection.inheritance_parent(node),
)
} else {
- self.box_type_transformation_input(facts, FfiStyleAdjustmentTarget::PseudoElement, Some(node))
+ self.box_type_transformation_input(facts, StyleAdjustmentTarget::PseudoElement, Some(node))
}
}
@@ -681,33 +396,43 @@ impl RetainedState {
/// element's font resolved through the document's resolver, line-height and color-scheme
/// against that font, and the remaining phase with the element facts the box-type
/// transformation reads. Root-input preparation finishes only the font and line-height
- /// phases and preserves them for completion, and a drive with an `initial_registered_context`
- /// may stop after the color-scheme phase with the context the registered custom properties it
- /// declares compute against, which it preserves likewise. Monospace default-size recascade
- /// stays in C++.
+ /// phases and preserves them for completion.
+ #[allow(clippy::too_many_arguments, clippy::too_many_lines)]
+ pub(in crate::css::style) fn engine_full_drive<'a>(
+ &self,
+ subject: DriveSubject,
+ writer: GroupValuesWriter<'a>,
+ store: &WinnerStore,
+ inputs: &bridge::FfiDocumentStyleComputationInputs,
+ font_scratch: &mut FontDriveScratch,
+ ) -> Drive<DrivenValues<'a>> {
+ self.engine_drive_with(self, subject, writer, None, store, inputs, font_scratch)
+ }
+
+ /// Drive a record as [`Self::engine_full_drive`] does, into `writer`, reading the records it
+ /// computes against from `records`. With a `selected` set of longhands, the drive evaluates
+ /// only those, beside the inputs every drive evaluates, and keeps the writer's values for the
+ /// rest.
#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
- pub(super) fn engine_full_drive(
+ pub(in crate::css::style) fn engine_drive_with<'a>(
&self,
+ records: &impl DriveRecords,
subject: DriveSubject,
- old_style_record: Option<computed::FinalStyleRecordID>,
+ writer: GroupValuesWriter<'a>,
+ selected: Option<&[u64]>,
store: &WinnerStore,
inputs: &bridge::FfiDocumentStyleComputationInputs,
font_scratch: &mut FontDriveScratch,
- goal: FontDriveGoal,
- initial_registered_context: Option<&custom_property_cascade::RegisteredValueContext>,
- ) -> Drive<FullDrive> {
+ ) -> Drive<DrivenValues<'a>> {
let random_base_values = store
.drive_random_base_values(self, subject.target.node())
- .or_refused()
- .inspect_err(|_| self.counters.bump(Counter::EngineComputedRecordBailValue))?;
+ .expect("a random function's base values are drawn before the row is driven");
let resource_contexts = store.drive_resource_contexts(self);
// NB: Include the originating element when selecting a pseudo-element's query containers.
- let container_unit_bases = store
- .reads_container_units(self)
- .then(|| self.container_unit_bases(subject.target.node(), subject.target.is_pseudo()));
+ let container_unit_bases = (store.container_unit_mask(self) != 0)
+ .then(|| self.container_unit_bases_with(records, subject.target.node(), subject.target.is_pseudo()));
let document_base_url = &self.document_resource_contexts.document_base_url;
let store = store.view(self);
- use crate::css::computed_value_types::{STYLE_GROUP_INDEX_FONT, STYLE_GROUP_INDEX_INHERITED_BOX};
use crate::css::css_pixels::CssPixels;
use crate::css::property_metadata::property_id as prop;
use crate::css::style_compute::{
@@ -716,19 +441,15 @@ impl RetainedState {
LONGHAND_DRIVE_PHASE_LINE_HEIGHT, LONGHAND_DRIVE_PHASE_REMAINING, drive_property_computation,
empty_longhand_driver_results, font_family_is_monospace,
};
+ use crate::css::table_group_builder::group_index;
use bridge::element_adjustment_fact as fact;
let DriveSubject { target, parent, facts } = subject;
let has = |bit: u32| facts & bit != 0;
let is_document_element = has(fact::IS_DOCUMENT_ELEMENT);
- if !self.computes_records() {
- self.counters.bump(Counter::EngineComputedRecordBailUnhosted);
- return Err(Unanswered::Refused);
- }
// HACK: A cascade that ends in `font-family: monospace` re-runs the font-size cascade over
// the whole ancestor chain against a 13px default instead of the 16px one, which
- // changes what a keyword size an ancestor declared means. See
- // `StyleComputer::recascade_font_size_if_needed`.
+ // changes what a keyword size an ancestor declared means.
let mut recascaded_font_size_reads_viewport = false;
let recascaded_font_size = if let Some(progress) = font_scratch
.pending
@@ -741,7 +462,7 @@ impl RetainedState {
.winning_declaration(prop::FONT_FAMILY)
.is_some_and(|(value, ..)| font_family_is_monospace(value.data()))
{
- match self.monospace_recascaded_font_size(target, inputs) {
+ match self.monospace_recascaded_font_size_with(records, target, inputs) {
Some(MonospaceRecascade::Size(recascaded, reads_viewport)) => {
recascaded_font_size_reads_viewport = reads_viewport;
Some(recascaded)
@@ -750,42 +471,17 @@ impl RetainedState {
return Err(font_scratch.suspend(target, request, None));
}
None => {
- self.counters.bump(Counter::EngineComputedRecordBailMonospaceQuirk);
- return Err(Unanswered::Refused);
+ unreachable!("the style engine answers every row");
}
}
} else {
None
};
- // The record being driven again has a view. One without is driven as an element with no
- // record is, from a fresh table.
- let old_view = old_style_record.and_then(|old_style_record| {
- let view = self.computed_group_sets.style_record_view(old_style_record.raw());
- debug_assert!(view.is_some(), "the record being driven again has a view");
- view
- });
- let old_table = match &old_view {
- Some(view) => {
- if view.animated_overlay.is_some() {
- self.counters.bump(Counter::EngineComputedRecordBailRecordOverlay);
- return Err(Unanswered::Refused);
- }
- // A record holding no table is driven from a fresh one, like a first record.
- view.longhand_table
- }
- None => None,
- };
let parent_view = match parent {
Some(parent) => {
- let Some(parent_record) = self.computed_group_sets.assigned_style_record(parent) else {
- self.counters.bump(Counter::EngineComputedRecordBailRecordParent);
+ let Some(parent_view) = records.assigned_record_view(parent) else {
return Err(Unanswered::AwaitsParent);
};
- let Some(parent_view) = self.computed_group_sets.style_record_view(parent_record.raw()) else {
- debug_assert!(false, "an assigned parent record has a view");
- self.counters.bump(Counter::EngineComputedRecordBailRecordParent);
- return Err(Unanswered::Refused);
- };
Some(parent_view)
}
None => None,
@@ -803,33 +499,30 @@ impl RetainedState {
match &parent_view {
Some(parent_view) => {
let parent_font = unsafe {
- parent_view.payloads[STYLE_GROUP_INDEX_FONT]
+ parent_view.payloads[group_index::FONT]
.cast::<crate::css::computed_value_types::FontValues>()
.deref()
};
+ let first_available = parent_font.first_available_font_metrics();
(
FfiFontMetrics {
font_size: parent_font.font_size.to_double(),
- x_height: drive_font_metric(parent_font.font_x_height),
- cap_height: drive_font_metric(parent_font.font_ascent),
- zero_advance: drive_font_metric(parent_font.font_zero_advance),
- line_height: parent_font.line_height_used.to_double(),
+ x_height: drive_font_metric(first_available.x_height),
+ cap_height: drive_font_metric(first_available.ascent),
+ zero_advance: drive_font_metric(first_available.zero_advance),
+ line_height: parent_font.line_height_used().to_double(),
},
parent_view.dependency_flags & FONT_METRICS_DEPEND_ON_VIEWPORT_METRICS != 0,
- parent_font.line_height_used.to_double(),
+ parent_font.line_height_used().to_double(),
)
}
None => (initial_metrics, false, inputs.initial_line_height),
};
let snapshot = match &parent_view {
Some(parent_view) => {
- let Some(parent_table) = parent_view.longhand_table else {
- debug_assert!(false, "an assigned parent record has a longhand table");
- self.counters.bump(Counter::EngineComputedRecordBailRecordParent);
- return Err(Unanswered::Refused);
- };
- Some(crate::css::style_compute::ParentSnapshot::new(
- parent_table,
+ let parent_longhands = parent_view.longhands();
+ Some(crate::css::style_compute::ParentSnapshot::from_view(
+ parent_longhands,
parent_view.animated_overlay,
parent_font_metrics_depend_on_viewport_metrics,
))
@@ -839,36 +532,39 @@ impl RetainedState {
// A highlight pseudo-element inherits its applicable properties from the same
// pseudo-element of the nearest ancestor.
let highlight = pseudo_kind::is_highlight(target.pseudo_kind()).then(|| {
- let snapshot = self
- .retained_highlight_inheritance_parent_style_record(target.node(), target.pseudo_kind())
- .and_then(|record| self.computed_group_sets.style_record_view(record.raw()))
- .and_then(|view| {
- let table = view.longhand_table?;
- Some(crate::css::style_compute::ParentSnapshot::new(
- table,
+ let snapshot = records
+ .highlight_inheritance_parent_view(target.node(), target.pseudo_kind())
+ .map(|view| {
+ crate::css::style_compute::ParentSnapshot::from_view(
+ view.longhands(),
view.animated_overlay,
view.dependency_flags & (1 << 1) != 0,
- ))
+ )
});
crate::css::style_compute::HighlightInheritance {
pseudo_kind: target.pseudo_kind(),
snapshot,
}
});
- // The subject axis is the element's own writing mode when it has one, else its parent's;
- // the initial writing mode is horizontal.
- let inherited_box_payload = old_view
- .as_ref()
- .or(parent_view.as_ref())
- .map(|view| view.payloads[STYLE_GROUP_INDEX_INHERITED_BOX]);
- let subject_inline_axis_is_horizontal = inherited_box_payload.is_none_or(|payload| {
- let inherited_box = unsafe {
- payload
- .cast::<crate::css::computed_values::InheritedBoxValues>()
- .deref()
- };
- inherited_box.writing_mode == crate::css::css_enums::writing_mode::HORIZONTAL_TB
- });
+ // The subject axis is the element's own writing mode: the keyword its winner declares,
+ // which is its computed value, else the one it held, else its parent's; the initial
+ // writing mode is horizontal.
+ let declared_writing_mode =
+ store
+ .winning_declaration(prop::WRITING_MODE)
+ .and_then(|(value, ..)| match value.data() {
+ StyleValueData::Keyword {
+ keyword: crate::css::style_compute::keyword::INITIAL,
+ } => Some(crate::css::css_enums::writing_mode::HORIZONTAL_TB),
+ StyleValueData::Keyword { keyword } => crate::css::style_compute::keyword_to_writing_mode(*keyword),
+ _ => None,
+ });
+ let subject_inline_axis_is_horizontal = match declared_writing_mode {
+ Some(writing_mode) => writing_mode == crate::css::css_enums::writing_mode::HORIZONTAL_TB,
+ None => parent_view.as_ref().is_none_or(|view| {
+ view.payloads.inherited_bits().writing_mode() == crate::css::css_enums::writing_mode::HORIZONTAL_TB
+ }),
+ };
let document_root_font_metrics = FfiFontMetrics {
font_size: inputs.root_font_size,
x_height: inputs.root_font_x_height,
@@ -879,9 +575,10 @@ impl RetainedState {
// A tree-counting function on a pseudo-element counts its originating element's siblings.
let sibling_position = self.sibling_position(subject.target.node());
let environment = FfiStyleComputationEnvironment {
- box_type_input: self.box_type_transformation_input(
+ box_type_input: self.box_type_transformation_input_with(
+ records,
facts,
- crate::css::style_compute::FfiStyleAdjustmentTarget::Element,
+ crate::css::style_compute::StyleAdjustmentTarget::Element,
parent,
),
color_scheme_input: FfiEffectiveColorSchemeInput {
@@ -950,7 +647,7 @@ impl RetainedState {
if !resuming {
self.counters.bump(Counter::EngineFullDrivesStarted);
}
- let (mut table, mut results, mut effective_color_scheme) = match resumed {
+ let (mut writer, mut results, mut effective_color_scheme) = match resumed {
Some(pending) => {
resolved_viewport_relative_length = pending.resolved_viewport_relative_length;
if !pending.root_font_complete {
@@ -960,29 +657,25 @@ impl RetainedState {
u64::from(pending.results.longhand_evaluations),
);
}
- (pending.table, pending.results, pending.effective_color_scheme)
+ (pending.writer, pending.results, pending.effective_color_scheme)
}
- None => (
- old_table.map_or_else(ComputedLonghandTable::new, ComputedLonghandTable::copied_for_drive),
- empty_longhand_driver_results(),
- -1,
- ),
+ None => (writer, empty_longhand_driver_results(), -1),
};
let drive = |counters: &Counters,
- table: &mut ComputedLonghandTable,
- results: &mut crate::css::style_compute::FfiLonghandDriverResults,
+ writer: &mut GroupValuesWriter<'_>,
+ results: &mut crate::css::style_compute::LonghandDriverResults,
effective_color_scheme: &mut i16,
phase: u8,
length: Option<&FfiLengthResolutionContext>,
input_line_height_metrics: Option<&FfiInputLineHeightMetrics>| unsafe {
let evaluations_before = results.longhand_evaluations;
drive_property_computation(
- table,
+ writer,
&store,
snapshot.as_ref(),
highlight.as_ref(),
&environment,
- None,
+ selected,
phase,
length,
input_line_height_metrics,
@@ -1011,18 +704,17 @@ impl RetainedState {
// element that declares its own `font-size` still has that declaration win, because the
// drive reads a winning declaration before it consults this.
if let Some(recascaded) = recascaded_font_size {
- table.set_computed(
+ writer.set_computed(
prop::FONT_SIZE,
StyleValueData::Length {
value: CssPixels::from_raw(recascaded).to_double(),
unit: crate::css::style_compute::px_length_unit(),
},
- -1,
);
}
drive(
&self.counters,
- &mut table,
+ &mut writer,
&mut results,
&mut effective_color_scheme,
LONGHAND_DRIVE_PHASE_FONT,
@@ -1038,9 +730,11 @@ impl RetainedState {
}
// The element's own font, resolved as the C++ font computer would for these values.
- let request = engine_sample::font_resolution_request(&table, None, inputs, || {
- self.font_feature_values_scope(target.node())
- });
+ let request = engine_sample::font_resolution_request(
+ |property| Some(writer.effective_value(property)),
+ inputs,
+ || self.font_feature_values_scope(target.node()),
+ );
let font_size = request.font_size();
let Some(resolved) = self
.font_resolution
@@ -1051,7 +745,7 @@ impl RetainedState {
root_font_complete: false,
color_scheme_complete: false,
recascaded_font_size,
- table,
+ writer: writer.detached(),
results,
effective_color_scheme,
resolved_viewport_relative_length,
@@ -1059,10 +753,9 @@ impl RetainedState {
return Err(font_scratch.suspend(target, request, Some(progress)));
};
if request.font_size_adjust == bridge::FontSizeAdjustKind::FromFont {
- table.set_computed(
+ writer.set_computed(
prop::FONT_SIZE_ADJUST,
engine_sample::computed_font_size_adjust_from_font(&request, &resolved),
- -1,
);
}
let own_metrics = |line_height: f64| FfiFontMetrics {
@@ -1091,7 +784,7 @@ impl RetainedState {
if !root_font_complete {
drive(
&self.counters,
- &mut table,
+ &mut writer,
&mut results,
&mut effective_color_scheme,
LONGHAND_DRIVE_PHASE_LINE_HEIGHT,
@@ -1100,37 +793,12 @@ impl RetainedState {
);
}
- let line_height_before_adjustments = engine_sample::used_line_height(&table, None, &request, &resolved);
- if goal == FontDriveGoal::RootInputs {
- let root_inputs = RootFontInputs {
- metrics: [
- font_size.to_bits(),
- drive_font_metric(resolved.x_height).to_bits(),
- drive_font_metric(resolved.ascent).to_bits(),
- drive_font_metric(resolved.zero_advance).to_bits(),
- line_height_before_adjustments.to_bits(),
- ],
- depends_on_viewport: results.font_metrics_depend_on_viewport_metrics,
- effective_zoom: f64::from(table.effective_zoom()).to_bits(),
- };
- font_scratch.pending = Some(PendingFontDrive {
- target,
- progress: Some(DriveProgress {
- root_font_complete: true,
- color_scheme_complete: false,
- recascaded_font_size,
- table,
- results,
- effective_color_scheme,
- resolved_viewport_relative_length,
- }),
- });
- return Ok(FullDrive::RootInputs(root_inputs));
- }
+ let line_height_before_adjustments =
+ engine_sample::used_line_height(|property| Some(writer.effective_value(property)), &request, &resolved);
if !color_scheme_complete {
drive(
&self.counters,
- &mut table,
+ &mut writer,
&mut results,
&mut effective_color_scheme,
LONGHAND_DRIVE_PHASE_COLOR_SCHEME,
@@ -1138,7 +806,7 @@ impl RetainedState {
None,
);
}
- effective_color_scheme = table.effective_color_scheme();
+ effective_color_scheme = writer.effective_color_scheme();
let remaining_length = length_context(
own_metrics(line_height_before_adjustments),
@@ -1154,38 +822,6 @@ impl RetainedState {
inputs.root_font_metrics_depend_on_viewport_metrics
},
);
- // A registered custom property computes against the font and color scheme settled now, as
- // the host finalizes one after the line-height phase; the winners the remaining phase reads
- // substitute what it computes to.
- if let Some(initial_context) = initial_registered_context {
- let context = self.registered_value_context(
- target.node(),
- FfiLengthResolutionContext {
- resolved_viewport_relative_length: std::ptr::null_mut(),
- ..remaining_length
- },
- u8::try_from(effective_color_scheme).unwrap_or(inputs.preferred_color_scheme),
- target.is_pseudo(),
- );
-
- // The initial environment already used this context. Resolve again only if
- // computing the font, line-height, or color scheme changed it.
- if context != *initial_context {
- font_scratch.pending = Some(PendingFontDrive {
- target,
- progress: Some(DriveProgress {
- root_font_complete: true,
- color_scheme_complete: true,
- recascaded_font_size,
- table,
- results,
- effective_color_scheme,
- resolved_viewport_relative_length,
- }),
- });
- return Ok(FullDrive::AwaitsRegisteredContext(context));
- }
- }
let input_line_height_metrics = if has(fact::CHECK_INPUT_LINE_HEIGHT) {
FfiInputLineHeightMetrics {
current_line_height: line_height_before_adjustments,
@@ -1199,7 +835,7 @@ impl RetainedState {
};
drive(
&self.counters,
- &mut table,
+ &mut writer,
&mut results,
&mut effective_color_scheme,
LONGHAND_DRIVE_PHASE_REMAINING,
@@ -1208,22 +844,20 @@ impl RetainedState {
);
// A tree-counting value is admitted only where the retained tree places the element.
if results.uses_tree_counting_function && sibling_position.is_none() {
- self.counters.bump(Counter::EngineComputedRecordBailDrive);
- return Err(Unanswered::Refused);
+ unreachable!("the style engine answers every row");
}
- let line_height_used_after = engine_sample::used_line_height(&table, None, &request, &resolved);
- let font = engine_sample::font_group_build_inputs(&table, None, &request, line_height_used_after, &resolved);
+ let values = |property| Some(writer.effective_value(property));
+ let line_height_used_after = engine_sample::used_line_height(values, &request, &resolved);
+ let font = engine_sample::font_group_build_inputs(values, &request, line_height_used_after, &resolved);
let length = FfiLengthResolutionContext {
resolved_viewport_relative_length: std::ptr::null_mut(),
..remaining_length
};
- Ok(FullDrive::Driven(DrivenTable {
- table,
+ Ok(DrivenValues {
+ writer,
length,
- longhand_evaluations: results.longhand_evaluations,
font: Some(font),
- explicitly_inherited_groups: results.explicitly_inherited_non_inherited_style_groups,
- }))
+ })
}
}
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/mod.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/mod.rs
new file mode 100644
index 00000000000..93975d774be
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/mod.rs
@@ -0,0 +1,253 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The style engine; see
+//! `Documentation/Style/StyleEngine.md`.
+//!
+#[cfg(test)]
+pub(crate) mod allocation_count;
+#[cfg(test)]
+mod allocation_tests;
+mod bloom;
+mod cascade;
+mod cold_pass;
+pub(in crate::css::style) mod compute;
+pub(super) mod counters;
+pub(in crate::css::style) mod custom_properties;
+mod custom_property_moves;
+mod declared_only;
+mod demand;
+#[cfg(test)]
+mod differential_tests;
+pub(in crate::css::style) mod drive;
+mod extent_map;
+#[cfg(test)]
+mod fork_tests;
+pub(crate) mod highlight_observers;
+pub(crate) mod install;
+mod install_scratch;
+mod invalidation;
+mod live;
+pub(crate) mod main_effects;
+mod matched_rules;
+mod matching;
+mod pending_inputs;
+pub(super) use pending_inputs::HoverSealMemo;
+pub(crate) mod pool;
+pub(in crate::css::style) mod projection;
+mod records;
+mod results;
+mod rule_changes;
+pub(crate) mod rule_store;
+mod rules;
+mod self_check;
+mod shared_pages;
+mod shared_prefix;
+mod sharing;
+#[cfg(test)]
+mod test_support;
+mod traversal;
+pub(in crate::css::style) mod winner_store;
+mod write_once;
+
+use super::*;
+use bloom::{attribute_hash, class_hash, id_hash, tag_hash};
+pub(super) use cascade::DeclaredOnly;
+pub(super) use live::Live;
+#[cfg(test)]
+pub(super) use records::PseudoElementStyles;
+pub(crate) use records::Record;
+pub(crate) use records::{CustomDeclarations, RareSetFacts, RareStyleFacts};
+pub(super) use records::{RecordFacts, Sample};
+
+pub(super) use cold_pass::{Report, ReportField};
+pub(super) use rules::ProcessRuleIndexes;
+#[cfg(test)]
+pub(super) use rules::entries_of;
+pub(super) use self_check::SelfCheckSettings;
+use smallvec::SmallVec;
+
+/// The pseudo-elements a pass styles beside their element, in the order the host installs them.
+pub(super) const PSEUDO_ELEMENT_KINDS: [u8; 9] = {
+ use super::publication::pseudo_kind::{
+ AFTER, BACKDROP, BEFORE, FIRST_LETTER, MARKER, SEARCH_TEXT, SEARCH_TEXT_CURRENT, SELECTION, SPELLING_ERROR,
+ };
+ [
+ BEFORE,
+ AFTER,
+ FIRST_LETTER,
+ SELECTION,
+ SEARCH_TEXT,
+ SEARCH_TEXT_CURRENT,
+ SPELLING_ERROR,
+ BACKDROP,
+ MARKER,
+ ]
+};
+
+/// The highlight pseudo-elements, which inherit from the same pseudo-element of the nearest
+/// ancestor that has one.
+pub(super) const HIGHLIGHT_KINDS: [u8; 4] = {
+ use super::publication::pseudo_kind::{SEARCH_TEXT, SEARCH_TEXT_CURRENT, SELECTION, SPELLING_ERROR};
+ [SELECTION, SEARCH_TEXT, SEARCH_TEXT_CURRENT, SPELLING_ERROR]
+};
+
+/// The keys an element contributes to its descendants' ancestor filter.
+pub(super) fn ancestor_keys_of(facts: projection::ProjectionRow<'_>) -> SmallVec<[u32; 8]> {
+ let mut keys = SmallVec::new();
+ let id = facts.id();
+ if !id.is_none() {
+ keys.push(id_hash(id));
+ }
+ keys.extend(facts.classes().iter().map(|&class| class_hash(class)));
+ for tag in [facts.tag(), facts.folded_tag()] {
+ if !tag.is_none() {
+ keys.push(tag_hash(tag));
+ }
+ }
+ keys.extend(
+ facts
+ .attributes()
+ .iter()
+ .map(|attribute| attribute_hash(attribute.name)),
+ );
+ keys
+}
+
+/// What a computation waits on before it can answer.
+#[derive(Default)]
+pub(super) struct Waits {
+ pub(super) fonts: Vec<font_resolution::FontRequest>,
+ pub(super) random_bases: Vec<super::random_bases::RandomBaseRequest>,
+}
+
+/// How many rounds a computation may wait on fonts and random base values: a declined element hides
+/// what its descendants wait on, so each round can find more.
+const MAX_RESOLVE_ROUNDS: usize = 32;
+
+impl StyleEngine {
+ /// Runs `body` with the fonts of the document found by the content of their requests: a round
+ /// computes the values its font requests name anew, so the fonts the round before asked for are
+ /// found by the content of those values.
+ fn matching_fonts_by_content<T>(&mut self, body: impl FnOnce(&mut Self) -> T) -> T {
+ let set = |engine: &mut Self, matches_by_content| {
+ let Some(cache) = &mut engine.retained.font_resolution else {
+ return false;
+ };
+ let before = cache.matches_by_content();
+ cache.set_matches_by_content(matches_by_content);
+ before
+ };
+ let before = set(self, true);
+ let answer = body(self);
+ set(self, before);
+ answer
+ }
+
+ /// The answer of `attempt`, run again until it no longer waits on anything, which this resolves
+ /// for `node` between its runs, or none where it keeps waiting.
+ pub(super) fn until_resolved<T>(
+ &mut self,
+ node: StyleNodeID,
+ mut attempt: impl FnMut(&mut Self) -> Result<T, Waits>,
+ ) -> Option<T> {
+ self.matching_fonts_by_content(|engine| {
+ for _ in 0..MAX_RESOLVE_ROUNDS {
+ match attempt(engine) {
+ Ok(answer) => return Some(answer),
+ Err(waits) => {
+ for request in waits.fonts {
+ engine.refill_font_request(node, request);
+ }
+ for request in waits.random_bases {
+ engine.retained.draw_random_base_value(request);
+ }
+ }
+ }
+ }
+ None
+ })
+ }
+
+ /// The computed initial values of the document under `root`.
+ fn computed_initial(&mut self, root: StyleNodeID) -> Option<traversal::InitialStyle> {
+ // The initial values compute against the document's initial font, which no element may
+ // have asked the resolver for yet.
+ self.until_resolved(root, |engine| {
+ match engine.retained.initial_style(root) {
+ Ok(computed) => {
+ // SAFETY: The initial style takes over the references the drive made.
+ let mut payloads = unsafe {
+ crate::css::computed_values::StyleGroups::adopt(
+ computed.payloads,
+ crate::css::computed_value_types::StyleBits {
+ inherited: crate::css::computed_value_types::InheritedSetValues {
+ bits: crate::css::computed_value_types::InheritedBits::INITIAL,
+ effective_zoom_bits: computed.value_facts.effective_zoom().to_bits(),
+ },
+ reset: crate::css::computed_value_types::ResetBits::INITIAL,
+ },
+ )
+ };
+ // The documents of the process share the initial groups but the font group.
+ let shared = engine.retained.process_style.share_initial_groups(
+ engine
+ .retained
+ .document_style_computation_inputs
+ .device_pixels_per_css_pixel,
+ &payloads,
+ );
+ for index in crate::css::computed_values::StyleGroupIndex::all() {
+ if index.usize() != crate::css::table_group_builder::group_index::FONT {
+ payloads.share_group(shared.groups(), index);
+ }
+ }
+ Ok(Some(traversal::InitialStyle::new(computed, payloads, shared)))
+ }
+ // NB: An engine no host published its fonts to yet, such as a test's bare engine, has no resolver
+ // to ask, and its initial style waits on fonts it cannot resolve yet.
+ Err(Some(_)) if engine.host.font_resolver.is_none() => Ok(None),
+ Err(Some(request)) => Err(Waits {
+ fonts: vec![*request],
+ random_bases: Vec::new(),
+ }),
+ Err(None) => Ok(None),
+ }
+ })
+ .flatten()
+ }
+
+ /// Has style passes run on the threads of `pool`, which the process shares.
+ pub(crate) fn share_style_pool(&mut self, pool: std::sync::Arc<pool::StylePool>) {
+ self.retained.style_pool = Some(pool);
+ }
+
+ /// The pool a pass on `threads` threads runs on besides the calling thread, or on the default
+ /// number for the machine for none, where its threads have started.
+ fn style_pool(&mut self, threads: u32) -> Option<std::sync::Arc<rayon::ThreadPool>> {
+ let threads = match threads {
+ 0 => traversal::thread_count(),
+ threads => (threads as usize).min(traversal::MAX_THREAD_COUNT),
+ };
+ // The calling thread is one of the threads the pass runs on.
+ let workers = threads.max(1) - 1;
+ // NB: An engine no render state holds, such as a test's, starts threads of its own.
+ self.retained
+ .style_pool
+ .get_or_insert_with(|| std::sync::Arc::new(pool::StylePool::new(pool::PoolStart::OnFirstPass)))
+ .workers(workers)
+ }
+}
+
+impl RetainedState {
+ /// What the audit of what passes reuse asks for: what the engine read as it started, or off
+ /// without it.
+ fn cache_audit_mode(&self) -> self_check::Mode {
+ self.live_style
+ .as_ref()
+ .map_or(self_check::Mode::Off, |live| live.cache_audit)
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/pool.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/pool.rs
new file mode 100644
index 00000000000..45e7bb24b6b
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/pool.rs
@@ -0,0 +1,127 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The threads style passes run on besides the calling thread. The owner of every document's
+//! render state holds one pool for the process and hands it to each document's style engine, so
+//! the documents of a process share their style threads, and the heaps those threads warm.
+
+use std::sync::{Arc, Mutex, PoisonError};
+
+/// When a pool's threads start.
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(crate) enum PoolStart {
+ /// On a thread of its own, once a pass first asks for them: the passes until they have started
+ /// run on the calling thread alone, which spares the first pass of a document starting them.
+ InBackground,
+ /// On the thread of the first pass asking for them, which then runs on them.
+ OnFirstPass,
+}
+
+/// The pool of threads style passes run on besides the calling thread, started once a pass
+/// first asks for it.
+pub(crate) struct StylePool {
+ start: PoolStart,
+ threads: Mutex<PoolThreads>,
+}
+
+enum PoolThreads {
+ NotStarted,
+ /// Starting `workers` threads, on a thread of their own.
+ Starting {
+ workers: usize,
+ },
+ Started(Arc<rayon::ThreadPool>),
+}
+
+impl StylePool {
+ pub(crate) fn new(start: PoolStart) -> Self {
+ Self {
+ start,
+ threads: Mutex::new(PoolThreads::NotStarted),
+ }
+ }
+
+ /// The pool of `workers` threads a pass runs on besides the calling thread, where it has
+ /// started: none for no workers, and none while the threads start in the background, which
+ /// the first such ask starts them for.
+ pub(crate) fn workers(self: &Arc<Self>, workers: usize) -> Option<Arc<rayon::ThreadPool>> {
+ if workers == 0 {
+ return None;
+ }
+ let mut threads = self.threads.lock().unwrap_or_else(PoisonError::into_inner);
+ match &*threads {
+ PoolThreads::Started(pool) if pool.current_num_threads() == workers => return Some(pool.clone()),
+ PoolThreads::Starting { workers: starting } if *starting == workers => return None,
+ _ => {}
+ }
+ match self.start {
+ PoolStart::OnFirstPass => {
+ let pool = Arc::new(start_threads(workers));
+ *threads = PoolThreads::Started(pool.clone());
+ Some(pool)
+ }
+ PoolStart::InBackground => {
+ *threads = PoolThreads::Starting { workers };
+ let this = self.clone();
+ std::thread::Builder::new()
+ .name("Style start".into())
+ .spawn(move || {
+ let pool = Arc::new(start_threads(workers));
+ let mut threads = this.threads.lock().unwrap_or_else(PoisonError::into_inner);
+ // NB: A pass may have asked for another number of threads meanwhile.
+ if matches!(*threads, PoolThreads::Starting { workers: starting } if starting == workers) {
+ *threads = PoolThreads::Started(pool);
+ }
+ })
+ .expect("the thread starting the engine pool starts");
+ None
+ }
+ }
+ }
+
+ /// The threads of the pool, whatever their number, where they have started.
+ pub(crate) fn started(&self) -> Option<Arc<rayon::ThreadPool>> {
+ match &*self.threads.lock().unwrap_or_else(PoisonError::into_inner) {
+ PoolThreads::Started(pool) => Some(pool.clone()),
+ PoolThreads::NotStarted | PoolThreads::Starting { .. } => None,
+ }
+ }
+}
+
+fn start_threads(workers: usize) -> rayon::ThreadPool {
+ rayon::ThreadPoolBuilder::new()
+ .num_threads(workers)
+ .thread_name(|index| format!("StyleWorker {index}"))
+ .build()
+ .expect("the engine thread pool starts")
+}
+
+/// What each thread a pass runs on keeps between passes, by thread, the calling thread's last: a slot is made the first
+/// time its thread asks for it, so a document, or a fork of its render state, holds only what its threads used.
+pub(super) struct PerThread<T>([std::sync::OnceLock<Box<Mutex<T>>>; super::traversal::MAX_THREAD_COUNT + 1]);
+
+impl<T> Default for PerThread<T> {
+ fn default() -> Self {
+ Self(std::array::from_fn(|_| std::sync::OnceLock::new()))
+ }
+}
+
+impl<T: Default> PerThread<T> {
+ /// What thread `index` keeps, made where it is not yet, or none past the last thread.
+ pub(super) fn get(&self, index: usize) -> Option<&Mutex<T>> {
+ self.0.get(index).map(|slot| &**slot.get_or_init(Box::default))
+ }
+
+ /// What the threads that asked keep.
+ pub(super) fn made(&self) -> impl Iterator<Item = &Mutex<T>> {
+ self.0.iter().filter_map(|slot| slot.get().map(|made| &**made))
+ }
+
+ /// How many threads may keep anything.
+ pub(super) fn len(&self) -> usize {
+ self.0.len()
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/records.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/records.rs
new file mode 100644
index 00000000000..4ec21762b56
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/records.rs
@@ -0,0 +1,2281 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The computed styles a style pass produced, by element, which the elements after them compute
+//! against. Each element's record is written once, by whichever thread styles it, before any of its
+//! children is styled.
+
+use super::super::animations::DeclarationScope;
+use super::super::container_queries::{ContainerRecords, ContainerVerdict};
+use super::super::selector_evaluation::StructuralRead;
+use super::super::transaction_view::TransactionFactSide;
+use super::super::*;
+use super::drive::DriveRecords;
+use super::traversal::InitialStyle;
+use super::write_once::WriteOnce;
+use crate::css::computed_values::{GroupSeed, GroupValueFacts, GroupValueLayout, LonghandID};
+use crate::css::style::installed_records::InstalledRecordID;
+use crate::css::style::memory_report::{MemoryOwner, MemoryReport};
+use crate::css::style_compute::RootFontReads;
+use crate::css::table_group_builder::group_index;
+use std::borrow::Cow;
+use std::sync::Arc;
+
+/// One element's computed style: its groups, each holding one reference, with their computed values,
+/// the facts its readers read without them, and what its computation recorded beside them.
+#[repr(C)]
+pub(crate) struct Record {
+ /// NB: First, so that a record's address is the address of the groups the host and layout read
+ /// through their places.
+ pub(in super::super) payloads: crate::css::computed_values::StyleGroups,
+ /// What the record's readers read of the element's style without its groups, and the identity
+ /// of the slot holding the record.
+ pub(super) header: RecordHeader,
+}
+
+/// A record's header word, which the host reads from its own thread: the facts of the record,
+/// settled when it is made, the computed `display` in bits 0-12 and the flags in bits 16-23; whether
+/// its groups hold images in bit 15, settled as a slot takes it; and the identity of that slot, its
+/// index in bits 24-47 and its generation in bits 48-63, which the slot names as it takes the record
+/// and forgets as it lets go of it.
+pub(in super::super) struct RecordHeader(std::sync::atomic::AtomicU64);
+
+const _: () = assert!((InstalledRecordID::MAX_SLOT as u64) < RecordHeader::SLOT_MASK);
+const _: () = assert!((InstalledRecordID::MAX_GENERATION as u64) <= u64::MAX >> RecordHeader::GENERATION_SHIFT);
+
+impl RecordHeader {
+ const DISPLAY_MASK: u64 = (1 << 13) - 1;
+ const HOLDS_IMAGE_VALUES: u64 = 1 << 15;
+ const FLAGS_SHIFT: u32 = 16;
+ const SLOT_SHIFT: u32 = 24;
+ const GENERATION_SHIFT: u32 = 48;
+ const SLOT_MASK: u64 = (1 << 24) - 1;
+ /// The slot bits of a record no slot holds.
+ const NO_SLOT: u64 = Self::SLOT_MASK;
+ const IDENTITY_MASK: u64 = !((1 << Self::SLOT_SHIFT) - 1);
+
+ pub(super) fn new(facts: RecordFacts) -> Self {
+ Self(std::sync::atomic::AtomicU64::new(
+ u64::from(facts.display) | u64::from(facts.flags) << Self::FLAGS_SHIFT | Self::NO_SLOT << Self::SLOT_SHIFT,
+ ))
+ }
+
+ fn facts(&self) -> RecordFacts {
+ let header = self.load();
+ RecordFacts {
+ display: (header & Self::DISPLAY_MASK) as u16,
+ flags: (header >> Self::FLAGS_SHIFT) as u8,
+ }
+ }
+
+ fn load(&self) -> u64 {
+ self.0.load(std::sync::atomic::Ordering::Relaxed)
+ }
+
+ fn holds_image_values(&self) -> bool {
+ self.load() & Self::HOLDS_IMAGE_VALUES != 0
+ }
+
+ /// Replaces the bits of `mask` with `bits` in one step: the host reads the word from its own thread, and must
+ /// never see an identity no slot named.
+ fn replace(&self, mask: u64, bits: u64) {
+ use std::sync::atomic::Ordering::Relaxed;
+ let _ = self
+ .0
+ .fetch_update(Relaxed, Relaxed, |header| Some((header & !mask) | bits));
+ }
+
+ fn set_holds_image_values(&self, holds_image_values: bool) {
+ self.replace(
+ Self::HOLDS_IMAGE_VALUES,
+ if holds_image_values {
+ Self::HOLDS_IMAGE_VALUES
+ } else {
+ 0
+ },
+ );
+ }
+
+ fn installed_record(&self) -> Option<InstalledRecordID> {
+ let header = self.load();
+ match (header >> Self::SLOT_SHIFT) & Self::SLOT_MASK {
+ Self::NO_SLOT => None,
+ slot => Some(InstalledRecordID::from_parts(
+ slot as u32,
+ (header >> Self::GENERATION_SHIFT) as u32,
+ )),
+ }
+ }
+
+ /// Names the slot `id` where no slot is named yet, and answers whether it did: a fork of the
+ /// render state may be naming a slot of its own for the same record on its own thread.
+ fn name_installed_record(&self, id: InstalledRecordID) -> bool {
+ use std::sync::atomic::Ordering::Relaxed;
+ assert!(id.slot() <= InstalledRecordID::MAX_SLOT && id.generation() <= InstalledRecordID::MAX_GENERATION);
+ let identity = u64::from(id.slot()) << Self::SLOT_SHIFT | u64::from(id.generation()) << Self::GENERATION_SHIFT;
+ self.0
+ .fetch_update(Relaxed, Relaxed, |header| {
+ ((header >> Self::SLOT_SHIFT) & Self::SLOT_MASK == Self::NO_SLOT)
+ .then_some((header & !Self::IDENTITY_MASK) | identity)
+ })
+ .is_ok()
+ }
+
+ fn forget_installed_record(&self) {
+ self.replace(Self::IDENTITY_MASK, Self::NO_SLOT << Self::SLOT_SHIFT);
+ }
+}
+
+/// The pseudo-elements of an element that generate a box, as a bit per kind.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
+pub(in super::super) struct PseudoElementStyles(u16);
+
+impl PseudoElementStyles {
+ pub(in super::super) const NONE: Self = Self(0);
+
+ /// The pseudo-elements `records` style, by kind.
+ pub(in super::super) fn of(records: &[(u8, Arc<Record>)]) -> Self {
+ Self(records.iter().fold(0, |mask, (kind, _)| mask | (1 << kind)))
+ }
+
+ /// The pseudo-elements of the kinds whose bits `bits` holds, as a test names them.
+ #[cfg(test)]
+ pub(in super::super) fn from_bits(bits: u64) -> Self {
+ Self(u16::try_from(bits).expect("every pseudo-element kind has a bit of 16"))
+ }
+
+ /// The bits of the kinds, `1 << kind` each, as the host reads them.
+ pub(in super::super) fn bits(self) -> u64 {
+ u64::from(self.0)
+ }
+}
+
+/// The custom properties the children of an element inherit.
+#[derive(Clone)]
+pub(in super::super) enum InheritableCustomProperties {
+ /// Those the element holds, as they are where no registration keeps one from inheriting.
+ Held,
+ /// Others: those it holds but for the ones a registration keeps from inheriting, or those its
+ /// parent handed down where it holds none that inherit.
+ Other(Option<Arc<crate::css::custom_properties::CustomPropertyStore>>),
+}
+
+impl InheritableCustomProperties {
+ /// The custom properties children inherit as `inheritable`, of an element holding `held`.
+ pub(in super::super) fn of(
+ held: Option<&Arc<crate::css::custom_properties::CustomPropertyStore>>,
+ inheritable: Option<Cow<'_, Arc<crate::css::custom_properties::CustomPropertyStore>>>,
+ ) -> Self {
+ match (held, &inheritable) {
+ (None, None) => Self::Held,
+ (Some(held), Some(inheritable)) if Arc::ptr_eq(held, inheritable) => Self::Held,
+ _ => Self::Other(inheritable.map(Cow::into_owned)),
+ }
+ }
+
+ fn same_as(&self, other: &Self) -> bool {
+ match (self, other) {
+ (Self::Held, Self::Held) => true,
+ (Self::Other(None), Self::Other(None)) => true,
+ (Self::Other(Some(mine)), Self::Other(Some(theirs))) => Arc::ptr_eq(mine, theirs),
+ _ => false,
+ }
+ }
+}
+
+/// Whether both are the very same allocation, or neither is any.
+fn same_arc<T: ?Sized>(first: Option<&Arc<T>>, second: Option<&Arc<T>>) -> bool {
+ match (first, second) {
+ (None, None) => true,
+ (Some(first), Some(second)) => Arc::ptr_eq(first, second),
+ _ => false,
+ }
+}
+
+/// The custom declarations an element's cascade decided, as written.
+pub(crate) type CustomDeclarations = Arc<[(CustomDeclaration, RetainedStyleValueData)]>;
+
+/// What a record's rare set holds beside its groups.
+#[derive(Clone, Default)]
+pub(crate) struct RareSetFacts {
+ /// What the element's computation recorded and read beyond its values, which the records of
+ /// elements styled alike share.
+ pub(crate) facts: Option<Arc<RareStyleFacts>>,
+ /// The custom declarations the element's cascade decided, as written, which a sample of its
+ /// animations resolves the ones reading an animated custom property from.
+ pub(crate) custom_declarations: Option<CustomDeclarations>,
+}
+
+impl RareSetFacts {
+ /// Whether `other` holds these facts and declarations themselves.
+ pub(crate) fn is(&self, other: &Self) -> bool {
+ same_arc(self.facts.as_ref(), other.facts.as_ref())
+ && same_arc(self.custom_declarations.as_ref(), other.custom_declarations.as_ref())
+ }
+}
+
+/// What an element's computation read beyond its inherited context and its declarations.
+#[derive(Clone, Copy, Default, PartialEq)]
+pub(crate) struct ComputationReads {
+ /// The style groups of the properties that do not inherit whose parent's values the element's
+ /// computation read, or every group where one of them belongs to none.
+ pub(in crate::css::style) parent_reset_groups: u32,
+ /// Whether the element's computation read its place among its siblings, through a
+ /// tree-counting function.
+ pub(in crate::css::style) reads_sibling_position: bool,
+ /// How much of the root element's font the element's computation resolved lengths against.
+ pub(in crate::css::style) reads_root_font: RootFontReads,
+ /// Whether the element's computation resolved a length against a metric of its own or its
+ /// parent's first available font.
+ pub(in crate::css::style) reads_font_metric_lengths: bool,
+ /// What the element's computation read of the document's environment.
+ pub(in crate::css::style) environment_reads: crate::css::style::input_types::StyleEnvironment,
+ /// Whether the element's computation read its attributes, through `attr()`, which what reads
+ /// them beside the winners' values settles as the record is made.
+ pub(in crate::css::style) reads_attributes: bool,
+ /// The container-relative units the element's computation resolved against its query
+ /// containers, as a `container_relative_length_unit_mask`.
+ pub(in crate::css::style) container_units: u8,
+}
+
+/// What a style records of its computation beyond its values: the flags beside its values, what
+/// its groups are built from, where its longhands live, and what its computation read. Elements
+/// styled alike record the same, so siblings, and parents and their children, share one.
+#[derive(Clone)]
+pub(crate) struct RareStyleFacts {
+ /// The custom properties the element's children inherit.
+ pub(in super::super) inheritable_custom_properties: InheritableCustomProperties,
+ /// The flags a longhand table of the element publishes beside its values, which elements
+ /// whose declarations and computations wrote the same longhands share.
+ pub(in super::super) table_flags: Arc<crate::css::computed_longhand_table::LonghandTableFlags>,
+ /// What the groups are built from beside their computed values.
+ pub(in super::super) value_facts: GroupValueFacts,
+ /// Where the record's computed longhand values live.
+ pub(in super::super) longhand_home: LonghandHome,
+ /// The custom properties the element's longhands substitute, which a sample of its animations
+ /// moving none of them leaves them as they are.
+ pub(in super::super) custom_property_reads: crate::css::style::custom_property_cascade::LonghandCustomPropertyReads,
+ /// What else the element's computation read.
+ pub(in super::super) reads: ComputationReads,
+ /// The identity of the counter-style registry of its style scope, where the style reads it,
+ /// or zero.
+ pub(in super::super) counter_style_environment_identity: u64,
+ /// The scope the winning `animation-name` was declared in, where the `@keyframes` it names are
+ /// looked for first.
+ pub(in super::super) animation_name_scope: DeclarationScope,
+ /// The pseudo-elements of the element that generate a box, which a pass settles as it styles
+ /// them beside the element.
+ // NB: Records styled alike but for these hold the same style, so `same_as` leaves them out.
+ pub(in super::super) pseudo_element_styles: PseudoElementStyles,
+}
+
+// NB: Every element with a style of its own holds one of these; a field that grows it grows them all.
+const _: () = assert!(size_of::<Record>() == 64);
+const _: () = assert!(std::mem::offset_of!(Record, payloads) == 0);
+const _: () = assert!(std::mem::offset_of!(Record, header) == 56);
+const _: () = assert!(size_of::<RecordFacts>() == 4);
+const _: () = assert!(size_of::<GroupValueFacts>() == 32);
+const _: () = assert!(size_of::<RareStyleFacts>() == 120);
+
+impl RareStyleFacts {
+ /// These facts, with `inheritable` as the custom properties the element's children inherit.
+ pub(in super::super) fn with_inheritable_custom_properties(
+ self: &Arc<Self>,
+ inheritable: InheritableCustomProperties,
+ ) -> Arc<Self> {
+ if self.inheritable_custom_properties.same_as(&inheritable) {
+ return self.clone();
+ }
+ Arc::new(Self {
+ inheritable_custom_properties: inheritable,
+ ..(**self).clone()
+ })
+ }
+
+ /// These facts, styling the pseudo-elements of `styles`.
+ pub(in super::super) fn with_pseudo_element_styles(self: &Arc<Self>, styles: PseudoElementStyles) -> Arc<Self> {
+ if self.pseudo_element_styles == styles {
+ return self.clone();
+ }
+ Arc::new(Self {
+ pseudo_element_styles: styles,
+ ..(**self).clone()
+ })
+ }
+
+ /// The facts of a style a computation made, which holds its longhands in its groups, and whose
+ /// pseudo-elements a pass settles after it.
+ pub(in super::super) fn of_computation(
+ inheritable_custom_properties: InheritableCustomProperties,
+ counter_style_environment_identity: u64,
+ table_flags: Arc<crate::css::computed_longhand_table::LonghandTableFlags>,
+ value_facts: GroupValueFacts,
+ custom_property_reads: crate::css::style::custom_property_cascade::LonghandCustomPropertyReads,
+ reads: ComputationReads,
+ animation_name_scope: DeclarationScope,
+ ) -> Self {
+ Self {
+ inheritable_custom_properties,
+ table_flags,
+ value_facts,
+ longhand_home: LonghandHome::Groups,
+ custom_property_reads,
+ reads,
+ counter_style_environment_identity,
+ animation_name_scope,
+ pseudo_element_styles: PseudoElementStyles::NONE,
+ }
+ }
+
+ /// The facts of a style the host made, which read nothing of the document: `source_groups` holds
+ /// its longhands.
+ fn of_host_style(
+ table_flags: crate::css::computed_longhand_table::LonghandTableFlags,
+ value_facts: crate::css::computed_values::GroupValueFacts,
+ source_groups: crate::css::computed_values::StyleGroups,
+ counter_style_environment_identity: u64,
+ ) -> Self {
+ Self {
+ inheritable_custom_properties: InheritableCustomProperties::Held,
+ table_flags: Arc::new(table_flags),
+ value_facts,
+ longhand_home: LonghandHome::SourceGroups(DerivedSource::of(source_groups)),
+ custom_property_reads: Default::default(),
+ reads: ComputationReads::default(),
+ counter_style_environment_identity,
+ animation_name_scope: DeclarationScope::Unscoped,
+ pseudo_element_styles: PseudoElementStyles::NONE,
+ }
+ }
+
+ /// Whether `other` records what these do, so that a record may hold either.
+ pub(in super::super) fn same_as(&self, other: &RareStyleFacts) -> bool {
+ matches!(
+ (&self.longhand_home, &other.longhand_home),
+ (LonghandHome::Groups, LonghandHome::Groups)
+ ) && self
+ .inheritable_custom_properties
+ .same_as(&other.inheritable_custom_properties)
+ && (Arc::ptr_eq(&self.table_flags, &other.table_flags) || self.table_flags.same_as(&other.table_flags))
+ && self.value_facts.publication_equals(&other.value_facts)
+ && self.custom_property_reads == other.custom_property_reads
+ && self.reads == other.reads
+ && self.counter_style_environment_identity == other.counter_style_environment_identity
+ && self.animation_name_scope == other.animation_name_scope
+ }
+}
+
+/// Where a record's computed longhand values live.
+#[derive(Clone)]
+pub(in super::super) enum LonghandHome {
+ /// In the record's own groups.
+ Groups,
+ /// In the groups of the style a derived record was derived from, each of which it holds a
+ /// reference to: a derived style holds the longhands of its source.
+ SourceGroups(Box<DerivedSource>),
+}
+
+/// What a derived record holds of the style it was derived from.
+#[derive(Clone)]
+pub(in super::super) struct DerivedSource {
+ /// The source's groups, which hold the derived record's longhands.
+ pub(in super::super) groups: crate::css::computed_values::StyleGroups,
+ /// What the animations of the element sampled over the source, where the derived record is a
+ /// sample of them.
+ pub(in super::super) sample: Option<Box<Sample>>,
+}
+
+impl DerivedSource {
+ fn of(groups: crate::css::computed_values::StyleGroups) -> Box<Self> {
+ Box::new(Self { groups, sample: None })
+ }
+}
+
+/// What a record of a sample of the animations of an element holds beside its groups.
+#[derive(Clone)]
+pub(in super::super) struct Sample {
+ /// The installed record the animations sample over.
+ pub(in super::super) base: Arc<Record>,
+ /// The values the animations compose over the base.
+ pub(in super::super) animated_overlay: Arc<crate::css::animated_overlay::AnimatedOverlay>,
+ /// What a view of the sample depends on: what a view of the base does, with an `<image>` a
+ /// sampled value holds where the base holds none, and in the display:none subtree a sampled
+ /// display puts it in.
+ pub(in super::super) dependency_flags: u8,
+ /// The identity the host names the sample by.
+ pub(in super::super) identity: computed::FinalStyleRecordID,
+}
+
+/// What a record holds of an element's style beside its values, settled when the record is made.
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[repr(C)]
+pub(in super::super) struct RecordFacts {
+ /// The computed `display`, packed by `pack_display`.
+ display: u16,
+ /// The dependency flags at their bit values, with whether the element is `display: none` or
+ /// inherits from one that is at `IN_DISPLAY_NONE_SUBTREE`, and `DECLARES_CSS_ANIMATIONS` and
+ /// `DECLARES_TRANSITIONS`.
+ flags: u8,
+}
+
+/// `display` in 16 bits: its tag in bits 0-1, then the three bytes of its encoding in five, five
+/// and one bit.
+fn pack_display(display: crate::css::display::FfiDisplay) -> u16 {
+ let [tag, first, second, third] = display.encoded().to_le_bytes();
+ assert!(
+ tag < 4 && first < 32 && second < 32 && third < 2,
+ "every display value packs into 16 bits"
+ );
+ u16::from(tag) | u16::from(first) << 2 | u16::from(second) << 7 | u16::from(third) << 12
+}
+
+fn unpack_display(packed: u16) -> crate::css::display::FfiDisplay {
+ let field = |shift: u16, bits: u16| u32::from((packed >> shift) & ((1 << bits) - 1));
+ crate::css::display::FfiDisplay::from_raw(field(0, 2) | field(2, 5) << 8 | field(7, 5) << 16 | field(12, 1) << 24)
+}
+
+impl RecordFacts {
+ /// Whether the computed `animation-name` names any animation.
+ const DECLARES_CSS_ANIMATIONS: u8 = 1 << 3;
+ /// Whether the computed `transition-*` values make any longhand transitionable.
+ const DECLARES_TRANSITIONS: u8 = 1 << 4;
+
+ /// The facts of a style whose computed values `value_of` answers, which resolves no color yet.
+ pub(in super::super) fn of_values<'v>(
+ value_of: impl Fn(u16) -> &'v RetainedStyleValueData,
+ dependency_flags: u8,
+ in_display_none_subtree: bool,
+ ) -> Self {
+ use crate::css::computed_longhand_table::IN_DISPLAY_NONE_SUBTREE;
+ use crate::css::property_metadata::property_id as prop;
+ use crate::css::style_compute::{
+ animation_names_declare_css_animations, display_of, transition_values_declare_transitions,
+ };
+ let mut facts = Self {
+ display: pack_display(display_of(value_of(prop::DISPLAY))),
+ flags: 0,
+ };
+ facts.add_dependency_flags(dependency_flags);
+ facts.flags |= (u8::from(in_display_none_subtree) * IN_DISPLAY_NONE_SUBTREE)
+ | (u8::from(animation_names_declare_css_animations(value_of(prop::ANIMATION_NAME)))
+ * Self::DECLARES_CSS_ANIMATIONS)
+ | (u8::from(transition_values_declare_transitions(
+ value_of(prop::TRANSITION_PROPERTY),
+ value_of(prop::TRANSITION_DURATION),
+ value_of(prop::TRANSITION_DELAY),
+ )) * Self::DECLARES_TRANSITIONS);
+ facts
+ }
+
+ /// The computed `display`.
+ pub(in super::super) fn display(&self) -> crate::css::display::FfiDisplay {
+ unpack_display(self.display)
+ }
+
+ /// The dependency flags of the element's computation, without whether it is in a
+ /// `display: none` subtree.
+ pub(in super::super) fn dependency_flags(&self) -> u8 {
+ use crate::css::computed_longhand_table::IN_DISPLAY_NONE_SUBTREE;
+ self.flags & !(IN_DISPLAY_NONE_SUBTREE | Self::DECLARES_CSS_ANIMATIONS | Self::DECLARES_TRANSITIONS)
+ }
+
+ /// Adds `flags` to the dependency flags of the element's computation.
+ pub(in super::super) fn add_dependency_flags(&mut self, flags: u8) {
+ assert_eq!(
+ flags & (Self::DECLARES_CSS_ANIMATIONS | Self::DECLARES_TRANSITIONS),
+ 0,
+ "a computation's dependency flags leave the declaration bits clear"
+ );
+ self.flags |= flags;
+ }
+
+ /// Whether the element is `display: none` or inherits from one that is.
+ pub(in super::super) fn in_display_none_subtree(&self) -> bool {
+ self.flags & crate::css::computed_longhand_table::IN_DISPLAY_NONE_SUBTREE != 0
+ }
+
+ /// Whether the computed `animation-name` names any animation.
+ pub(in super::super) fn declares_css_animations(&self) -> bool {
+ self.flags & Self::DECLARES_CSS_ANIMATIONS != 0
+ }
+
+ /// Whether the computed `transition-*` values make any longhand transitionable.
+ pub(in super::super) fn declares_transitions(&self) -> bool {
+ self.flags & Self::DECLARES_TRANSITIONS != 0
+ }
+
+ /// The dependency flags the element's style publishes.
+ pub(in super::super) fn publication_dependency_flags(&self) -> u8 {
+ self.flags & !(Self::DECLARES_CSS_ANIMATIONS | Self::DECLARES_TRANSITIONS)
+ }
+}
+
+/// Which children of an element its new record restyles.
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(super) enum ChildImpact {
+ None,
+ /// Only the children that read the element's values of properties that do not inherit.
+ ResetReaders,
+ /// Only the custom properties it hands down moved: each child reads them anew, and computes
+ /// again where it substitutes one that moved.
+ CustomProperties,
+ /// Both of the above.
+ ResetReadersAndCustomProperties,
+ All,
+}
+
+// NB: The inherited groups are the inherited sets, which a child holding its parents set shares.
+const _: () = assert!(
+ crate::css::computed_values::INHERITED_SET_GROUPS.len()
+ == crate::css::style::computed::ENGINE_INHERITED_GROUP_COUNT
+);
+
+impl ChildImpact {
+ /// Which children of an element moving from the groups `old` to `new` restyle: all of them
+ /// where an inherited group moved, and the ones reading their parent's values of properties
+ /// that do not inherit where another did.
+ pub(super) fn of_groups(
+ new: &crate::css::computed_values::StyleGroups,
+ old: &crate::css::computed_values::StyleGroups,
+ ) -> Self {
+ let group_differs = |group: usize| {
+ let (new, old) = (new[group].as_ptr(), old[group].as_ptr());
+ // SAFETY: Both are live payloads of the group.
+ new != old && !unsafe { crate::css::computed_values::style_group_payloads_equal(group, new, old) }
+ };
+ let inherited = crate::css::style::computed::ENGINE_INHERITED_GROUP_COUNT;
+ // NB: The inherited bits and zoom beside the inherited groups reach the children as the groups do.
+ if !new.shares_inherited_groups_with(old)
+ && (new.inherited_values() != old.inherited_values() || (0..inherited).any(group_differs))
+ {
+ return Self::All;
+ }
+ // NB: The reset bits are read by the children reading their parent's reset values, as
+ // the box group's were.
+ if new.reset_bits() != old.reset_bits() {
+ return Self::ResetReaders;
+ }
+ match !new.shares_reset_groups_with(old) && (inherited..group_index::COUNT).any(group_differs) {
+ true => Self::ResetReaders,
+ false => Self::None,
+ }
+ }
+}
+
+impl RetainedState {
+ /// Whether `node`, holding `record`, reads its parent's values of properties that do not
+ /// inherit: its record does, or the keyframes of its animations say `inherit` for one.
+ pub(super) fn reads_parent_reset_values(&self, node: StyleNodeID, record: &Record) -> bool {
+ record.rare().reads.parent_reset_groups != 0 || self.keyframes_reading_parent_reset_values.contains(&node)
+ }
+}
+
+impl Record {
+ /// What the element's computation recorded and read beyond its values, which most elements
+ /// share with their siblings, and which the record's rare set holds beside its groups.
+ pub(in super::super) fn rare(&self) -> &Arc<RareStyleFacts> {
+ self.payloads.rare_facts().expect("a record's rare set holds its facts")
+ }
+
+ /// The custom declarations the element's cascade decided, as written, which a sample of its
+ /// animations resolves the ones reading an animated custom property from, and which its rare
+ /// set holds beside its groups.
+ pub(in super::super) fn custom_declarations(&self) -> Option<&CustomDeclarations> {
+ self.payloads.custom_declarations()
+ }
+
+ /// The custom properties the element holds, which its inherited set holds beside its groups.
+ pub(in super::super) fn custom_properties(
+ &self,
+ ) -> Option<&Arc<crate::css::custom_properties::CustomPropertyStore>> {
+ self.payloads.custom_properties()
+ }
+
+ /// The custom properties the element's children inherit.
+ pub(in super::super) fn inheritable_custom_properties(
+ &self,
+ ) -> Option<&Arc<crate::css::custom_properties::CustomPropertyStore>> {
+ match &self.rare().inheritable_custom_properties {
+ InheritableCustomProperties::Held => self.custom_properties(),
+ InheritableCustomProperties::Other(inheritable) => inheritable.as_ref(),
+ }
+ }
+
+ /// The identity of the custom-property environment the record was resolved in: that of the store it holds, or
+ /// zero where it holds none.
+ pub(in super::super) fn custom_property_environment(&self) -> u64 {
+ self.custom_properties()
+ .map_or(0, super::super::custom_property_environments::environment_identity)
+ }
+
+ /// The record holding what this one does, resolved in the custom-property environment of `store` instead.
+ pub(in super::super) fn in_custom_property_environment(
+ &self,
+ store: Option<Arc<crate::css::custom_properties::CustomPropertyStore>>,
+ ) -> Self {
+ let derived = Self::derived(self, &self.payloads);
+ Self {
+ payloads: derived.payloads.with_custom_properties(store.as_ref()),
+ ..derived
+ }
+ }
+
+ /// The groups holding the record's computed values, where groups hold them.
+ pub(in super::super) fn value_groups(&self) -> &crate::css::computed_values::StyleGroups {
+ match &self.rare().longhand_home {
+ LonghandHome::Groups => &self.payloads,
+ LonghandHome::SourceGroups(source) => &source.groups,
+ }
+ }
+
+ /// What the element's animations sampled over the style this record samples them over, where
+ /// it is a sample of them.
+ pub(in super::super) fn sample_of_animations(&self) -> Option<&Sample> {
+ match &self.rare().longhand_home {
+ LonghandHome::Groups => None,
+ LonghandHome::SourceGroups(source) => source.sample.as_deref(),
+ }
+ }
+
+ /// The computed value of `longhand`.
+ pub(in super::super) fn longhand(&self, longhand: LonghandID) -> &RetainedStyleValueData {
+ let groups = self.value_groups();
+ let property =
+ GroupValueLayout::get().resolved(longhand.property(), |property| self.longhand(LonghandID::new(property)));
+ let place = GroupValueLayout::get().place(LonghandID::new(property));
+ if let Some(field) = place.bit_field() {
+ return groups.style_bits().value(field);
+ }
+ crate::css::computed_values::value_at(
+ groups.group(crate::css::computed_values::StyleGroupIndex::new(place.group())),
+ place,
+ )
+ }
+
+ /// The value a group build reads for `property`: its recorded currentcolor-dependent specified
+ /// value where a drive did not evaluate it, else its computed value.
+ pub(in super::super) fn effective_value(&self, property: u16) -> &RetainedStyleValueData {
+ self.rare()
+ .value_facts
+ .value_read_in_place(property)
+ .unwrap_or_else(|| self.longhand(LonghandID::new(property)))
+ }
+
+ /// The recorded specified values of the longhands whose computed values depend on what the
+ /// element inherits.
+ pub(in super::super) fn inheritance_dependent_values(
+ &self,
+ ) -> impl Iterator<Item = (u16, &RetainedStyleValueData)> + Clone {
+ self.rare().value_facts.inheritance_dependent_values()
+ }
+
+ /// The color scheme the element's colors resolved against.
+ pub(in super::super) fn effective_color_scheme(&self) -> i16 {
+ self.rare().value_facts.effective_color_scheme()
+ }
+
+ /// The groups the children of an element holding the record start their values from.
+ pub(in super::super) fn group_seed(&self) -> GroupSeed<'_> {
+ GroupSeed::new(self.value_groups(), &self.rare().value_facts)
+ }
+
+ /// Whether the element holding the record generates boxes, or its descendants do: whether
+ /// they have styles.
+ pub(super) fn is_displayed(&self) -> bool {
+ !self.facts().display().is_none()
+ }
+
+ /// What the record's readers read of the element's style without its groups.
+ pub(in super::super) fn facts(&self) -> RecordFacts {
+ self.header.facts()
+ }
+
+ /// The identity of the slot holding the record, while one does.
+ pub(in super::super) fn installed_record(&self) -> Option<InstalledRecordID> {
+ self.header.installed_record()
+ }
+
+ /// The pseudo-elements of the element that generate a box.
+ pub(in super::super) fn pseudo_element_styles(&self) -> PseudoElementStyles {
+ self.rare().pseudo_element_styles
+ }
+
+ /// This record, styling the pseudo-elements of `styles`: itself where it does, otherwise a copy
+ /// sharing all it holds.
+ pub(in super::super) fn with_pseudo_element_styles(self: &Arc<Self>, styles: PseudoElementStyles) -> Arc<Self> {
+ if self.pseudo_element_styles() == styles {
+ return self.clone();
+ }
+ Arc::new(Self {
+ payloads: self
+ .payloads
+ .clone()
+ .with_rare_facts(
+ self.rare().with_pseudo_element_styles(styles),
+ self.custom_declarations().cloned(),
+ &[],
+ )
+ .with_custom_properties(self.custom_properties()),
+ header: RecordHeader::new(self.facts()),
+ })
+ }
+
+ /// This record, whose computation depends on `dependency_flags` too, as a test makes one.
+ #[cfg(test)]
+ pub(in super::super) fn with_test_dependency_flags(self: &Arc<Self>, dependency_flags: u8) -> Arc<Self> {
+ let mut facts = self.facts();
+ facts.add_dependency_flags(dependency_flags);
+ Arc::new(Self {
+ payloads: self.payloads.clone(),
+ header: RecordHeader::new(facts),
+ })
+ }
+
+ /// Name the identity of the slot that takes the record, and what a view of it depends on, and
+ /// answer whether it did: a record a fork's slot names already keeps that name.
+ #[must_use]
+ pub(in super::super) fn name_installed_record(&self, id: InstalledRecordID, view_dependency_flags: u8) -> bool {
+ self.settle_view_dependency_flags(view_dependency_flags);
+ self.header.name_installed_record(id)
+ }
+
+ /// A copy of the record sharing all it holds, which no slot names.
+ pub(in super::super) fn copy_without_a_name(&self) -> Self {
+ Self {
+ payloads: self.payloads.clone(),
+ header: RecordHeader::new(self.facts()),
+ }
+ }
+
+ /// Settle what a view of the record depends on for a holder no slot names it to.
+ pub(in super::super) fn settle_view_dependency_flags(&self, view_dependency_flags: u8) {
+ self.header
+ .set_holds_image_values(view_dependency_flags & computed::HOLDS_IMAGE_VALUES != 0);
+ }
+
+ /// What a view of the record depends on, as the slot holding it last settled it.
+ pub(in super::super) fn view_dependency_flags(&self) -> u8 {
+ computed::view_dependency_flags(&self.facts(), self.header.holds_image_values())
+ }
+
+ /// Forget the identity of the slot that let go of the record.
+ pub(in super::super) fn forget_installed_record(&self) {
+ self.header.forget_installed_record();
+ }
+
+ /// Whether `other` holds what this record does, the pseudo-elements it styles included.
+ pub(in super::super) fn holds_the_same_as(&self, other: &Record) -> bool {
+ self.pseudo_element_styles() == other.pseudo_element_styles() && self.holds_the_same_style_as(other)
+ }
+
+ /// Whether `other` holds the style this record does, whatever pseudo-elements either styles,
+ /// as a pass compares a record it computed with one it held before it settles them.
+ pub(in super::super) fn holds_the_same_style_as(&self, other: &Record) -> bool {
+ self.holds_the_same_besides_its_table_as(other)
+ && self.rare().value_facts.publication_equals(&other.rare().value_facts)
+ && self.holds_the_same_values_as(other)
+ && self.rare().table_flags.publication_equals(&other.rare().table_flags)
+ }
+
+ /// Whether `other` holds the computed values this record does.
+ fn holds_the_same_values_as(&self, other: &Record) -> bool {
+ let (mine, theirs) = (self.value_groups(), other.value_groups());
+ mine.iter()
+ .zip(theirs.iter())
+ .enumerate()
+ .all(|(group, (mine, theirs))| {
+ mine.as_ptr() == theirs.as_ptr()
+ // SAFETY: Both records hold a reference to each of their value groups.
+ || unsafe { crate::css::computed_values::hold_the_same_values(group, mine.as_ptr(), theirs.as_ptr()) }
+ })
+ }
+
+ /// Whether `other` holds the custom declarations this record does: the element's own, which
+ /// moving custom properties builds its custom properties from again. A name has one winner, so
+ /// the order they stand in says nothing, and what a declaration holds counts by value, as a
+ /// cascade makes the value of `initial` anew.
+ fn holds_the_same_custom_declarations_as(&self, other: &Record) -> bool {
+ match (&self.custom_declarations(), &other.custom_declarations()) {
+ (None, None) => true,
+ (Some(mine), Some(theirs)) => {
+ let same = |mine: &(CustomDeclaration, crate::css::style_value::RetainedStyleValueData),
+ theirs: &(CustomDeclaration, crate::css::style_value::RetainedStyleValueData)| {
+ mine.0 == theirs.0 && (mine.1.pointer() == theirs.1.pointer() || mine.1 == theirs.1)
+ };
+ Arc::ptr_eq(mine, theirs)
+ || (mine.len() == theirs.len()
+ && mine.iter().enumerate().all(|(index, declaration)| {
+ same(declaration, &theirs[index])
+ || theirs
+ .iter()
+ .any(|their_declaration| same(declaration, their_declaration))
+ }))
+ }
+ _ => false,
+ }
+ }
+
+ /// Whether `other` holds what this record does, its longhand table aside.
+ fn holds_the_same_besides_its_table_as(&self, other: &Record) -> bool {
+ let same_store =
+ |a: Option<&Arc<crate::css::custom_properties::CustomPropertyStore>>,
+ b: Option<&Arc<crate::css::custom_properties::CustomPropertyStore>>| match (a, b) {
+ (None, None) => true,
+ (Some(a), Some(b)) => Arc::ptr_eq(a, b) || a.holds_same_values_as(b),
+ _ => false,
+ };
+ self.payloads.current_color() == other.payloads.current_color()
+ && self.rare().custom_property_reads == other.rare().custom_property_reads
+ && self.rare().reads == other.rare().reads
+ && self.rare().counter_style_environment_identity == other.rare().counter_style_environment_identity
+ && self.holds_the_same_custom_declarations_as(other)
+ && self.rare().animation_name_scope == other.rare().animation_name_scope
+ && same_store(self.custom_properties(), other.custom_properties())
+ && same_store(
+ self.inheritable_custom_properties(),
+ other.inheritable_custom_properties(),
+ )
+ && self.payloads.holds_equal_payloads_as(&other.payloads)
+ && self.facts() == other.facts()
+ }
+}
+
+impl Record {
+ /// The record of a style the host computed into `values`, with the flags `flags` and the
+ /// dependency flags `dependency_flags` its computation settled beside them, which holds the
+ /// default groups until the host builds its own. No element computes against it.
+ pub(in super::super) fn from_values(
+ values: crate::css::computed_values::GroupValues<'_>,
+ flags: crate::css::computed_longhand_table::LonghandTableFlags,
+ dependency_flags: u8,
+ defaults: &crate::css::computed_values::DefaultGroups,
+ ) -> Self {
+ let facts = RecordFacts::of_values(|property| values.value(property), dependency_flags, false);
+ let value_facts = values.facts().clone();
+ let style_bits = values.style_bits();
+ // NB: The groups hold the values in their value arrays and in their payload handles.
+ let value_groups = values.into_groups();
+ Self {
+ payloads: defaults
+ .groups()
+ .clone()
+ .with_style_bits(style_bits)
+ .with_rare_facts(
+ Arc::new(RareStyleFacts::of_host_style(flags, value_facts, value_groups, 0)),
+ None,
+ &[],
+ )
+ .with_custom_properties(None),
+ header: RecordHeader::new(facts),
+ }
+ }
+
+ /// The record of a style holding `value_of(property)` for each longhand, as a test makes one.
+ #[cfg(test)]
+ pub(crate) fn of_test_values(value_of: impl Fn(u16) -> RetainedStyleValueData) -> Self {
+ use crate::css::property_metadata::{FIRST_LONGHAND_PROPERTY_ID, LAST_LONGHAND_PROPERTY_ID};
+ let defaults = crate::css::computed_values::DefaultGroups::default();
+ crate::css::computed_values::with_default_seed(&defaults, |seed| {
+ let mut writer = crate::css::computed_values::GroupValuesWriter::seeded_for_child(
+ seed,
+ seed,
+ std::iter::empty(),
+ crate::css::computed_longhand_table::LonghandTableFlags::empty(),
+ 0,
+ );
+ for property in FIRST_LONGHAND_PROPERTY_ID..=LAST_LONGHAND_PROPERTY_ID {
+ let value = value_of(property);
+ if GroupValueLayout::get().holds_value(LonghandID::new(property)) && !value.pointer().is_null() {
+ writer.set(property, value);
+ }
+ }
+ let (values, flags, dependency_flags) = writer.finish(&[]);
+ Self::from_values(values, flags, dependency_flags, &defaults)
+ })
+ }
+
+ /// The record of a style the host made, holding `payloads`, whose computed values are the
+ /// initial ones of `initial`, which it keeps the groups of. No element computes against it.
+ pub(in super::super) fn of_initial(
+ initial: &InitialStyle,
+ payloads: &crate::css::computed_values::StyleGroups,
+ counter_style_environment_identity: u64,
+ ) -> Self {
+ Self {
+ payloads: payloads
+ .clone()
+ .with_rare_facts(
+ Arc::new(RareStyleFacts::of_host_style(
+ initial.flags.clone(),
+ initial.value_facts.clone(),
+ initial.payloads.clone(),
+ counter_style_environment_identity,
+ )),
+ None,
+ &[],
+ )
+ .with_custom_properties(None),
+ header: RecordHeader::new(RecordFacts::of_values(
+ |property| initial.longhand(LonghandID::new(property)),
+ initial.dependency_flags,
+ false,
+ )),
+ }
+ }
+
+ /// Whether the record's values derive from the metrics of the first available font of the
+ /// element or its parent, which a load filling one of its faces in moves: a length relative to
+ /// one of them, or a `font-size-adjust`, which sizes the font by them. A `line-height: normal`
+ /// does not: its used value is read through the cascade.
+ pub(super) fn reads_font_metrics(&self) -> bool {
+ use crate::css::property_metadata::property_id;
+ use crate::css::style_compute::keyword;
+ let is_keyword = |property, expected| {
+ matches!(
+ self.longhand(LonghandID::new(property)).optional_data(),
+ Some(crate::css::style_value::StyleValueData::Keyword { keyword }) if *keyword == expected
+ )
+ };
+ self.rare().reads.reads_font_metric_lengths || !is_keyword(property_id::FONT_SIZE_ADJUST, keyword::NONE)
+ }
+
+ /// The record of a style derived from that of `source` holding `payloads` in place of its
+ /// groups, such as an anonymous box's or a sample of animations over it, which holds the
+ /// longhands of `source`.
+ pub(in super::super) fn derived(source: &Record, payloads: &crate::css::computed_values::StyleGroups) -> Self {
+ Self::derived_with(source, payloads, |_| {})
+ }
+
+ /// The record `derived` answers, with its rare facts as `adjust` leaves them.
+ fn derived_with(
+ source: &Record,
+ payloads: &crate::css::computed_values::StyleGroups,
+ adjust: impl FnOnce(&mut RareStyleFacts),
+ ) -> Self {
+ let mut rare = RareStyleFacts::clone(source.rare());
+ if matches!(rare.longhand_home, LonghandHome::Groups) {
+ rare.longhand_home = LonghandHome::SourceGroups(DerivedSource::of(source.payloads.clone()));
+ }
+ adjust(&mut rare);
+ Self {
+ payloads: payloads
+ .clone()
+ .with_current_color(source.payloads.current_color())
+ .with_rare_facts(Arc::new(rare), source.custom_declarations().cloned(), &[])
+ .with_custom_properties(source.custom_properties()),
+ header: RecordHeader::new(source.facts()),
+ }
+ }
+}
+
+impl Record {
+ /// The record of a sample of the animations of an element over the installed record `base`,
+ /// holding `payloads`, the groups of `base` with `animated_overlay` composed into them, whose
+ /// views depend on `dependency_flags`, named `identity`.
+ pub(in super::super) fn sample(
+ base: &Arc<Record>,
+ payloads: &crate::css::computed_values::StyleGroups,
+ animated_overlay: Arc<crate::css::animated_overlay::AnimatedOverlay>,
+ dependency_flags: u8,
+ identity: computed::FinalStyleRecordID,
+ ) -> Self {
+ Self::derived_with(base, payloads, |rare| {
+ let LonghandHome::SourceGroups(source) = &mut rare.longhand_home else {
+ unreachable!("a derived record holds the longhands of its source");
+ };
+ source.sample = Some(Box::new(Sample {
+ base: base.clone(),
+ animated_overlay,
+ dependency_flags,
+ identity,
+ }));
+ })
+ }
+}
+
+impl RetainedState {
+ /// Install the record of a style the host made holding `payloads`, whose computed values are
+ /// the initial ones, and answer its identity. Nothing holds
+ /// the record yet: the next sweep frees it unless a holder pins it first.
+ pub(in super::super) fn install_initial_derived_record(
+ &mut self,
+ payloads: &crate::css::computed_values::StyleGroups,
+ counter_style_environment_identity: u64,
+ ) -> computed::FinalStyleRecordID {
+ let initial = self
+ .live_style
+ .as_ref()
+ .map(|live| live.initial.clone())
+ .expect("a style the host made inherits from one a pass styled");
+ let record = Record::of_initial(&initial, payloads, counter_style_environment_identity);
+ self.install_new_record(Arc::new(record))
+ }
+
+ /// Install the record of a style derived from that of the record `source` is or composes
+ /// over, holding `payloads`, and answer its identity, or none
+ /// where `source` is not a record the engine installed. Nothing holds the record yet: the next
+ /// sweep frees it unless a holder pins it first.
+ pub(in super::super) fn install_record_derived_from(
+ &mut self,
+ source: computed::FinalStyleRecordID,
+ payloads: &crate::css::computed_values::StyleGroups,
+ ) -> Option<computed::FinalStyleRecordID> {
+ let source = self.computed_group_sets.installed_base_record(source)?.clone();
+ Some(self.install_record_derived(&source, payloads, None))
+ }
+
+ /// Install the record of a style derived from `source`, holding `payloads`, in the counter style
+ /// registry `counter_style_environment_identity` names where it names one other than the
+ /// source's, and answer its identity. Nothing holds the
+ /// record yet: the next sweep frees it unless a holder pins it first.
+ pub(in super::super) fn install_record_derived(
+ &mut self,
+ source: &Record,
+ payloads: &crate::css::computed_values::StyleGroups,
+ counter_style_environment_identity: Option<u64>,
+ ) -> computed::FinalStyleRecordID {
+ let record = Arc::new(Record::derived_with(source, payloads, |rare| {
+ if let Some(identity) = counter_style_environment_identity {
+ rare.counter_style_environment_identity = identity;
+ }
+ }));
+ self.install_new_record(record)
+ }
+
+ fn install_new_record(&mut self, record: Arc<Record>) -> computed::FinalStyleRecordID {
+ self.computed_group_sets.install_record(&record, || {
+ computed::record_dependency_flags(&record.facts(), &record.payloads)
+ })
+ }
+}
+
+impl Record {
+ /// Counts what `record` holds, by owner, the first time the report reaches it: the record
+ /// itself, its groups with their values, and its custom properties.
+ pub(in super::super) fn report_memory(record: &Arc<Record>, report: &mut MemoryReport) {
+ use crate::heap_size::HeapSize;
+ if !report.sizer.first_sight(Arc::as_ptr(record)) {
+ return;
+ }
+ report.add(
+ MemoryOwner::Records,
+ crate::heap_size::ARC_HEADER_BYTES + size_of::<Record>(),
+ );
+ // NB: The rare facts count once, by the first record reaching them.
+ if report.sizer.first_sight(Arc::as_ptr(record.rare())) {
+ let rare = record.rare();
+ let custom_property_reads = match &rare.custom_property_reads {
+ crate::css::style::custom_property_cascade::LonghandCustomPropertyReads::Named(names) => {
+ names.heap_size(&mut report.sizer)
+ }
+ _ => 0,
+ };
+ report.add(
+ MemoryOwner::Records,
+ crate::heap_size::ARC_HEADER_BYTES + size_of::<RareStyleFacts>() + custom_property_reads,
+ );
+ report.count(MemoryOwner::GroupValueFacts, &rare.value_facts);
+ }
+ // NB: The custom declarations count once, by the first record reaching them.
+ let custom_declarations = record
+ .custom_declarations()
+ .map_or(0, |declarations| declarations.heap_size(&mut report.sizer));
+ report.add(MemoryOwner::Records, custom_declarations);
+ // NB: The group sets count once, by the first record reaching them.
+ for (set, bytes) in record.payloads.set_allocations() {
+ if report.sizer.first_sight(set) {
+ report.add(MemoryOwner::Records, bytes);
+ }
+ }
+ // NB: A group's allocation holds its computed values after its payload, and the style
+ // values those hold count once, the first time any owner reaches them.
+ let mut payloads = 0;
+ for (group, payload) in record.payloads.iter().enumerate() {
+ if !report.sizer.first_sight(payload.as_ptr()) {
+ continue;
+ }
+ payloads += crate::css::computed_values::group_payload_allocation_bytes(group, payload.as_ptr());
+ // SAFETY: The record holds a reference to each of its groups.
+ payloads += unsafe { crate::css::computed_values::group_values(group, payload.as_ptr()) }
+ .heap_size(&mut report.sizer);
+ }
+ report.add(MemoryOwner::Payloads, payloads);
+ if let Some(store) = record.custom_properties() {
+ report.count(MemoryOwner::CustomProperties, store);
+ }
+ if let InheritableCustomProperties::Other(inheritable) = &record.rare().inheritable_custom_properties {
+ report.count(MemoryOwner::CustomProperties, inheritable);
+ }
+ }
+}
+
+impl crate::heap_size::HeapSize for CustomDeclaration {
+ fn heap_size(&self, _: &mut crate::heap_size::HeapSizer) -> usize {
+ 0
+ }
+}
+
+impl crate::heap_size::HeapSize for ContainerVerdict {
+ fn heap_size(&self, _: &mut crate::heap_size::HeapSizer) -> usize {
+ crate::heap_size::vec_bytes(&self.effects)
+ }
+}
+
+impl Held {
+ fn report_memory(&self, report: &mut MemoryReport) {
+ Record::report_memory(&self.record, report);
+ report.count(MemoryOwner::RetainedSlots, &self.matches);
+ }
+}
+
+fn report_pseudo_element_records_memory(records: &PseudoElementRecords, report: &mut MemoryReport) {
+ report.add(MemoryOwner::RetainedSlots, crate::heap_size::small_vec_bytes(records));
+ for (_, record) in records {
+ Record::report_memory(record, report);
+ }
+}
+
+/// The custom properties an element holds or hands down, where it holds any.
+pub(super) type HeldCustomProperties = Option<Arc<crate::css::custom_properties::CustomPropertyStore>>;
+
+/// The custom properties an element holds or hands down, as a pass reads them: borrowed from its
+/// record, unless its animations sampled them.
+pub(super) type BorrowedCustomProperties<'a> = Option<Cow<'a, Arc<crate::css::custom_properties::CustomPropertyStore>>>;
+
+pub(super) type PseudoElementRecords = smallvec::SmallVec<[(u8, Arc<Record>); 2]>;
+
+/// One element's record, with the identity it shares under. Elements holding one record need not
+/// share an identity: a record reused for an equal cascade says nothing of the elements' selectors.
+/// The rule index entries an element matched, in index order, behind one thin pointer, which the
+/// elements that matched alike share.
+pub(in super::super) type MatchList = Arc<Box<[u32]>>;
+
+#[derive(Clone)]
+pub(super) struct Held {
+ record: Arc<Record>,
+ sharing_identity: StyleNodeID,
+ /// The rule index entries the element matched, in index order, where the pass kept them.
+ matches: Option<MatchList>,
+}
+
+/// What the passes before kept of one element that few elements have.
+#[derive(Clone, Default)]
+struct RareRetained {
+ pseudo_element_records: PseudoElementRecords,
+ /// What the container conditions of the element's matches read of its containers.
+ container_reads: Option<Arc<ContainerVerdict>>,
+}
+
+/// What the passes before kept of one element.
+#[derive(Clone, Default)]
+struct RetainedSlot {
+ held: Option<Held>,
+ /// The element's pseudo-element records and container reads, where it has either.
+ rare: Option<Box<RareRetained>>,
+}
+
+impl RetainedSlot {
+ fn is_empty(&self) -> bool {
+ self.held.is_none() && self.rare.is_none()
+ }
+
+ fn pseudo_element_records(&self) -> &[(u8, Arc<Record>)] {
+ self.rare
+ .as_ref()
+ .map_or(&[], |rare| rare.pseudo_element_records.as_slice())
+ }
+
+ fn container_reads(&self) -> Option<&Arc<ContainerVerdict>> {
+ self.rare.as_ref()?.container_reads.as_ref()
+ }
+}
+
+// NB: Every element a pass styled has one of these.
+const _: () = assert!(size_of::<RetainedSlot>() == 32);
+
+/// How many element slots a page of retained records holds.
+const RETAINED_PAGE_SIZE: usize = 256;
+
+/// How many element slots the first page of retained records holds at least: a document of a few
+/// elements holds few slots, and the first page doubles as its document grows.
+const RETAINED_FIRST_PAGE_MIN_SIZE: usize = 8;
+
+fn empty_retained_page(length: usize) -> Arc<[RetainedSlot]> {
+ (0..length).map(|_| RetainedSlot::default()).collect()
+}
+
+/// The records the passes before kept, by element, which a pass that restyles some elements reads
+/// for the others.
+///
+/// A fork of the render state takes the records in pages it shares with the state it forked until
+/// either side writes one: forking costs a reference count per page, and the first write to a
+/// page after a fork copies the page alone.
+#[derive(Clone, Default)]
+pub(super) struct RetainedRecords {
+ /// Each page holds `RETAINED_PAGE_SIZE` slots but for the first, until the page after it exists.
+ pages: Vec<Arc<[RetainedSlot]>>,
+ /// The root font inputs the last pass that styled the document element resolved
+ /// root-relative lengths against, with that element. A record reads the metrics of its first
+ /// available font through its cascade, which a load filling one of its faces in moves, so what
+ /// the descendants resolved against is kept as the pass found it rather than read again from
+ /// the record.
+ root_font: Option<(StyleNodeID, super::compute::RootFontInputs)>,
+}
+
+impl RetainedRecords {
+ /// Counts the pages and what their slots hold, by owner.
+ pub(super) fn report_memory(&self, report: &mut MemoryReport) {
+ report.add(MemoryOwner::RetainedSlots, crate::heap_size::vec_bytes(&self.pages));
+ for page in &self.pages {
+ if !report.sizer.first_sight(page.as_ptr()) {
+ continue;
+ }
+ report.add(
+ MemoryOwner::RetainedSlots,
+ crate::heap_size::ARC_HEADER_BYTES + size_of_val::<[RetainedSlot]>(page),
+ );
+ for slot in page.iter() {
+ if let Some(held) = &slot.held {
+ report.styled_elements += 1;
+ held.report_memory(report);
+ }
+ if let Some(rare) = &slot.rare {
+ report.add(MemoryOwner::RetainedSlots, size_of::<RareRetained>());
+ report_pseudo_element_records_memory(&rare.pseudo_element_records, report);
+ report.count(MemoryOwner::RetainedSlots, &rare.container_reads);
+ }
+ }
+ }
+ }
+
+ /// Keep the root font inputs a pass that styled the document element `node` resolved against.
+ pub(super) fn keep_root_font(&mut self, node: StyleNodeID, root_font: super::compute::RootFontInputs) {
+ self.root_font = Some((node, root_font));
+ }
+
+ /// Whether the style of `node`, its own or one of its pseudo-elements', derives from the
+ /// metrics of a first available font, or is not known not to, having no record.
+ pub(super) fn reads_font_metrics(&self, node: StyleNodeID) -> bool {
+ self.get(node).is_none_or(|record| record.reads_font_metrics())
+ || self
+ .pseudo_element_records(node)
+ .iter()
+ .any(|(_, record)| record.reads_font_metrics())
+ }
+
+ fn slot(&self, slot: usize) -> Option<&RetainedSlot> {
+ self.pages
+ .get(slot / RETAINED_PAGE_SIZE)?
+ .get(slot % RETAINED_PAGE_SIZE)
+ }
+
+ /// The slot, for writing, which copies its page where a fork shares it.
+ fn slot_mut(&mut self, slot: usize) -> Option<&mut RetainedSlot> {
+ let page = self.pages.get_mut(slot / RETAINED_PAGE_SIZE)?;
+ Arc::make_mut(page).get_mut(slot % RETAINED_PAGE_SIZE)
+ }
+
+ /// Make room for `slot_count` elements.
+ fn reserve(&mut self, slot_count: usize) {
+ let first_page_length = slot_count
+ .next_power_of_two()
+ .clamp(RETAINED_FIRST_PAGE_MIN_SIZE, RETAINED_PAGE_SIZE);
+ match self.pages.first_mut() {
+ Some(first) if first.len() < first_page_length => {
+ let mut slots = Vec::with_capacity(first_page_length);
+ slots.extend_from_slice(first);
+ slots.resize_with(first_page_length, RetainedSlot::default);
+ *first = slots.into();
+ }
+ None if slot_count != 0 => self.pages.push(empty_retained_page(first_page_length)),
+ _ => {}
+ }
+ let page_count = slot_count.div_ceil(RETAINED_PAGE_SIZE);
+ while self.pages.len() < page_count {
+ self.pages.push(empty_retained_page(RETAINED_PAGE_SIZE));
+ }
+ }
+
+ fn held(&self, node: StyleNodeID) -> Option<&Held> {
+ self.slot(node.element_slot())?.held.as_ref()
+ }
+
+ pub(super) fn get(&self, node: StyleNodeID) -> Option<&Arc<Record>> {
+ Some(&self.held(node)?.record)
+ }
+
+ /// The rule index entries `node` matched, where the passes kept them.
+ pub(super) fn matches_of(&self, node: StyleNodeID) -> Option<&MatchList> {
+ self.held(node)?.matches.as_ref()
+ }
+
+ pub(super) fn pseudo_element_records(&self, node: StyleNodeID) -> &[(u8, Arc<Record>)] {
+ self.slot(node.element_slot())
+ .map_or(&[], RetainedSlot::pseudo_element_records)
+ }
+
+ /// What the container conditions of the rules `node` matched, its pseudo-elements' included,
+ /// read of its containers, where it matched any rule applying under container conditions.
+ pub(super) fn container_reads(&self, node: StyleNodeID) -> Option<&Arc<ContainerVerdict>> {
+ self.slot(node.element_slot())?.container_reads()
+ }
+
+ /// Keep the records a pass computed for the elements of `styled`, over the ones they replace,
+ /// emptying their cells for the next pass, and note in `changed` the elements whose records,
+ /// or pseudo-element records, are not the ones they held. The records replaced go to
+ /// `replaced`, to drop wherever is convenient.
+ pub(super) fn absorb(
+ &mut self,
+ cells: &mut RecordCells,
+ styled: &[StyleNodeID],
+ mut changed: Option<&mut Vec<StyleNodeID>>,
+ replaced: &mut Replaced,
+ ) {
+ self.reserve(cells.slot_count);
+ // The copies of the records the pass computed that style the pseudo-elements their
+ // elements do, one per record and set of pseudo-elements, which elements sharing a style
+ // share.
+ let mut with_pseudo_element_styles: HashMap<(usize, PseudoElementStyles), Arc<Record>> = HashMap::default();
+ for node in styled {
+ let slot = node.element_slot();
+ let Some(page) = cells.pages[slot / CELL_PAGE_SIZE].get_mut() else {
+ continue;
+ };
+ let cell = slot % CELL_PAGE_SIZE;
+ if let Some(mut held) = page.held[cell].take() {
+ let container_reads = page.container_reads[cell].take();
+ let reads_containers = container_reads.is_some();
+ let mut pseudo_element_records = page.pseudo_element_records[cell].take().unwrap_or_default();
+ let styles = PseudoElementStyles::of(&pseudo_element_records);
+ if held.record.pseudo_element_styles() != styles {
+ held.record = with_pseudo_element_styles
+ .entry((Arc::as_ptr(&held.record) as usize, styles))
+ .or_insert_with(|| held.record.with_pseudo_element_styles(styles))
+ .clone();
+ }
+ let retained = self
+ .slot_mut(slot)
+ .expect("the records have room for every styled element");
+ // NB: Where the records are installed, one holding what the record it replaces
+ // does gives way to it, which the host holds already.
+ if let Some(changed) = changed.as_deref_mut() {
+ let old = retained.pseudo_element_records();
+ let mut same_pseudo_element_records = old.len() == pseudo_element_records.len();
+ for (new, old) in pseudo_element_records.iter_mut().zip(old) {
+ if new.0 != old.0 {
+ same_pseudo_element_records = false;
+ } else if !Arc::ptr_eq(&new.1, &old.1) {
+ match new.1.holds_the_same_as(&old.1) {
+ true => new.1 = old.1.clone(),
+ false => same_pseudo_element_records = false,
+ }
+ }
+ }
+ let same_record = match &retained.held {
+ Some(old) if Arc::ptr_eq(&old.record, &held.record) => true,
+ Some(old) if held.record.holds_the_same_as(&old.record) => {
+ held.record = old.record.clone();
+ true
+ }
+ _ => false,
+ };
+ // What an element's container conditions read is the host's to record as it
+ // installs the element's record, which it does again where they read anew.
+ if !same_record || !same_pseudo_element_records || reads_containers {
+ changed.push(*node);
+ }
+ }
+ if retained
+ .held
+ .as_ref()
+ .is_some_and(|old| !old.record.is_displayed() && held.record.is_displayed())
+ {
+ replaced.revealed.push(*node);
+ }
+ replaced.records.extend(retained.held.replace(held));
+ let mut rare = retained.rare.take();
+ let replaced_pseudo_element_records = rare
+ .as_mut()
+ .map(|rare| std::mem::take(&mut rare.pseudo_element_records))
+ .unwrap_or_default();
+ if !pseudo_element_records.is_empty() || container_reads.is_some() {
+ let mut rare = rare.unwrap_or_default();
+ rare.pseudo_element_records = pseudo_element_records;
+ rare.container_reads = container_reads;
+ retained.rare = Some(rare);
+ }
+ if !replaced_pseudo_element_records.is_empty() {
+ replaced.pseudo_element_records.push(replaced_pseudo_element_records);
+ }
+ }
+ }
+ cells.release();
+ }
+
+ /// Renumber the matches the records hold for a rebuilt rule index, where `renumbering` has the
+ /// entry standing for each one of the index before. An element that matched an entry the
+ /// rebuilt index lost holds no matches, and is matched against the whole index when restyled.
+ pub(super) fn renumber_matches(&mut self, renumbering: &[Option<u32>]) {
+ // Elements sharing a style hold one list, which they keep sharing. The lists renumbered
+ // are kept until the end, so that no other list takes the place of one of them.
+ let mut renumbered: HashMap<*const u32, Option<MatchList>> = HashMap::default();
+ let mut originals: Vec<MatchList> = Vec::new();
+ for page in &mut self.pages {
+ // NB: A page holding no matches is left to the fork it may be shared with.
+ if !page
+ .iter()
+ .any(|slot| slot.held.as_ref().is_some_and(|held| held.matches.is_some()))
+ {
+ continue;
+ }
+ for held in Arc::make_mut(page).iter_mut().filter_map(|slot| slot.held.as_mut()) {
+ let Some(matches) = held.matches.take() else {
+ continue;
+ };
+ held.matches = renumbered
+ .entry(matches.as_ptr())
+ .or_insert_with(|| {
+ // A list naming no entry that moved is kept as it is.
+ if matches
+ .iter()
+ .all(|&entry| renumbering.get(entry as usize).copied().flatten() == Some(entry))
+ {
+ return Some(Arc::clone(&matches));
+ }
+ matches
+ .iter()
+ .map(|&entry| renumbering.get(entry as usize).copied().flatten())
+ .collect::<Option<Vec<u32>>>()
+ .map(|mut new| {
+ new.sort_unstable();
+ new.dedup();
+ Arc::new(new.into_boxed_slice())
+ })
+ })
+ .clone();
+ originals.push(matches);
+ }
+ }
+ }
+
+ /// Have `node` hold `installed` in place of its record at the address `own`, which holds what
+ /// `installed` does, where it still holds that record.
+ pub(super) fn adopt(&mut self, node: StyleNodeID, own: usize, installed: Arc<Record>) {
+ let slot = node.element_slot();
+ if !self
+ .slot(slot)
+ .and_then(|retained| retained.held.as_ref())
+ .is_some_and(|held| Arc::as_ptr(&held.record) as usize == own)
+ {
+ return;
+ }
+ if let Some(held) = self.slot_mut(slot).and_then(|retained| retained.held.as_mut()) {
+ held.record = installed;
+ }
+ }
+
+ /// Forget the record of an element that left the tree.
+ pub(super) fn forget(&mut self, node: StyleNodeID) {
+ let slot = node.element_slot();
+ if self.slot(slot).is_some_and(|retained| !retained.is_empty())
+ && let Some(retained) = self.slot_mut(slot)
+ {
+ *retained = RetainedSlot::default();
+ }
+ }
+}
+
+/// The records a pass replaced.
+#[derive(Default)]
+pub(super) struct Replaced {
+ records: Vec<Held>,
+ pseudo_element_records: Vec<PseudoElementRecords>,
+ /// The elements whose records the pass moved from one that is not displayed to one that is.
+ pub(super) revealed: Vec<StyleNodeID>,
+}
+
+impl Replaced {
+ /// How many records, or sets of pseudo-element records, were replaced.
+ pub(super) fn len(&self) -> usize {
+ self.records.len() + self.pseudo_element_records.len()
+ }
+
+ /// Drop every record replaced, keeping the room they took.
+ pub(super) fn clear(&mut self) {
+ self.records.clear();
+ self.pseudo_element_records.clear();
+ self.revealed.clear();
+ }
+}
+
+/// The cells a pass writes the records it computes to, by element slot.
+#[derive(Default)]
+pub(super) struct RecordCells {
+ /// How many elements the cells have room for.
+ slot_count: usize,
+ /// The cells of the elements, by page of `CELL_PAGE_SIZE` element slots: only the pages a
+ /// pass writes to are made, as it first writes to them, and they go once their records are
+ /// kept, so the cells take no room between passes.
+ pages: Vec<std::sync::OnceLock<Box<CellPage>>>,
+}
+
+/// How many elements a page of record cells holds.
+const CELL_PAGE_SIZE: usize = 64;
+
+/// The record cells of `CELL_PAGE_SIZE` elements.
+struct CellPage {
+ /// Elements that share a style hold one record.
+ held: [WriteOnce<Held>; CELL_PAGE_SIZE],
+ /// The records of each element's pseudo-elements that generate a box.
+ pseudo_element_records: [WriteOnce<PseudoElementRecords>; CELL_PAGE_SIZE],
+ /// What the container conditions of each element's matches read of its containers, where it
+ /// matched a rule applying under container conditions. An element's own, not its record's:
+ /// elements whose cascades decide alike share a record, but not their containers.
+ container_reads: [WriteOnce<Arc<ContainerVerdict>>; CELL_PAGE_SIZE],
+}
+
+impl Default for CellPage {
+ fn default() -> Self {
+ Self {
+ held: std::array::from_fn(|_| WriteOnce::default()),
+ pseudo_element_records: std::array::from_fn(|_| WriteOnce::default()),
+ container_reads: std::array::from_fn(|_| WriteOnce::default()),
+ }
+ }
+}
+
+impl RecordCells {
+ /// Counts the cells and what a pass left in them, by owner.
+ pub(super) fn report_memory(&self, report: &mut MemoryReport) {
+ let pages = self.pages.iter().filter_map(std::sync::OnceLock::get);
+ report.add(
+ MemoryOwner::RecordCells,
+ crate::heap_size::vec_bytes(&self.pages) + pages.clone().count() * size_of::<CellPage>(),
+ );
+ for page in pages {
+ for held in page.held.iter().filter_map(WriteOnce::get) {
+ held.report_memory(report);
+ }
+ for records in page.pseudo_element_records.iter().filter_map(WriteOnce::get) {
+ report_pseudo_element_records_memory(records, report);
+ }
+ }
+ }
+
+ /// Make room for `slot_count` elements.
+ pub(super) fn reserve(&mut self, slot_count: usize) {
+ self.slot_count = self.slot_count.max(slot_count);
+ let pages = slot_count.div_ceil(CELL_PAGE_SIZE);
+ if self.pages.len() < pages {
+ self.pages.resize_with(pages, std::sync::OnceLock::new);
+ }
+ }
+
+ fn page(&self, slot: usize) -> Option<&CellPage> {
+ self.pages.get(slot / CELL_PAGE_SIZE)?.get().map(|page| &**page)
+ }
+
+ /// The page holding the cells of the element in `slot`, to write them, made where it is not.
+ fn to_write(&self, slot: usize) -> &CellPage {
+ self.pages[slot / CELL_PAGE_SIZE].get_or_init(Box::default)
+ }
+
+ fn held(&self, slot: usize) -> Option<&Held> {
+ self.page(slot)?.held[slot % CELL_PAGE_SIZE].get()
+ }
+
+ fn pseudo_element_records(&self, slot: usize) -> Option<&PseudoElementRecords> {
+ self.page(slot)?.pseudo_element_records[slot % CELL_PAGE_SIZE].get()
+ }
+
+ fn container_reads(&self, slot: usize) -> Option<&Arc<ContainerVerdict>> {
+ self.page(slot)?.container_reads[slot % CELL_PAGE_SIZE].get()
+ }
+
+ /// Lets go of the pages the cells were written to.
+ fn release(&mut self) {
+ for page in &mut self.pages {
+ page.take();
+ }
+ }
+}
+
+/// The records of a pass, falling back to the records the passes before kept, and then to the
+/// installed record of an element no pass computed, so its descendants still compute against a
+/// style.
+///
+/// An element whose animations the host composes over the record it holds hands its children the
+/// composition: they inherit the animated values.
+#[derive(Clone, Copy)]
+pub(super) struct Records<'a> {
+ state: &'a RetainedState,
+ cells: &'a RecordCells,
+ previous: Option<&'a RetainedRecords>,
+ /// What says that the record an element holds and its record here hold equal values, where
+ /// it then hands its children the composition the host lays over the record it holds, as one
+ /// a reference pass computed anew does, custom property stores of its own included.
+ composes_over_equal_records: Option<fn(&Record, &Record) -> bool>,
+}
+
+impl<'a> Records<'a> {
+ /// The root font inputs the last pass that styled the document element `node` resolved
+ /// against, where one did.
+ pub(super) fn kept_root_font(&self, node: StyleNodeID) -> Option<super::compute::RootFontInputs> {
+ let (kept, root_font) = self.previous?.root_font?;
+ (kept == node).then_some(root_font)
+ }
+
+ pub(super) fn new(state: &'a RetainedState, cells: &'a RecordCells, previous: Option<&'a RetainedRecords>) -> Self {
+ Self {
+ state,
+ cells,
+ previous,
+ composes_over_equal_records: None,
+ }
+ }
+
+ /// These records, handing children the composition over a record the host holds that holds
+ /// values equal to an element's record here, as `equal` says.
+ pub(super) fn composing_over_equal_records(self, equal: fn(&Record, &Record) -> bool) -> Self {
+ Self {
+ composes_over_equal_records: Some(equal),
+ ..self
+ }
+ }
+
+ /// The view of the composition of the animations of `node` over the record it holds, where the
+ /// host composes them over that record, values of running transitions included: a child
+ /// inherits them as it inherits any animated value.
+ ///
+ /// NB: A transition of the child decides against the after-change style, which inherits the
+ /// parent's after-change style: the decision takes the value beneath the transitions of
+ /// the ancestor the child inherits it from, as the records mark the values they inherit.
+ pub(super) fn composition(&self, node: StyleNodeID) -> Option<computed::StyleRecordView<'a>> {
+ let sets = &self.state.computed_group_sets;
+ let record = self.get_shared(node)?;
+ if let Some(view) = sets.composition_over_record(node, record) {
+ return Some(view);
+ }
+ let equal = self.composes_over_equal_records?;
+ let held = sets.held_record(node).filter(|held| equal(held, record))?;
+ sets.composition_over_record(node, held)
+ }
+
+ /// The custom properties `node` hands down and the ones it holds, here or as it is installed,
+ /// which an inheriting lookup reads: those its animations sampled, where the host sampled them
+ /// over the environment of the record it holds.
+ pub(super) fn custom_stores_of(
+ &self,
+ node: StyleNodeID,
+ ) -> Option<(BorrowedCustomProperties<'a>, BorrowedCustomProperties<'a>)> {
+ let sets = &self.state.computed_group_sets;
+ let record = match self.get_shared(node) {
+ Some(record) => record,
+ None => sets.installed_base_record(sets.assigned_style_record(node)?)?,
+ };
+ // NB: Only an element whose animations sampled custom properties asks whether its record
+ // holds the ones they were sampled over, which compares the records.
+ if let Some(sampled) = self.sampled_custom_properties(node)
+ && self.samples_custom_properties_of(node, record)
+ {
+ return Some((
+ self.state
+ .inheritable_custom_property_store(sampled.as_ref(), None)
+ .map(|store| Cow::Owned(store.into_owned())),
+ sampled.map(Cow::Owned),
+ ));
+ }
+ Some((
+ record.inheritable_custom_properties().map(Cow::Borrowed),
+ record.custom_properties().map(Cow::Borrowed),
+ ))
+ }
+
+ /// Whether the custom properties the host sampled the animations of `node` over are the ones
+ /// `record`, which this pass may have computed, holds: those of the record the element holds,
+ /// where `record` holds the same custom properties as it, as a store computed again does. A pseudo-element computed in the
+ /// same pass as a new record of its element that moved no custom property inherits the
+ /// animated values as it did.
+ fn samples_custom_properties_of(&self, node: StyleNodeID, record: &Arc<Record>) -> bool {
+ let sets = &self.state.computed_group_sets;
+ if sets.holds_record(node, record) {
+ return true;
+ }
+ let same_store =
+ |a: Option<&Arc<crate::css::custom_properties::CustomPropertyStore>>,
+ b: Option<&Arc<crate::css::custom_properties::CustomPropertyStore>>| match (a, b) {
+ (None, None) => true,
+ (Some(a), Some(b)) => Arc::ptr_eq(a, b) || a.holds_same_values_as(b),
+ _ => false,
+ };
+ sets.held_record(node).is_some_and(|held| {
+ same_store(held.custom_properties(), record.custom_properties())
+ && same_store(
+ held.inheritable_custom_properties(),
+ record.inheritable_custom_properties(),
+ )
+ })
+ }
+
+ /// The custom properties the animations of `node` sampled, where the host sampled them over
+ /// the environment of the record the element holds: the element's own custom properties with
+ /// the animated values in place of theirs.
+ pub(super) fn sampled_custom_properties(&self, node: StyleNodeID) -> Option<HeldCustomProperties> {
+ self.sampled_custom_property_store(node).map(|store| store.cloned())
+ }
+
+ /// The custom properties the animations of the pseudo-element of `kind` of `node` sampled:
+ /// its own custom properties with the animated values in place of theirs, where the host
+ /// holds an animation overlay for it.
+ pub(super) fn sampled_pseudo_element_custom_properties(&self, node: StyleNodeID, kind: u8) -> HeldCustomProperties {
+ let (_, held) = self
+ .state
+ .pseudo_element_custom_property_data
+ .get(&node)?
+ .iter()
+ .find(|(pseudo, held)| *pseudo == kind && held.sampled_over.is_some())?;
+ self.state.custom_property_environments.store(held.identity).cloned()
+ }
+
+ /// As [`Self::sampled_custom_properties`], borrowed.
+ fn sampled_custom_property_store(
+ &self,
+ node: StyleNodeID,
+ ) -> Option<Option<&'a Arc<crate::css::custom_properties::CustomPropertyStore>>> {
+ let environment = self
+ .state
+ .computed_group_sets
+ .custom_property_environment_identity(node);
+ let sampled = self
+ .state
+ .element_custom_property_data
+ .get(&node)
+ .filter(|held| {
+ held.sampled_over.is_some() && (environment == Some(held.identity) || held.sampled_over == environment)
+ })?
+ .identity;
+ Some(self.state.custom_property_environments.store(sampled))
+ }
+
+ /// Whether this pass computed `node`.
+ pub(super) fn computed(&self, node: StyleNodeID) -> bool {
+ self.cells.held(node.element_slot()).is_some()
+ }
+
+ /// Whether `node` holds a record the host does not hold yet: one this pass computed, or one a
+ /// pass before it computed that was not installed since, as where a pass restyles only the
+ /// elements that waited on a font or a random base value. The elements below it read it as
+ /// that record has it.
+ fn holds_uninstalled_record(&self, node: StyleNodeID) -> bool {
+ if self.computed(node) {
+ return true;
+ }
+ let Some(record) = self.previous.and_then(|previous| previous.get(node)) else {
+ return false;
+ };
+ self.state
+ .computed_group_sets
+ .held_record(node)
+ .is_none_or(|held| !Arc::ptr_eq(held, record) && !held.holds_the_same_style_as(record))
+ }
+
+ /// Which children of `node` the record this pass computed for it restyles: those computing
+ /// from something it differs in from what they inherited before, the one it held or the
+ /// composition of its animations over that. A child computes from its parent's
+ /// inherited groups, color, zoom, publication dependencies, display and custom properties, as
+ /// a result is reused by, and from its other groups only where it read them.
+ pub(super) fn child_impact(&self, node: StyleNodeID) -> ChildImpact {
+ let (Some(new), Some(old)) = (
+ self.cells.held(node.element_slot()),
+ self.previous.and_then(|previous| previous.get(node)),
+ ) else {
+ return ChildImpact::All;
+ };
+ // https://drafts.csswg.org/css-pseudo-4/#highlight-cascade
+ // The highlight pseudo-elements of the children inherit from the element's.
+ if self.highlights_moved(node) {
+ return ChildImpact::All;
+ }
+ let new = &new.record;
+ if Arc::ptr_eq(new, old) {
+ return ChildImpact::None;
+ }
+ // The children inherited the composition of the element's animations over the record it
+ // held, where the host composed one, and the custom properties those sampled.
+ let composition = self.state.computed_group_sets.composition_over_record(node, old);
+ if self.sampled_custom_properties(node).is_some() {
+ return ChildImpact::All;
+ }
+ // An inherited longhand no group holds reaches the children through the table alone.
+ let ungrouped_inherited_moved = || {
+ crate::css::computed_values::StyleGroupMasks::get()
+ .ungrouped_inherited()
+ .iter()
+ .any(|&property| {
+ match (
+ computed::ViewLonghands::of_record(new).handle(property),
+ computed::ViewLonghands::of_record(old).handle(property),
+ ) {
+ (Some(new), Some(old)) => !crate::css::style_value::retained_style_values_equal(new, old),
+ (new, old) => new.is_some() != old.is_some(),
+ }
+ })
+ };
+ if new.payloads.current_color() != old.payloads.current_color()
+ || new.payloads.inherited_values() != old.payloads.inherited_values()
+ // https://drafts.csswg.org/css-color-adjust-1/#color-scheme-prop
+ // A child whose `color-scheme` is the one it inherits uses the scheme its parent uses.
+ || new.effective_color_scheme() != old.effective_color_scheme()
+ || new.facts().publication_dependency_flags() != old.facts().publication_dependency_flags()
+ || new.facts().display != old.facts().display
+ || ungrouped_inherited_moved()
+ // https://drafts.csswg.org/css-color-4/#resolving-other-colors
+ // A child inheriting a value that reads `currentcolor` resolves it against its own
+ // color, so the specified values the record retains reach the children where the
+ // colors they resolve to here did not move.
+ || crate::css::computed_longhand_table::inherited_inheritance_dependent_value_moved(
+ old.inheritance_dependent_values(),
+ new.inheritance_dependent_values(),
+ )
+ {
+ return ChildImpact::All;
+ }
+ let inherited = composition.map_or(&old.payloads, |view| view.payloads);
+ let impact = match ChildImpact::of_groups(&new.payloads, inherited) {
+ ChildImpact::None
+ if crate::css::computed_longhand_table::non_inherited_inheritance_changes(
+ old.inheritance_dependent_values(),
+ new.inheritance_dependent_values(),
+ ) != 0 =>
+ {
+ ChildImpact::ResetReaders
+ }
+ impact => impact,
+ };
+ let stores_moved = !same_arc(new.custom_properties(), old.custom_properties())
+ || !same_arc(new.inheritable_custom_properties(), old.inheritable_custom_properties());
+ match (impact, stores_moved) {
+ (ChildImpact::None, true) => ChildImpact::CustomProperties,
+ (ChildImpact::ResetReaders, true) => ChildImpact::ResetReadersAndCustomProperties,
+ (impact, _) => impact,
+ }
+ }
+
+ /// Whether the records this pass computed for the highlight pseudo-elements of `node` hold
+ /// other styles than the ones it held before.
+ fn highlights_moved(&self, node: StyleNodeID) -> bool {
+ let Some(new) = self.cells.pseudo_element_records(node.element_slot()) else {
+ return false;
+ };
+ let old = self
+ .previous
+ .map_or(&[][..], |previous| previous.pseudo_element_records(node));
+ let of_kind = |records: &'_ [(u8, Arc<Record>)], kind: u8| {
+ records
+ .iter()
+ .find(|(held, _)| *held == kind)
+ .map(|(_, record)| record.clone())
+ };
+ super::HIGHLIGHT_KINDS
+ .iter()
+ .any(|&kind| match (of_kind(new, kind), of_kind(old, kind)) {
+ (None, None) => false,
+ (Some(new), Some(old)) => !Arc::ptr_eq(&new, &old) && !new.holds_the_same_as(&old),
+ _ => true,
+ })
+ }
+
+ pub(super) fn get(&self, node: StyleNodeID) -> Option<&'a Record> {
+ self.get_shared(node).map(|record| &**record)
+ }
+
+ /// The records of the pseudo-elements of `node` that generate a box, by kind.
+ pub(super) fn pseudo_element_records(&self, node: StyleNodeID) -> &'a [(u8, Arc<Record>)] {
+ match self.cells.pseudo_element_records(node.element_slot()) {
+ Some(records) => records.as_slice(),
+ None if self.computed(node) => &[],
+ None => self
+ .previous
+ .map_or(&[], |previous| previous.pseudo_element_records(node)),
+ }
+ }
+
+ pub(super) fn insert_pseudo_element_records(&self, node: StyleNodeID, records: PseudoElementRecords) {
+ for (_, record) in &records {
+ self.note_sibling_position_read(node, record);
+ }
+ assert!(
+ self.cells.to_write(node.element_slot()).pseudo_element_records[node.element_slot() % CELL_PAGE_SIZE]
+ .set(records)
+ .is_ok(),
+ "an element's pseudo-elements are styled once per pass"
+ );
+ }
+
+ fn held(&self, node: StyleNodeID) -> Option<&'a Held> {
+ match self.cells.held(node.element_slot()) {
+ Some(held) => Some(held),
+ None => self.previous?.held(node),
+ }
+ }
+
+ pub(super) fn get_shared(&self, node: StyleNodeID) -> Option<&'a Arc<Record>> {
+ Some(&self.held(node)?.record)
+ }
+
+ /// The identity of the elements `node` is indistinguishable from to selectors: the element
+ /// that was computed, which every element sharing its style through the sharing cache names.
+ ///
+ /// NB: An identity holds for the pass that shared the style: what no rule reads can change on an
+ /// element no pass restyles, so one the pass did not style is alike to none but itself.
+ pub(super) fn sharing_identity(&self, node: StyleNodeID) -> Option<StyleNodeID> {
+ match self.cells.held(node.element_slot()) {
+ Some(held) => Some(held.sharing_identity),
+ None => self.previous?.held(node).map(|_| node),
+ }
+ }
+
+ /// Keep the record `node` held before for this pass, with what it matched.
+ pub(super) fn keep_previous(&self, node: StyleNodeID) -> bool {
+ let Some(previous) = self.previous else {
+ return false;
+ };
+ let Some(held) = previous.held(node) else {
+ return false;
+ };
+ self.insert(node, held.record.clone(), node, held.matches.clone());
+ self.insert_pseudo_element_records(node, previous.pseudo_element_records(node).into());
+ if let Some(reads) = previous.container_reads(node) {
+ self.insert_container_reads(node, reads.clone());
+ }
+ true
+ }
+
+ /// Keep `record`, the one `node` held before over the custom properties its parent hands down
+ /// now, with what else it held.
+ pub(super) fn keep_previous_over_moved_custom_properties(&self, node: StyleNodeID, record: Arc<Record>) -> bool {
+ let Some(held) = self.previous.and_then(|previous| previous.held(node)) else {
+ return false;
+ };
+ self.insert(node, record, node, held.matches.clone());
+ self.insert_pseudo_element_records(node, PseudoElementRecords::new());
+ if let Some(reads) = self.previous.and_then(|previous| previous.container_reads(node)) {
+ self.insert_container_reads(node, reads.clone());
+ }
+ true
+ }
+
+ /// Note on the parent of `node` that `record`, held for it or a pseudo-element of it, computes
+ /// from where it stands among its siblings, which an element moving among them moves.
+ fn note_sibling_position_read(&self, node: StyleNodeID, record: &Record) {
+ if record.rare().reads.reads_sibling_position {
+ self.state.projection.note_structural_read(
+ TransactionFactSide::After,
+ node,
+ StructuralRead::SiblingPositionValue,
+ );
+ }
+ }
+
+ /// Keep what the container conditions of the rules `node` matched read of its containers.
+ pub(super) fn insert_container_reads(&self, node: StyleNodeID, reads: Arc<ContainerVerdict>) {
+ assert!(
+ self.cells.to_write(node.element_slot()).container_reads[node.element_slot() % CELL_PAGE_SIZE]
+ .set(reads)
+ .is_ok(),
+ "an element is styled once per pass"
+ );
+ }
+
+ /// What the container conditions of the rules `node` matched read of its containers, here
+ /// or in a pass before, where it matched any rule applying under container conditions.
+ pub(super) fn container_reads(&self, node: StyleNodeID) -> Option<&Arc<ContainerVerdict>> {
+ match self.computed(node) {
+ true => self.cells.container_reads(node.element_slot()),
+ false => self.previous?.container_reads(node),
+ }
+ }
+
+ /// How much of the root element's font the style of `node` resolves lengths against, its own
+ /// or its pseudo-elements', or through the container conditions of the rules it matched, whose
+ /// queries may read any of it, as may a node having no record.
+ pub(super) fn reads_root_font(&self, node: StyleNodeID) -> RootFontReads {
+ let Some(record) = self.get(node) else {
+ return RootFontReads::Metrics;
+ };
+ if self.container_reads(node).is_some_and(|reads| reads.reads_root_font) {
+ return RootFontReads::Metrics;
+ }
+ self.pseudo_element_records(node)
+ .iter()
+ .fold(record.rare().reads.reads_root_font, |reads, (_, record)| {
+ reads.max(record.rare().reads.reads_root_font)
+ })
+ }
+
+ /// Whether `node` reads its containers, through the container conditions of the rules it
+ /// matched or the container-relative lengths of its own or its pseudo-elements' styles.
+ pub(super) fn reads_containers(&self, node: StyleNodeID) -> bool {
+ self.container_reads(node).is_some()
+ || self
+ .get(node)
+ .is_some_and(|record| record.rare().reads.container_units != 0)
+ || self
+ .pseudo_element_records(node)
+ .iter()
+ .any(|(_, record)| record.rare().reads.container_units != 0)
+ }
+
+ /// Whether the record this pass computed for `node` moves beneath a composition of its
+ /// animations, which the host lays over the new record once it is installed: the element has
+ /// animations, or the record it moves to or from declares CSS animations, which the host
+ /// plans. A transition the host starts once it installs the record composes nothing the
+ /// children wait for: they compute from the after-change style, and restyle once the host
+ /// publishes the values the transition starts from.
+ pub(super) fn moves_beneath_a_composition(&self, node: StyleNodeID) -> bool {
+ let Some(new) = self.cells.held(node.element_slot()) else {
+ return false;
+ };
+ let new = &new.record;
+ let old = self.previous.and_then(|previous| previous.get(node));
+ if old.is_some_and(|old| Arc::ptr_eq(old, new)) {
+ return false;
+ }
+ let animates = |record: &Record| record.facts().declares_css_animations();
+ (animates(new)
+ || old.is_some_and(|old| animates(old))
+ || self.state.projection.adjustment_facts(node) & bridge::element_adjustment_fact::HAS_ANIMATIONS != 0)
+ && old.is_none_or(|old| !new.holds_the_same_style_as(old))
+ }
+
+ /// Whether the record this pass computed for `node` is displayed where the one it held before
+ /// was not: the elements below it were not styled since, and match and compute anew.
+ pub(super) fn revealed(&self, node: StyleNodeID) -> bool {
+ let Some(new) = self.cells.held(node.element_slot()) else {
+ return false;
+ };
+ self.previous
+ .and_then(|previous| previous.get(node))
+ .is_some_and(|old| !old.is_displayed() && new.record.is_displayed())
+ }
+
+ /// Whether the record this pass computed for `node` describes another container than the one
+ /// it held before: another query container, by type, name, writing mode or direction, or,
+ /// where `custom_properties` asks, a style container holding other custom properties. The
+ /// elements below it that read their containers read them anew.
+ pub(super) fn container_moved(&self, node: StyleNodeID, custom_properties: bool) -> bool {
+ let (Some(new), Some(old)) = (
+ self.cells.held(node.element_slot()),
+ self.previous.and_then(|previous| previous.get(node)),
+ ) else {
+ return false;
+ };
+ let new = &new.record;
+ if Arc::ptr_eq(new, old) {
+ return false;
+ }
+ let state = self.state;
+ fn row<'r>(
+ state: &RetainedState,
+ node: StyleNodeID,
+ record: &'r Record,
+ ) -> Option<super::super::tree::ContainerQueryInputs<'r>> {
+ state.container_query_input_row_of_payloads(node, &record.payloads, 0, true)
+ }
+ // A size container's font-relative query lengths (`@container (width > 5em)`) resolve
+ // against its own font and line height, which its row does not hold.
+ let font_moved = || {
+ let font = group_index::FONT;
+ let box_values = crate::css::computed_value_views::ComputedValuesView::of(&new.payloads).box_values();
+ (box_values.is_size_container || box_values.is_inline_size_container)
+ && new.payloads[font].as_ptr() != old.payloads[font].as_ptr()
+ };
+ row(state, node, new) != row(state, node, old)
+ || font_moved()
+ || (custom_properties
+ && match (new.custom_properties(), old.custom_properties()) {
+ (None, None) => false,
+ (Some(a), Some(b)) => !Arc::ptr_eq(a, b),
+ _ => true,
+ })
+ }
+
+ /// The rule index entries `node` matched, here or in a pass before, where they were kept.
+ pub(super) fn matches_of(&self, node: StyleNodeID) -> Option<&MatchList> {
+ self.held(node)?.matches.as_ref()
+ }
+
+ pub(super) fn insert(
+ &self,
+ node: StyleNodeID,
+ record: Arc<Record>,
+ sharing_identity: StyleNodeID,
+ matches: Option<MatchList>,
+ ) {
+ self.note_sibling_position_read(node, &record);
+ assert!(
+ self.cells.to_write(node.element_slot()).held[node.element_slot() % CELL_PAGE_SIZE]
+ .set(Held {
+ record,
+ sharing_identity,
+ matches,
+ })
+ .is_ok(),
+ "an element is styled once per pass"
+ );
+ }
+
+ /// The resolved color of the style `node` holds, here or as it is installed.
+ pub(super) fn current_color_of(&self, node: StyleNodeID) -> Option<u32> {
+ let view = match self.get(node) {
+ Some(record) => match self.composition(node) {
+ Some(view) => view,
+ None => return Some(record.payloads.current_color()),
+ },
+ None => self.state.assigned_record_view(node)?,
+ };
+ let payload = view.payloads[crate::css::table_group_builder::group_index::INHERITED_TEXT].as_ptr();
+ if payload.is_null() {
+ return None;
+ }
+ // SAFETY: The payload is the live inherited text group of the record.
+ Some(unsafe { &*payload.cast::<crate::css::computed_value_types::InheritedTextValues>() }.color)
+ }
+}
+
+impl ContainerRecords for Records<'_> {
+ /// An element holding a record the host does not hold yet, which this pass or one before it in
+ /// the same update computed, is the query container that record says it is, which the
+ /// elements below it compute against before the record is installed.
+ fn query_row(&self, node: StyleNodeID) -> Option<super::super::tree::ContainerQueryInputs<'_>> {
+ if !self.holds_uninstalled_record(node) {
+ return self.state.query_row(node);
+ }
+ let record = self.get(node)?;
+ self.state
+ .container_query_input_row_of_payloads(node, &record.payloads, 0, false)
+ }
+
+ fn any_element_row(&self, node: StyleNodeID) -> Option<super::super::tree::ContainerQueryInputs<'_>> {
+ if !self.holds_uninstalled_record(node) {
+ return self.state.any_element_row(node);
+ }
+ let record = self.get(node)?;
+ self.state
+ .container_query_input_row_of_payloads(node, &record.payloads, 0, true)
+ }
+
+ fn record_view(
+ &self,
+ node: StyleNodeID,
+ row: super::super::tree::ContainerQueryInputs<'_>,
+ ) -> Option<computed::StyleRecordView<'_>> {
+ match self.holds_uninstalled_record(node) {
+ true => self.assigned_record_view(node),
+ false => self.state.record_view(node, row),
+ }
+ }
+
+ /// The custom properties the element's record holds, with the values the animations of an
+ /// element still holding it sampled in place of theirs, as its children inherit them.
+ fn custom_store(
+ &self,
+ node: StyleNodeID,
+ row: super::super::tree::ContainerQueryInputs<'_>,
+ ) -> Option<Option<&crate::css::custom_properties::CustomPropertyStore>> {
+ if !self.holds_uninstalled_record(node) {
+ return self.state.custom_store(node, row);
+ }
+ let record = self.get_shared(node)?;
+ if self.samples_custom_properties_of(node, record)
+ && let Some(sampled) = self.sampled_custom_property_store(node)
+ {
+ return Some(sampled.map(|store| &**store));
+ }
+ Some(record.custom_properties().map(|store| &**store))
+ }
+}
+
+impl Record {
+ /// The view of the record, as the computation of the elements inheriting from it reads it.
+ fn view(self: &Arc<Self>) -> computed::StyleRecordView<'_> {
+ computed::StyleRecordView {
+ payloads: &self.payloads,
+ base_payloads: &self.payloads,
+ record: self,
+ animated_overlay: None,
+ pseudo_element_styles: 0,
+ counter_style_environment_identity: 0,
+ dependency_flags: self.facts().publication_dependency_flags(),
+ }
+ }
+}
+
+impl<'a> Records<'a> {
+ /// The record the highlight pseudo-element of `kind` of `node` inherits from: that of the same
+ /// pseudo-element of its nearest flat-tree ancestor holding one, here or, for an ancestor these
+ /// records hold nothing for, as it is installed.
+ pub(super) fn highlight_inheritance_parent(&self, node: StyleNodeID, kind: u8) -> Option<HighlightParent<'a>> {
+ let mut ancestor = self.state.projection.inheritance_parent(node);
+ while let Some(current) = ancestor {
+ match self.get(current) {
+ Some(_) => {
+ if let Some((_, record)) = self
+ .pseudo_element_records(current)
+ .iter()
+ .find(|(held, _)| *held == kind)
+ {
+ return Some(HighlightParent::Record(record));
+ }
+ }
+ None => {
+ if let Some(record) = self.state.computed_group_sets.pseudo_style_record(current, kind) {
+ return Some(HighlightParent::Installed(record));
+ }
+ }
+ }
+ ancestor = self.state.projection.inheritance_parent(current);
+ }
+ None
+ }
+}
+
+/// The record a highlight pseudo-element inherits from: one the engine computed, or one the current
+/// engine installed.
+#[derive(Clone, Copy)]
+pub(super) enum HighlightParent<'a> {
+ Record(&'a Arc<Record>),
+ Installed(computed::FinalStyleRecordID),
+}
+
+impl HighlightParent<'_> {
+ /// The identity of the record, which tells it apart from any other one live.
+ pub(super) fn identity(self) -> usize {
+ match self {
+ Self::Record(record) => Arc::as_ptr(record) as usize,
+ Self::Installed(record) => record.raw() as usize,
+ }
+ }
+}
+
+impl DriveRecords for Records<'_> {
+ fn assigned_record_view(&self, node: StyleNodeID) -> Option<computed::StyleRecordView<'_>> {
+ let Some(record) = self.get_shared(node) else {
+ return self.state.assigned_record_view(node);
+ };
+ if let Some(view) = self.composition(node) {
+ return Some(view);
+ }
+ Some(record.view())
+ }
+
+ fn highlight_inheritance_parent_view(&self, node: StyleNodeID, kind: u8) -> Option<computed::StyleRecordView<'_>> {
+ match self.highlight_inheritance_parent(node, kind)? {
+ HighlightParent::Record(record) => Some(record.view()),
+ HighlightParent::Installed(record) => self.state.computed_group_sets.style_record_view(record.raw()),
+ }
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/results.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/results.rs
new file mode 100644
index 00000000000..58f9cd8025d
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/results.rs
@@ -0,0 +1,226 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The cascade result cache: an element whose cascade picked the same declarations as one computed
+//! shortly before it, under a parent whose inherited style is the same, takes that element's record
+//! instead of computing its own.
+//!
+//! Where the style sharing cache finds siblings and cousins before matching, this finds elements
+//! anywhere that end up with the same winners, such as the levels of a chain of identically styled
+//! elements. What a computation reads beyond its winners is in the key: the parent's inherited groups
+//! by identity, its color, zoom and dependency flags, the box the element would be a child of, the
+//! element's custom-property store by identity, the facts its computation adjusts for and the
+//! counter-style registry of its style scope. Winners from an element's own declarations match
+//! where those declarations declare the same values.
+
+use super::super::animations::DeclarationScope;
+use super::super::computed::ENGINE_INHERITED_GROUP_COUNT;
+use super::super::*;
+use super::cascade::Winner;
+use super::records::Record;
+use crate::css::display::FfiDisplay;
+use smallvec::SmallVec;
+use std::collections::VecDeque;
+use std::hash::{Hash, Hasher};
+use std::sync::Arc;
+
+/// How many computed elements each thread keeps to reuse.
+const CAPACITY: usize = 32;
+
+/// How many hashes of recently computed elements each thread remembers. An element whose winners
+/// include its own declarations is kept to reuse only once its hash recurs, so the many elements
+/// whose inline style is their own cost a hash rather than an entry.
+const SEEN_CAPACITY: usize = 64;
+
+/// What a computation reads besides its winners and the element's own declarations.
+#[derive(Clone, Copy, PartialEq)]
+pub(super) struct ResultContext {
+ pub(super) parent_inherited_groups: [usize; ENGINE_INHERITED_GROUP_COUNT],
+ pub(super) parent_color: u32,
+ /// The inherited longhands the parent holds as bits, and its effective zoom.
+ pub(super) parent_inherited_values: crate::css::computed_value_types::InheritedSetValues,
+ pub(super) parent_dependency_flags: u8,
+ /// The display of the parent, which is the box the element would be a child of.
+ pub(super) parent_display: FfiDisplay,
+ pub(super) custom_properties: usize,
+ pub(super) adjustment_facts: u32,
+ pub(super) language: StyleAtomID,
+ pub(super) directionality: StyleAtomID,
+ /// The identity of the counter-style registry of the element's style scope, which its
+ /// `list-style-type` or `content` may resolve counter styles against.
+ pub(super) counter_style_environment: u64,
+ /// The hash of the context with the winners and the element's own declarations.
+ pub(super) hash: u64,
+}
+
+impl ResultContext {
+ /// Complete the context of `node` with the hash of everything its result depends on.
+ pub(super) fn hashed(mut self, state: &RetainedState, node: StyleNodeID, winners: &[Winner]) -> Self {
+ self.hash = self.hash_with(state, node, winners);
+ self
+ }
+
+ fn hash_with(&self, state: &RetainedState, node: StyleNodeID, winners: &[Winner]) -> u64 {
+ let mut hasher = crate::fast_hash::fast_hasher();
+ winners.hash(&mut hasher);
+ for kind in element_declaration_kinds(winners) {
+ for (declared, written) in element_declarations(state, node, kind) {
+ declared.hash(&mut hasher);
+ written.pointer().hash(&mut hasher);
+ }
+ }
+ self.parent_inherited_groups.hash(&mut hasher);
+ self.parent_color.hash(&mut hasher);
+ self.custom_properties.hash(&mut hasher);
+ self.adjustment_facts.hash(&mut hasher);
+ hasher.finish()
+ }
+}
+
+struct Entry {
+ node: StyleNodeID,
+ winners: SmallVec<[Winner; 16]>,
+ context: ResultContext,
+ record: Arc<Record>,
+ /// The custom-property store the context names by identity, which the entry keeps alive so
+ /// that no other store takes its address. The record may hold another, computed from it.
+ _custom_properties: Option<Arc<crate::css::custom_properties::CustomPropertyStore>>,
+}
+
+pub(super) struct ResultCache {
+ /// Most recently computed last.
+ entries: VecDeque<Entry>,
+ seen: [u64; SEEN_CAPACITY],
+ next_seen: usize,
+ /// How often an element with declarations of its own was found and missed since the counts
+ /// last started over. While such elements rarely repeat, a thread computes them without
+ /// looking for them.
+ hits: u32,
+ misses: u32,
+ lookups: u32,
+}
+
+impl Default for ResultCache {
+ fn default() -> Self {
+ Self {
+ entries: VecDeque::new(),
+ seen: [0; SEEN_CAPACITY],
+ next_seen: 0,
+ hits: 0,
+ misses: 0,
+ lookups: 0,
+ }
+ }
+}
+
+/// How many lookups the hit counts cover before they start over.
+const COUNT_PERIOD: u32 = 1024;
+
+/// The declarations of `kind` of `node`, each with the value it was written with. Equal values
+/// elements declare are one canonical value, so two elements declaring the same declare the same
+/// values.
+fn element_declarations(
+ state: &RetainedState,
+ node: StyleNodeID,
+ kind: ElementDeclarationKind,
+) -> impl Iterator<Item = (&DeclarationEntry, &RetainedStyleValueData)> {
+ state
+ .element_declarations
+ .declarations(node, kind)
+ .unwrap_or_default()
+ .iter()
+}
+
+/// The kinds of an element's own declarations its winners came from.
+fn element_declaration_kinds(winners: &[Winner]) -> impl Iterator<Item = ElementDeclarationKind> + '_ {
+ let mut seen = 0_u8;
+ winners.iter().filter_map(move |winner| match winner.source {
+ WinnerSource::Element(kind) if seen & (1 << kind.index()) == 0 => {
+ seen |= 1 << kind.index();
+ Some(kind)
+ }
+ _ => None,
+ })
+}
+
+impl ResultCache {
+ /// Whether looking for the next element with declarations of its own is worth its cost.
+ pub(super) fn worth_looking(&mut self) -> bool {
+ self.lookups += 1;
+ if self.lookups == COUNT_PERIOD {
+ self.lookups = 0;
+ self.hits = 0;
+ self.misses = 0;
+ }
+ // A hit saves a computation, which costs some twenty lookups that miss.
+ self.misses < 64 || self.hits * 20 >= self.misses
+ }
+
+ pub(super) fn find(
+ &mut self,
+ state: &RetainedState,
+ node: StyleNodeID,
+ winners: &[Winner],
+ animation_name_scope: DeclarationScope,
+ context: &ResultContext,
+ ) -> Option<Arc<Record>> {
+ // NB: The winners of a sheet several shadow roots adopt are the same in each, but not the
+ // scope their `animation-name` looks for `@keyframes` in.
+ let position = self.entries.iter().rposition(|entry| {
+ entry.context == *context
+ && entry.winners[..] == *winners
+ && entry.record.rare().animation_name_scope == animation_name_scope
+ && element_declaration_kinds(winners).all(|kind| {
+ let identities = |node| {
+ element_declarations(state, node, kind)
+ .map(|(declared, written)| (*declared, written.pointer()))
+ };
+ identities(node).eq(identities(entry.node))
+ })
+ });
+ let declares_own = element_declaration_kinds(winners).next().is_some();
+ let Some(position) = position else {
+ self.misses += u32::from(declares_own);
+ return None;
+ };
+ self.hits += u32::from(declares_own);
+ let entry = self.entries.remove(position).expect("the position is in the cache");
+ let record = entry.record.clone();
+ self.entries.push_back(entry);
+ Some(record)
+ }
+
+ pub(super) fn insert(
+ &mut self,
+ node: StyleNodeID,
+ winners: &[Winner],
+ context: ResultContext,
+ custom_properties: Option<Arc<crate::css::custom_properties::CustomPropertyStore>>,
+ record: Arc<Record>,
+ ) {
+ debug_assert_eq!(
+ context.custom_properties,
+ custom_properties
+ .as_ref()
+ .map_or(0, |store| Arc::as_ptr(store) as usize)
+ );
+ if element_declaration_kinds(winners).next().is_some() && !self.seen.contains(&context.hash) {
+ self.seen[self.next_seen] = context.hash;
+ self.next_seen = (self.next_seen + 1) % SEEN_CAPACITY;
+ return;
+ }
+ if self.entries.len() == CAPACITY {
+ self.entries.pop_front();
+ }
+ self.entries.push_back(Entry {
+ node,
+ winners: winners.into(),
+ context,
+ record,
+ _custom_properties: custom_properties,
+ });
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/sharing.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/sharing.rs
new file mode 100644
index 00000000000..a994ddda9b6
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/sharing.rs
@@ -0,0 +1,201 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The style sharing cache: an element that agrees with one styled shortly before it on everything
+//! its style could depend on takes that element's record instead of matching, cascading and
+//! computing its own.
+//!
+//! Two elements agree when their parents are the same element or shared a style through this cache, which by
+//! induction makes their ancestor chains indistinguishable to selectors, and they themselves have
+//! the same tag, namespace, classes and states, no id a selector tests for, and no declarations of
+//! their own. Rule entries that read anything beyond that, such as attributes or siblings,
+//! revalidate: they are evaluated for the element and must match exactly as they matched the
+//! candidate.
+
+use super::super::index::StateSet;
+use super::super::*;
+use super::matching::ElementMatch;
+use super::projection::ElementFacts;
+use super::records::Record;
+use super::rules::RuleIndex;
+use smallvec::SmallVec;
+use std::sync::Arc;
+
+/// How many recently styled elements each thread keeps to share with.
+const CAPACITY: usize = 16;
+
+/// What two elements must agree on, besides their classes, custom states and parts, to share.
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(super) struct SharingKey {
+ /// The sharing identity of the parent.
+ parent: StyleNodeID,
+ /// The sharing identity of the inheritance parent, or the inheritance parent itself where the
+ /// host composes its animations over its record: elements sharing a record do not share a
+ /// composition.
+ inheritance_parent: StyleNodeID,
+ inheritance_parent_composes: bool,
+ tag: StyleAtomID,
+ namespace: StyleAtomID,
+ states: StateSet,
+ directionality: StyleAtomID,
+ language: StyleAtomID,
+ heading_level: u8,
+ part_exposure: StyleAtomID,
+ adjustment_facts: u32,
+ tree_scope: TreeScopeID,
+ assigned_slot: Option<StyleNodeID>,
+ /// The records of the highlight pseudo-elements of the inheritance parent, which those of the
+ /// element inherit from.
+ highlight_parents: [usize; 4],
+ /// The highlights the host shows in the element, whose pseudo-elements a pass styles.
+ highlight_observers: u8,
+}
+
+/// The matched entries that revalidate, with the scope proximity of each.
+pub(super) type Revalidation = SmallVec<[(u32, u32); 4]>;
+
+pub(super) fn revalidation_of(index: &RuleIndex, matches: &[ElementMatch]) -> Revalidation {
+ matches
+ .iter()
+ .filter(|matched| index.entries.view(matched.entry as usize).revalidates())
+ .map(|matched| (matched.entry, matched.scope_proximity))
+ .collect()
+}
+
+/// The key `node` shares under, or none where it cannot share: it has an id a selector tests for,
+/// declarations of its own, a shadow tree or parts, a composition of its animations over its
+/// record, or a parent this pass did not style.
+pub(super) fn key_of(
+ state: &RetainedState,
+ index: &RuleIndex,
+ records: &super::records::Records<'_>,
+ node: StyleNodeID,
+ facts: &ElementFacts,
+) -> Option<SharingKey> {
+ let id = facts.id();
+ if (id != StyleAtomID::NONE && index.tests_id(id))
+ || !state.element_declarations.custom_declarations(node).is_empty()
+ || [
+ ElementDeclarationKind::InlineStyle,
+ ElementDeclarationKind::PresentationalHint,
+ ElementDeclarationKind::SvgPresentationAttribute,
+ ]
+ .into_iter()
+ .any(|kind| !state.element_declarations.declared_properties(node, kind).is_empty())
+ || state.projection.shadow_root_of(node).is_some()
+ || !state.projection.part_hosts_of(node).is_empty()
+ // https://drafts.csswg.org/css-pseudo-4/#treelike
+ // An element sharing a style takes the records of its pseudo-elements too, which inherit
+ // the composition of the element's own animations, as no other element's style tells.
+ || records.composition(node).is_some()
+ // NB: A pseudo-element's record substitutes the custom properties its own animations sampled, which are not the
+ // same for two elements with the same rules: their animations can stand at different times.
+ || state.pseudo_element_samples_custom_properties(node)
+ {
+ return None;
+ }
+ let identity = |node: Option<StyleNodeID>| records.sharing_identity(node?);
+ let inheritance_parent = state.projection.inheritance_parent(node);
+ let inheritance_parent_composes = inheritance_parent.is_some_and(|parent| records.composition(parent).is_some());
+ Some(SharingKey {
+ parent: identity(state.projection.parent(node))?,
+ inheritance_parent: match inheritance_parent_composes {
+ true => inheritance_parent?,
+ false => identity(inheritance_parent)?,
+ },
+ inheritance_parent_composes,
+ tag: facts.tag(),
+ namespace: facts.namespace(),
+ states: facts.states(),
+ directionality: facts.directionality(),
+ language: facts.language(),
+ heading_level: facts.heading_level(),
+ part_exposure: facts.part_exposure(),
+ adjustment_facts: state.projection.adjustment_facts(node),
+ tree_scope: state.projection.tree_scope(node),
+ assigned_slot: state.projection.assigned_slot_of(node),
+ highlight_parents: {
+ let parent_records = inheritance_parent.map_or(&[][..], |parent| records.pseudo_element_records(parent));
+ super::HIGHLIGHT_KINDS.map(|kind| {
+ parent_records
+ .iter()
+ .find(|(held, _)| *held == kind)
+ .map_or(0, |(_, record)| Arc::as_ptr(record) as usize)
+ })
+ },
+ highlight_observers: state.highlight_observers.kinds_of(node),
+ })
+}
+
+struct Candidate {
+ key: SharingKey,
+ record: Arc<Record>,
+ /// The element whose record the candidate holds, whose classes, custom states and parts the
+ /// key leaves out.
+ identity: StyleNodeID,
+ revalidation: Revalidation,
+}
+
+#[derive(Default)]
+pub(super) struct SharingCache {
+ /// Most recently styled last.
+ candidates: std::collections::VecDeque<Candidate>,
+}
+
+impl SharingCache {
+ /// The record of a candidate an element with `facts` agrees with, asking `revalidate` for the
+ /// element's matches among the entries that revalidate once some candidate agrees on
+ /// everything else.
+ pub(super) fn find(
+ &mut self,
+ projection: &super::projection::Projection,
+ key: &SharingKey,
+ facts: &ElementFacts,
+ mut revalidate: impl FnMut() -> Option<Revalidation>,
+ ) -> Option<(Arc<Record>, StyleNodeID)> {
+ let mut revalidation = None;
+ let position = self.candidates.iter().rposition(|candidate| {
+ if candidate.key != *key {
+ return false;
+ }
+ let Some(held) = projection.facts(candidate.identity) else {
+ return false;
+ };
+ if held.classes() != facts.classes()
+ || held.custom_states() != facts.custom_states()
+ || held.parts() != facts.parts()
+ {
+ return false;
+ }
+ revalidation
+ .get_or_insert_with(&mut revalidate)
+ .as_ref()
+ .is_some_and(|revalidation| *revalidation == candidate.revalidation)
+ })?;
+ let candidate = self.candidates.remove(position)?;
+ let found = (candidate.record.clone(), candidate.identity);
+ self.candidates.push_back(candidate);
+ Some(found)
+ }
+
+ pub(super) fn insert(
+ &mut self,
+ key: SharingKey,
+ record: Arc<Record>,
+ identity: StyleNodeID,
+ revalidation: Revalidation,
+ ) {
+ if self.candidates.len() == CAPACITY {
+ self.candidates.pop_front();
+ }
+ self.candidates.push_back(Candidate {
+ key,
+ record,
+ identity,
+ revalidation,
+ });
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal.rs
new file mode 100644
index 00000000000..0c3791cc12d
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal.rs
@@ -0,0 +1,2826 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The style traversal: every element of the flat tree, shadow trees included, is matched,
+//! cascaded and computed once the parent it inherits from is, on a pool of threads.
+//!
+//! The calling thread styles the document breadth-first from its root. Once a level of the tree is
+//! wide enough, it keeps a queue of elements for itself and hands the rest out in work units, which
+//! the threads of the pool style the same way; a small or narrow document never leaves the calling
+//! thread.
+//! Every thread keeps its own matcher, cascade scratch and ancestor filter, which it reconciles with
+//! the ancestor chain of each element's parent in its own tree as it moves between parents.
+
+use super::super::container_queries::{ContainerRecords, ContainerVerdict};
+use super::super::custom_property_cascade::{
+ LonghandCustomPropertyReads, PreparedCustomFunctions, value_reads_substitution_subject,
+};
+use super::super::random_bases::RandomBaseRequest;
+use super::super::*;
+use super::bloom::AncestorFilter;
+use super::cascade::{Cascade, CascadeCounters};
+use super::compute::{GroupSeeds, RootFontInputs};
+use super::custom_properties::{DrivenWithRegisteredProperties, SubstitutingSubject, drive_with_registered_properties};
+use super::drive::DriveRecords;
+use super::matching::{ElementMatch, MatchCounters, Matcher};
+use super::records::{ChildImpact, RareStyleFacts, Record, Records};
+use super::results::{ResultCache, ResultContext};
+use super::rules::{ContainerGateID, RuleIndex};
+use super::sharing::SharingCache;
+#[cfg(test)]
+use super::write_once::WriteOnce;
+use crate::css::computed_values::{GroupSeed, GroupValueFacts, LonghandID};
+use crate::css::style_compute::RootFontReads;
+use smallvec::SmallVec;
+use std::borrow::Cow;
+use std::collections::VecDeque;
+use std::sync::Mutex;
+
+mod cache_audit;
+
+#[cfg(test)]
+pub(super) use cache_audit::CacheAudit;
+pub(super) use cache_audit::mode_from_environment as cache_audit_mode_from_environment;
+
+/// The most threads the traversal runs on, however many are asked for.
+pub(super) const MAX_THREAD_COUNT: usize = 16;
+
+/// The most threads the traversal runs on where none are asked for. Beyond this many, passes over
+/// a thousand elements take no less time, while each thread more faults in pages of its own and
+/// keeps a stack and an allocator heap.
+const DEFAULT_MAX_THREAD_COUNT: usize = 8;
+
+/// How many threads the traversal runs on where none are asked for: three of every four logical
+/// processors, leaving the others to the main thread and the rest of the process, and at least one.
+pub(super) fn thread_count() -> usize {
+ std::thread::available_parallelism().map_or(1, |count| (count.get() * 3 / 4).clamp(1, DEFAULT_MAX_THREAD_COUNT))
+}
+
+/// How many elements a task hands to another at once.
+const WORK_UNIT: usize = 16;
+
+/// How many elements the calling thread keeps queued for itself before it hands work to the pool.
+const CALLING_THREAD_QUEUE_SIZE: usize = 32;
+
+/// How many elements a pass finds to style before the pool's threads join in. A pass styling fewer
+/// runs on the calling thread alone: starting the pool's threads costs more than they would save.
+const PARALLEL_PASS_SIZE: usize = 64;
+
+/// The computed initial values every element's style starts from.
+pub(in crate::css::style) struct InitialStyle {
+ /// Whether each initial value is important, inherited and evaluated, and what the box
+ /// adjustments and the font computation settled.
+ pub(super) flags: crate::css::computed_longhand_table::LonghandTableFlags,
+ /// What the initial values depend on, as `DEPENDS_ON_VIEWPORT_METRICS` and the like.
+ pub(super) dependency_flags: u8,
+ /// The initial groups, holding the initial values, which every element not changing a group's
+ /// values from them shares.
+ pub(super) payloads: crate::css::computed_values::StyleGroups,
+ /// The groups the documents of the process share, which `payloads` holds all but the font
+ /// group of.
+ _shared: std::sync::Arc<super::super::process_style::SharedInitialGroups>,
+ pub(super) color: u32,
+ /// What the initial groups are built from beside their values.
+ pub(super) value_facts: GroupValueFacts,
+ /// The font the initial values resolved.
+ pub(super) font: InitialFont,
+}
+
+/// The host font objects the document's initial font resolved to, by address.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(in crate::css::style) struct InitialFont {
+ pub(in crate::css::style) first_available_font: usize,
+ pub(in crate::css::style) font_cascade_list: usize,
+}
+
+impl InitialStyle {
+ /// The initial style of what a drive `computed`, whose values the groups `payloads` hold.
+ pub(super) fn new(
+ computed: super::compute::ComputedInitialStyle,
+ payloads: crate::css::computed_values::StyleGroups,
+ shared: std::sync::Arc<super::super::process_style::SharedInitialGroups>,
+ ) -> Self {
+ Self {
+ flags: computed.flags,
+ dependency_flags: computed.dependency_flags,
+ payloads,
+ _shared: shared,
+ color: computed.color,
+ value_facts: computed.value_facts,
+ font: computed.font,
+ }
+ }
+
+ /// The initial value of `longhand`.
+ pub(super) fn longhand(&self, longhand: crate::css::computed_values::LonghandID) -> &RetainedStyleValueData {
+ self.payloads.value(longhand.property())
+ }
+
+ /// The initial groups, as the values of an element start from them.
+ pub(super) fn group_seed(&self) -> GroupSeed<'_> {
+ GroupSeed::new(&self.payloads, &self.value_facts)
+ }
+
+ /// What the group values of an element whose parent's record is `parent` start from.
+ pub(super) fn group_seeds<'a>(&'a self, parent: Option<&'a std::sync::Arc<Record>>) -> GroupSeeds<'a> {
+ GroupSeeds {
+ seeds: [
+ parent.map_or_else(|| self.group_seed(), |record| record.group_seed()),
+ self.group_seed(),
+ ],
+ parent,
+ }
+ }
+
+ /// Whether `other` holds the initial values and groups this does.
+ pub(super) fn holds_the_same_values_as(&self, other: &InitialStyle) -> bool {
+ self.value_facts.publication_equals(&other.value_facts)
+ && self.payloads.inherited_values() == other.payloads.inherited_values()
+ && self
+ .payloads
+ .iter()
+ .zip(other.payloads.iter())
+ .enumerate()
+ .all(|(group, (mine, theirs))| {
+ // SAFETY: Both styles hold a reference to each of their groups.
+ unsafe { crate::css::computed_values::groups_hold_the_same(group, mine.as_ptr(), theirs.as_ptr()) }
+ })
+ }
+}
+
+/// How an element's style came about.
+#[derive(Clone, Copy)]
+pub(super) enum Outcome {
+ Computed {
+ directly: bool,
+ },
+ /// The element took the record of an element it agrees with.
+ Shared,
+ /// The element took the record of an element whose cascade picked the same declarations.
+ Reused,
+ /// The element's cascade did not finish.
+ CascadeDeclined,
+ /// The element's computation did not finish.
+ ComputeDeclined,
+}
+
+/// What the traversal produced for one element.
+#[cfg(test)]
+pub(super) struct ElementOutput {
+ /// The element's matches, kept to check them against the reference matcher, or none when its
+ /// facts could not be matched.
+ pub(super) matches: Option<Vec<ElementMatch>>,
+ pub(super) outcome: Outcome,
+}
+
+/// The hint of an element: what a pass restyles of it and below it.
+pub(super) type HintBits = u16;
+
+/// The element itself is restyled.
+pub(super) const RESTYLE_SELF: HintBits = 1 << 0;
+/// Every descendant of the element is restyled.
+pub(super) const RESTYLE_DESCENDANTS: HintBits = 1 << 1;
+/// Some descendant of the element is restyled.
+pub(super) const DIRTY_DESCENDANTS: HintBits = 1 << 2;
+/// The element is matched against the whole rule index, not only the entries it is restyled for.
+pub(super) const MATCH_SELF: HintBits = 1 << 3;
+/// Every descendant of the element is.
+pub(super) const MATCH_DESCENDANTS: HintBits = 1 << 4;
+/// The element's parent was restyled to something its children compute from, which its traversal
+/// passes it, or the composition of the parent's animations moved, which the hint notes.
+pub(super) const PARENT_CHANGED: HintBits = 1 << 5;
+/// The element's parent was restyled, to what its children compute from or not.
+const PARENT_RESTYLED: HintBits = 1 << 6;
+/// An ancestor of the element describes another container than it did, which the elements below
+/// it that read their containers are restyled for.
+const CONTAINERS_MOVED: HintBits = 1 << 7;
+/// The element is restyled for its pseudo-elements, which inherit the composition of its
+/// animations that moved, as under a parent that changed. Where nothing else restyles it, the
+/// host owes it no other composition.
+pub(super) const RESTYLE_PSEUDO_ELEMENTS: HintBits = 1 << 8;
+/// The custom properties the element's parent hands down moved, and nothing else it computes from:
+/// it takes them without computing again where it substitutes none that moved.
+const PARENT_CUSTOM_PROPERTIES_MOVED: HintBits = 1 << 9;
+/// The font of the document element above the element moved, which the elements below it that
+/// resolve lengths against what moved of the root element's font are restyled for.
+const ROOT_FONT_MOVED: HintBits = 1 << 10;
+/// Something the element computes from its matches moved, and nothing its matches follow, such as
+/// its font environment: it is computed again from the matches it holds, where nothing else asks to
+/// rematch it.
+pub(super) const RECOMPUTE_SELF: HintBits = 1 << 11;
+/// The bits restyling the element itself.
+pub(super) const RESTYLES_SELF: HintBits = RESTYLE_SELF | RESTYLE_PSEUDO_ELEMENTS;
+/// The bits a pass styles the element or its descendants for, which it walks down to the element
+/// for. A pass leaves the last two to children of an element whose record moved beneath the
+/// composition of its animations, which the next one takes alone.
+pub(super) const STYLES_SOMETHING: HintBits =
+ RESTYLES_SELF | RESTYLE_DESCENDANTS | CONTAINERS_MOVED | PARENT_CUSTOM_PROPERTIES_MOVED;
+
+/// The rule index entries elements are restyled for, which may match them now where they did
+/// not or the other way around: an element restyled for some entries alone keeps its other
+/// matches.
+pub(super) struct Reasons<'a> {
+ /// The elements with the entries each is restyled for, sorted.
+ pub(super) own: &'a [(StyleNodeID, u32)],
+ /// The same for the entries the descendants of an element are restyled for.
+ pub(super) descendants: &'a [(StyleNodeID, u32)],
+}
+
+impl Reasons<'_> {
+ /// The entries of `node` in sorted pairs, in index order.
+ fn of(pairs: &[(StyleNodeID, u32)], node: StyleNodeID) -> Option<super::records::MatchList> {
+ let start = pairs.partition_point(|&(held, _)| held < node);
+ let end = start + pairs[start..].partition_point(|&(held, _)| held == node);
+ (start != end).then(|| std::sync::Arc::new(pairs[start..end].iter().map(|&(_, entry)| entry).collect()))
+ }
+}
+
+/// The union of two sorted entry lists.
+fn union(
+ a: Option<super::records::MatchList>,
+ b: Option<&super::records::MatchList>,
+) -> Option<super::records::MatchList> {
+ match (a, b) {
+ (None, b) => b.cloned(),
+ (a, None) => a,
+ (Some(a), Some(b)) => {
+ let mut merged: Vec<u32> = a.iter().chain(b.iter()).copied().collect();
+ merged.sort_unstable();
+ merged.dedup();
+ Some(std::sync::Arc::new(merged.into_boxed_slice()))
+ }
+ }
+}
+
+pub(super) struct PassContext<'a> {
+ pub(super) state: &'a RetainedState,
+ pub(super) index: &'a RuleIndex,
+ pub(super) initial: &'a InitialStyle,
+ pub(super) records: &'a Records<'a>,
+ /// What the pass produced for each element, kept for a test to check.
+ #[cfg(test)]
+ pub(super) outputs: Option<&'a [WriteOnce<ElementOutput>]>,
+ /// What to restyle, by element slot, or none to style every element.
+ pub(super) hints: Option<&'a super::live::HintCells>,
+ pub(super) reasons: Option<&'a Reasons<'a>>,
+ /// Whether the records keep what their elements matched.
+ pub(super) keeps_matches: bool,
+ /// Whether the pass styles what waits on a font or a random base value in a round of its own
+ /// once those resolve: it suspends such an element with what its ancestors ask of it, and
+ /// holds back the records of the pseudo-elements of an element until none of them waits.
+ pub(super) suspends: bool,
+ /// The group caches of the threads, by thread, which a pass keeps for the next where it
+ /// keeps its caches: an element restyled in a later pass finds the groups the elements styled
+ /// before it built.
+ pub(super) group_caches: Option<&'a super::pool::PerThread<super::compute::GroupCache>>,
+ /// Whether the pass reuses what it computed for one element for another: shares records
+ /// between elements, reuses results and pseudo-element records, and keeps the caches of its
+ /// computations across elements. A reference pass checking the others does none of that.
+ pub(super) uses_caches: bool,
+ /// What the audit of what the pass reuses asks for, as `LIBWEB_STYLE_AUDIT_CACHES` asks.
+ pub(super) cache_audit: super::self_check::Mode,
+ /// The font inputs of the document element's record from before the pass, which elements
+ /// resolve root-relative lengths against unless the pass styles the document element.
+ pub(super) held_root_font: Option<RootFontInputs>,
+ /// The font inputs of the document element where the pass styled it, which every element
+ /// after it resolves root-relative lengths against.
+ pub(super) root_font: std::sync::OnceLock<RootFontInputs>,
+ /// What of those moved from the ones the document element had before, which restyles every
+ /// element under it that reads it.
+ pub(super) root_font_moved: std::sync::OnceLock<RootFontReads>,
+}
+
+impl<'a> PassContext<'a> {
+ /// A pass over every element, whose caches work across its elements and which keeps nothing beyond its records.
+ pub(super) fn new(
+ state: &'a RetainedState,
+ index: &'a RuleIndex,
+ initial: &'a InitialStyle,
+ records: &'a Records<'a>,
+ held_root_font: Option<RootFontInputs>,
+ ) -> Self {
+ Self {
+ state,
+ index,
+ initial,
+ records,
+ #[cfg(test)]
+ outputs: None,
+ hints: None,
+ reasons: None,
+ keeps_matches: false,
+ suspends: false,
+ group_caches: None,
+ uses_caches: true,
+ cache_audit: super::self_check::Mode::Off,
+ held_root_font,
+ root_font: Default::default(),
+ root_font_moved: Default::default(),
+ }
+ }
+}
+
+pub(super) fn is_document_element(state: &RetainedState, node: StyleNodeID) -> bool {
+ state.projection.adjustment_facts(node) & bridge::element_adjustment_fact::IS_DOCUMENT_ELEMENT != 0
+}
+
+fn root_font_of(record: &Record) -> RootFontInputs {
+ RootFontInputs::from_payloads(
+ &record.payloads,
+ super::super::computed::record_dependency_flags(&record.facts(), &record.payloads),
+ )
+}
+
+/// The document element, where `root` is it or its parent.
+pub(super) fn document_element_at(state: &RetainedState, root: StyleNodeID) -> Option<StyleNodeID> {
+ match is_document_element(state, root) {
+ true => Some(root),
+ false => std::iter::successors(state.projection.first_element_child(root), |&child| {
+ state.projection.next_element_sibling(child)
+ })
+ .find(|&child| is_document_element(state, child)),
+ }
+}
+
+/// The font inputs of the record the document element under `root` holds in `records`, if any:
+/// those the last pass that styled it resolved against, or those its record holds.
+pub(super) fn held_root_font(
+ state: &RetainedState,
+ records: &Records<'_>,
+ root: StyleNodeID,
+) -> Option<RootFontInputs> {
+ let document_element = document_element_at(state, root)?;
+ let record = records.get(document_element)?;
+ Some(
+ records
+ .kept_root_font(document_element)
+ .unwrap_or_else(|| root_font_of(record)),
+ )
+}
+
+impl PassContext<'_> {
+ #[cfg(test)]
+ fn set_output(&self, node: StyleNodeID, output: impl FnOnce() -> ElementOutput) {
+ if let Some(outputs) = self.outputs {
+ let _ = outputs[node.element_slot()].set(output());
+ }
+ }
+
+ fn root_font(&self) -> Option<RootFontInputs> {
+ self.root_font.get().copied().or(self.held_root_font)
+ }
+
+ fn root_font_moved(&self) -> RootFontReads {
+ self.root_font_moved.get().copied().unwrap_or_default()
+ }
+
+ /// Whether `node` resolves lengths against what moved of the document element's font.
+ fn reads_root_font_move(&self, node: StyleNodeID) -> bool {
+ let moved = self.root_font_moved();
+ moved != RootFontReads::None && self.records.reads_root_font(node).reads_move(moved)
+ }
+
+ /// Note the font inputs of the record the pass gave the document element `node`.
+ fn note_root_font(&self, node: StyleNodeID) {
+ let Some(record) = self.records.get(node) else {
+ return;
+ };
+ let root_font = root_font_of(record);
+ let previous = self
+ .held_root_font
+ .unwrap_or_else(|| RootFontInputs::from_document(&self.state.document_style_computation_inputs));
+ if self.root_font.set(root_font).is_ok() {
+ let _ = self.root_font_moved.set(root_font.moved_from(previous));
+ }
+ }
+
+ fn hint(&self, node: StyleNodeID) -> HintBits {
+ self.hints.map_or(
+ RESTYLE_SELF | RESTYLE_DESCENDANTS | MATCH_SELF | MATCH_DESCENDANTS,
+ |hints| hints.get(node.element_slot()).map_or(0, |cell| cell.bits),
+ )
+ }
+}
+
+#[derive(Default)]
+pub(super) struct Statistics {
+ pub(super) match_counters: MatchCounters,
+ pub(super) cascade_counters: CascadeCounters,
+ /// The fonts a drive waited on, to resolve before styling again.
+ pub(super) font_requests: Vec<font_resolution::FontRequest>,
+ /// The random caching keys a computation needed the base values of, to draw before styling
+ /// again.
+ pub(super) random_requests: Vec<RandomBaseRequest>,
+ /// The elements whose styles waited on those, which the pass styled nothing below.
+ pub(super) waiting: Vec<StyleNodeID>,
+ /// The elements of `waiting` the pass matched to the entries they held matched before, which
+ /// the next pass computes again from those without matching them.
+ pub(super) waiting_with_kept_matches: Vec<StyleNodeID>,
+ /// The elements the pass styled but for some of their pseudo-elements, whose styles waited on
+ /// those.
+ pub(super) waiting_pseudo_elements: Vec<StyleNodeID>,
+ /// What the pass suspended of those, where it suspends, for its next round to resume.
+ pub(super) suspended: Vec<Suspended>,
+ pub(super) pseudo_elements_declined: u64,
+ /// The elements the pass styled.
+ pub(super) styled: Vec<StyleNodeID>,
+ /// The elements that took the custom properties their parents hand down now without being
+ /// styled, keeping their style otherwise.
+ pub(super) moved_custom_properties: Vec<StyleNodeID>,
+ /// How many of those it styled differently than before, in what their children compute from.
+ pub(super) changed_elements: u64,
+ /// The children of elements whose records moved beneath the composition of their animations,
+ /// with the hints the pass kept for them, which the next pass restyles once the host composed
+ /// the animations over the new records.
+ pub(super) deferred: Vec<(StyleNodeID, HintBits)>,
+ /// The elements the pass restyled for their pseudo-elements alone.
+ pub(super) restyled_for_pseudo_elements: Vec<StyleNodeID>,
+ /// How many elements took the record of another.
+ pub(super) outcomes: super::counters::OutcomeCounts,
+ /// What `LIBWEB_STYLE_AUDIT_CACHES` found of what the pass reused, where it is set.
+ pub(super) cache_audit: cache_audit::CacheAudit,
+}
+
+/// What a pass suspended on fonts and random base values, for its next round to style once they
+/// resolve.
+pub(super) enum Suspended {
+ /// An element whose style waited, with what its ancestors ask of it: the round styles it and
+ /// the elements under it as if it had not waited.
+ Element(Queued),
+ /// The pseudo-elements of an element the pass styled, some of which waited.
+ PseudoElements(SuspendedPseudoElements),
+}
+
+/// The pseudo-elements of an element a pass styled but for some of them, which waited.
+pub(super) struct SuspendedPseudoElements {
+ node: StyleNodeID,
+ /// The matches of the element, and those whose container conditions held, which the
+ /// pseudo-elements are styled from.
+ matches: Vec<ElementMatch>,
+ applied: Vec<ElementMatch>,
+ gated: bool,
+ /// The records of those that did not wait, which the element keeps where no round follows.
+ records: super::records::PseudoElementRecords,
+}
+
+impl Suspended {
+ fn node(&self) -> StyleNodeID {
+ match self {
+ Self::Element(queued) => queued.node,
+ Self::PseudoElements(pseudo_elements) => pseudo_elements.node,
+ }
+ }
+}
+
+/// One thread's working state.
+/// How many longhand table flags a thread keeps for the records it makes next to share.
+const TABLE_FLAGS_KEPT: usize = 4;
+
+/// How many of the rare facts of the records it made last a thread keeps to share with the next.
+const RARE_FACTS_KEPT: usize = 8;
+
+struct Scratch<'a> {
+ matcher: Matcher<'a>,
+ cascade: Cascade,
+ filter: AncestorFilter,
+ /// The elements whose keys the filter holds, root first, with those keys.
+ ancestors: Vec<(StyleNodeID, SmallVec<[u32; 8]>)>,
+ matches: Vec<ElementMatch>,
+ /// What the entries an element was rematched for answer now, and whether one answers other
+ /// than it did before.
+ reason_answers: Vec<bool>,
+ reason_flipped: bool,
+ /// The matches of the element styled last whose container conditions hold, which its cascade
+ /// reads in place of `matches` where `gated`.
+ applied: Vec<ElementMatch>,
+ /// Whether the element styled last matched a rule applying under container conditions.
+ gated: bool,
+ /// What the container conditions of the element styled last read of its containers.
+ container_reads: Option<ContainerVerdict>,
+ /// What the thread measured and gathered, which the pass adds up.
+ statistics: Statistics,
+ substitutions: std::cell::RefCell<super::custom_properties::SubstitutionCache>,
+ sharing: SharingCache,
+ moved_names: super::custom_property_moves::MovedCustomProperties,
+ /// The pseudo-element records a thread computed, by kind, what they inherit from their
+ /// element and their winners: a pseudo-element's style is a function of those alone, where no
+ /// winner computes against the element itself or takes its value of a property that does not
+ /// inherit.
+ pseudo_elements: crate::fast_hash::FastMap<PseudoElementKey, std::sync::Arc<Record>>,
+ results: ResultCache,
+ /// The longhand table flags of the records the thread made last, most recent first, which the
+ /// next record holding the same flags shares.
+ table_flags: SmallVec<[std::sync::Arc<crate::css::computed_longhand_table::LonghandTableFlags>; TABLE_FLAGS_KEPT]>,
+ /// The rare sets of the records the thread made last, most recent first, whose rare facts
+ /// the next record recording the same shares, and whose set it shares where it holds the same
+ /// rare groups.
+ rare_facts: SmallVec<[crate::css::computed_values::RareSetRef; RARE_FACTS_KEPT]>,
+ /// The record of the element the thread styled last, whose group sets the next record holding
+ /// the same groups there shares, as the siblings of a list styled alike do.
+ last_record: Option<std::sync::Arc<Record>>,
+ /// The match lists of the elements the thread styled last, most recent first.
+ kept_match_lists: SmallVec<[super::records::MatchList; RARE_FACTS_KEPT]>,
+ groups: super::compute::GroupCache,
+ absolutized: crate::css::style_compute::AbsolutizedValues,
+ custom_property_stores: super::custom_properties::StoreCache,
+ revalidation_matches: Vec<ElementMatch>,
+ /// Whether the shadow host the scratch styled last moved the matches of its pseudo-elements
+ /// that elements of its shadow tree stand for, which are restyled with it then.
+ backing_elements_moved: bool,
+ /// What `LIBWEB_STYLE_AUDIT_CACHES` found of what the pass reused, where it is set.
+ cache_audit: Option<Box<cache_audit::CacheAudit>>,
+ /// The kinds of the pseudo-elements of the element styled last whose records came from
+ /// `pseudo_elements`, kept for the audit alone.
+ pseudo_element_cache_hits: SmallVec<[u8; 2]>,
+}
+
+impl<'a> Scratch<'a> {
+ fn new(context: &PassContext<'a>) -> Self {
+ let state = context.state;
+ Self {
+ matcher: Matcher::new(context.index, state),
+ cascade: Cascade::new(),
+ filter: AncestorFilter::new(),
+ ancestors: Vec::new(),
+ matches: Vec::new(),
+ reason_answers: Vec::new(),
+ reason_flipped: false,
+ applied: Vec::new(),
+ gated: false,
+ container_reads: None,
+ statistics: Statistics::default(),
+ substitutions: Default::default(),
+ sharing: SharingCache::default(),
+ moved_names: Default::default(),
+ pseudo_elements: Default::default(),
+ results: ResultCache::default(),
+ table_flags: SmallVec::new(),
+ rare_facts: SmallVec::new(),
+ last_record: None,
+ kept_match_lists: SmallVec::new(),
+ groups: Default::default(),
+ absolutized: Default::default(),
+ custom_property_stores: Default::default(),
+ revalidation_matches: Vec::new(),
+ backing_elements_moved: false,
+ cache_audit: cache_audit::CacheAudit::for_pass(context),
+ pseudo_element_cache_hits: SmallVec::new(),
+ }
+ }
+
+ /// `flags`, shared with the record the thread made last holding the same flags, if any.
+ fn shared_table_flags(
+ &mut self,
+ flags: crate::css::computed_longhand_table::LonghandTableFlags,
+ ) -> std::sync::Arc<crate::css::computed_longhand_table::LonghandTableFlags> {
+ let kept = &mut self.table_flags;
+ if let Some(index) = kept.iter().position(|held| held.same_as(&flags)) {
+ kept[..=index].rotate_right(1);
+ return kept[0].clone();
+ }
+ let flags = std::sync::Arc::new(flags);
+ if kept.len() == TABLE_FLAGS_KEPT {
+ kept.pop();
+ }
+ kept.insert(0, flags.clone());
+ flags
+ }
+
+ /// `rare`, shared with the record the thread made last recording the same, if any: the
+ /// siblings of a list mostly record alike.
+ fn interned_rare(
+ kept: &mut SmallVec<[crate::css::computed_values::RareSetRef; RARE_FACTS_KEPT]>,
+ rare: RareStyleFacts,
+ groups: crate::css::computed_values::StyleGroups,
+ custom_winners: &[(
+ super::rule_store::CustomDeclaration,
+ crate::css::style_value::RetainedStyleValueData,
+ )],
+ ) -> crate::css::computed_values::StyleGroups {
+ let declarations_of = |winners: &[_]| (!winners.is_empty()).then(|| winners.into());
+ if let Some(index) = kept.iter().position(|held| held.facts().same_as(&rare)) {
+ kept[..=index].rotate_right(1);
+ // NB: The written values are what a sample resolves, so holding the same ones is what makes
+ // two elements' declarations the same.
+ let custom_declarations = match kept[0].custom_declarations() {
+ Some(held)
+ if held.len() == custom_winners.len()
+ && held
+ .iter()
+ .zip(custom_winners)
+ .all(|(held, winner)| held.0 == winner.0 && held.1.pointer() == winner.1.pointer()) =>
+ {
+ Some(held.clone())
+ }
+ _ => declarations_of(custom_winners),
+ };
+ let groups = groups.with_rare_facts(kept[0].facts().clone(), custom_declarations, &[Some(&kept[0])]);
+ if !groups.rare_set().ptr_eq(&kept[0]) {
+ kept[0] = groups.rare_set().clone();
+ }
+ return groups;
+ }
+ let groups = groups.with_rare_facts(std::sync::Arc::new(rare), declarations_of(custom_winners), &[]);
+ if kept.len() == RARE_FACTS_KEPT {
+ kept.pop();
+ }
+ kept.insert(0, groups.rare_set().clone());
+ groups
+ }
+
+ /// The entries the element just matched, shared with the element the thread styled last that
+ /// matched the same ones, if any: the siblings of a list mostly match alike.
+ fn interned_matches(&mut self) -> super::records::MatchList {
+ let matched = || self.matches.iter().map(|matched| matched.entry);
+ let kept = &mut self.kept_match_lists;
+ if let Some(index) = kept.iter().position(|held| held.iter().copied().eq(matched())) {
+ kept[..=index].rotate_right(1);
+ return kept[0].clone();
+ }
+ let matches: super::records::MatchList = std::sync::Arc::new(matched().collect());
+ if kept.len() == RARE_FACTS_KEPT {
+ kept.pop();
+ }
+ kept.insert(0, matches.clone());
+ matches
+ }
+
+ /// Forget what the computations of the elements styled before cached, for the next to compute
+ /// from nothing they left.
+ fn forget_caches(&mut self) {
+ *self.substitutions.get_mut() = Default::default();
+ self.groups = Default::default();
+ self.absolutized = Default::default();
+ self.custom_property_stores = Default::default();
+ }
+
+ /// Make the filter hold exactly the keys of `parent` and its ancestors.
+ fn enter_parent(&mut self, context: &PassContext<'_>, parent: Option<StyleNodeID>) {
+ if self.ancestors.last().map(|(node, _)| *node) == parent {
+ return;
+ }
+ let tree = &context.state.projection;
+ let mut chain: SmallVec<[StyleNodeID; 32]> = SmallVec::new();
+ let mut ancestor = parent;
+ while let Some(node) = ancestor {
+ chain.push(node);
+ ancestor = tree.parent(node);
+ }
+ chain.reverse();
+ let common = self
+ .ancestors
+ .iter()
+ .zip(&chain)
+ .take_while(|((held, _), wanted)| held == *wanted)
+ .count();
+ while self.ancestors.len() > common {
+ let (_, keys) = self.ancestors.pop().expect("an ancestor was held");
+ for key in keys {
+ self.filter.remove(key);
+ }
+ }
+ let projection = &context.state.projection;
+ for &node in &chain[common..] {
+ let keys = projection
+ .row_of(node)
+ .map_or_else(SmallVec::new, super::ancestor_keys_of);
+ for &key in &keys {
+ self.filter.insert(key);
+ }
+ self.ancestors.push((node, keys));
+ }
+ }
+
+ /// Test `node` against the entries of `reasons` alone, into `reason_answers`, and note in
+ /// `reason_flipped` whether one answers other than before, or answer that it has to be matched
+ /// against the whole index.
+ fn test_reasons(&mut self, context: &PassContext<'_>, node: StyleNodeID, reasons: &[u32]) -> bool {
+ let Some(before) = context.records.matches_of(node) else {
+ return false;
+ };
+ let scoped = |entry: &u32| context.index.entries.view(*entry as usize).scoped();
+ // The entries of other trees that reach an element are matched from those trees.
+ if (context.index.has_scoped_entries() && (before.iter().any(scoped) || reasons.iter().any(scoped)))
+ || self.matcher.is_reached_from_other_trees(node)
+ {
+ return false;
+ }
+ self.reason_answers.clear();
+ self.reason_flipped = false;
+ for &reason in reasons {
+ let Ok(now) = self.matcher.matches_entry(node, reason) else {
+ return false;
+ };
+ self.reason_flipped |= now != before.binary_search(&reason).is_ok();
+ self.reason_answers.push(now);
+ }
+ true
+ }
+
+ /// The matches of `node` from the answers `test_reasons` left: those of `reasons` that hold,
+ /// and its other matches from before.
+ fn merge_reason_answers(&mut self, context: &PassContext<'_>, node: StyleNodeID, reasons: &[u32]) {
+ self.matches.clear();
+ // Both lists are in index order, as the matches have to be.
+ let mut kept = context
+ .records
+ .matches_of(node)
+ .map_or(&[][..], |before| &before[..])
+ .iter()
+ .copied()
+ .peekable();
+ for (&reason, &holds) in reasons.iter().zip(&self.reason_answers) {
+ while let Some(entry) = kept.next_if(|&entry| entry < reason) {
+ self.matches.push(self.matcher.element_match(node, entry));
+ }
+ kept.next_if_eq(&reason);
+ if holds {
+ self.matches.push(self.matcher.element_match(node, reason));
+ }
+ }
+ for entry in kept {
+ self.matches.push(self.matcher.element_match(node, entry));
+ }
+ }
+
+ /// Match, cascade and compute `node`, against the whole index where `reasons` is none and only
+ /// the entries of it otherwise, and answer whether its children are styled too. `moved` holds
+ /// the bits of its hint naming what moved of what it computes from besides its matches.
+ fn style_element(
+ &mut self,
+ context: &PassContext<'_>,
+ node: StyleNodeID,
+ reasons: Option<&[u32]>,
+ moved: HintBits,
+ ) -> bool {
+ let state = context.state;
+ if !context.uses_caches {
+ self.forget_caches();
+ }
+ self.statistics.styled.push(node);
+ self.backing_elements_moved = false;
+ self.gated = false;
+ self.container_reads = None;
+ self.pseudo_element_cache_hits.clear();
+ // The elements of a shadow tree standing for its host's pseudo-elements are styled from
+ // the host's matches for them, which no invalidation of theirs follows.
+ let matched_before = state
+ .projection
+ .shadow_root_of(node)
+ .map(|_| context.records.matches_of(node).cloned());
+ let facts = state.projection.facts(node);
+ let rematched = context.keeps_matches
+ && match (facts, reasons) {
+ (Some(_), Some(reasons)) => self.test_reasons(context, node, reasons),
+ _ => false,
+ };
+ // What an element matches, its parent and its containers decide its style. Its matches
+ // are the ones it had where no entry it was rematched for answers otherwise.
+ if rematched
+ && !self.reason_flipped
+ && moved & (PARENT_CHANGED | CONTAINERS_MOVED | RECOMPUTE_SELF) == 0
+ && (moved & PARENT_RESTYLED == 0
+ || state
+ .projection
+ .inheritance_parent(node)
+ .is_some_and(|parent| context.records.child_impact(parent) == ChildImpact::None))
+ && !context.reads_root_font_move(node)
+ && context.records.keep_previous(node)
+ {
+ return Self::children_are_styled(context, node);
+ }
+ if let (true, Some(reasons)) = (rematched, reasons) {
+ self.merge_reason_answers(context, node, reasons);
+ }
+ // An element standing for its shadow host's pseudo-element is styled from the host's
+ // rules, which no other element's style tells.
+ let backed = state.backed_host_pseudo_element(node);
+ let key = facts
+ .filter(|_| backed.is_none() && context.uses_caches)
+ .and_then(|facts| super::sharing::key_of(state, context.index, context.records, node, facts));
+ // The ancestor filter holds the element's ancestors in its own tree, which the rules of
+ // that tree test, and not the flat tree ancestors it inherits from. An element keeping
+ // its matches tests rules only to share a style.
+ let parent = state.projection.parent(node);
+ if !rematched || key.is_some() {
+ self.enter_parent(context, parent);
+ debug_assert!(
+ self.ancestors
+ .iter()
+ .rev()
+ .map(|(ancestor, _)| *ancestor)
+ .eq(state.projection.ancestors(node))
+ );
+ }
+ // An element matching what it matched before shares the style of another as one matched
+ // anew does: the revalidation answers and what the key holds decide its matches alike.
+ if let (Some(facts), Some(key)) = (facts, &key) {
+ let (matcher, filter, revalidation_matches) =
+ (&mut self.matcher, &self.filter, &mut self.revalidation_matches);
+ let shared = self.sharing.find(&context.state.projection, key, facts, || {
+ revalidation_matches.clear();
+ matcher
+ .match_revalidation_entries(node, facts, filter, revalidation_matches)
+ .ok()
+ .map(|()| super::sharing::revalidation_of(context.index, revalidation_matches))
+ });
+ if let Some((record, identity)) = shared {
+ let matches = context.records.matches_of(identity).cloned();
+ if let Some(before) = &matched_before {
+ self.backing_elements_moved = Self::moves_backing_elements(
+ context,
+ node,
+ before.as_ref().map(|before| &before[..]),
+ matches.as_deref().map(|matches| matches.iter().copied()),
+ );
+ }
+ context.records.insert(node, record, identity, matches);
+ // Elements sharing a style match the same rules, their pseudo-elements' too.
+ let pseudo_element_records = context.records.pseudo_element_records(identity).into();
+ context
+ .records
+ .insert_pseudo_element_records(node, pseudo_element_records);
+ self.statistics.outcomes.note(&Outcome::Shared);
+ self.audit_caches(context, node, cache_audit::Reuse::SharedStyle);
+ #[cfg(test)]
+ context.set_output(node, || ElementOutput {
+ matches: None,
+ outcome: Outcome::Shared,
+ });
+ return Self::children_are_styled(context, node);
+ }
+ }
+ let matched = rematched || {
+ self.matches.clear();
+ facts.is_some_and(|facts| {
+ self.statistics.outcomes.note_matched();
+ self.matcher
+ .match_element(node, facts, &self.filter, &mut self.matches)
+ .is_ok()
+ })
+ };
+ if matched {
+ self.apply_container_gates(context, node, false);
+ }
+ let cascaded = matched && self.cascade_element(context, node, backed);
+ let outcome = if !cascaded {
+ Outcome::CascadeDeclined
+ } else {
+ let computed = self.compute(context, node);
+ match computed {
+ Ok((record, computed)) => {
+ if let Some(before) = &matched_before {
+ self.backing_elements_moved = Self::moves_backing_elements(
+ context,
+ node,
+ before.as_ref().map(|before| &before[..]),
+ Some(self.matches.iter().map(|matched| matched.entry)),
+ );
+ }
+ let matches = context.keeps_matches.then(|| self.interned_matches());
+ context.records.insert(node, record.clone(), node, matches);
+ // The document element's font is what the root-relative lengths of every
+ // element after it resolve against.
+ if is_document_element(state, node) {
+ context.note_root_font(node);
+ }
+ let pseudo_elements_element_dependent = self.compute_pseudo_elements(context, node);
+ if let Some(reads) = self.container_reads.take() {
+ context.records.insert_container_reads(node, std::sync::Arc::new(reads));
+ }
+ // An element sharing this style takes its pseudo-elements' records too, so
+ // neither may compute against the element itself, nor against the containers
+ // above it.
+ if let (true, Some(key), false) = (
+ facts.is_some(),
+ key,
+ computed.element_dependent || pseudo_elements_element_dependent || self.gated,
+ ) {
+ let revalidation = super::sharing::revalidation_of(context.index, &self.matches);
+ self.sharing.insert(key, record, node, revalidation);
+ }
+ self.audit_caches(
+ context,
+ node,
+ match computed.reused {
+ true => cache_audit::Reuse::ReusedResult,
+ false => cache_audit::Reuse::ComputationCaches,
+ },
+ );
+ match computed.reused {
+ true => Outcome::Reused,
+ false => Outcome::Computed {
+ directly: computed.directly,
+ },
+ }
+ }
+ Err(outcome) => outcome,
+ }
+ };
+ let unstyled = matches!(outcome, Outcome::CascadeDeclined | Outcome::ComputeDeclined);
+ // An element waiting on a font that matched what it held matched before keeps those
+ // matches, which the next pass computes it from again.
+ if unstyled
+ && matched
+ && self.statistics.waiting.last() == Some(&node)
+ && context.records.matches_of(node).is_some_and(|before| {
+ before.len() == self.matches.len()
+ && before
+ .iter()
+ .zip(&self.matches)
+ .all(|(&entry, matched)| entry == matched.entry)
+ })
+ {
+ self.statistics.waiting_with_kept_matches.push(node);
+ }
+ self.statistics.outcomes.note(&outcome);
+ #[cfg(test)]
+ context.set_output(node, || ElementOutput {
+ matches: matched.then(|| self.matches.clone()),
+ outcome,
+ });
+ // An element this pass holds no record for, such as one waiting on a font, has no style
+ // for its children to inherit. The pass that styles it styles them.
+ !unstyled && Self::children_are_styled(context, node)
+ }
+
+ /// Whether the shadow host `node`, matching `after` where it matched `before`, moved the
+ /// matches of a pseudo-element an element of its shadow tree stands for.
+ fn moves_backing_elements(
+ context: &PassContext<'_>,
+ node: StyleNodeID,
+ before: Option<&[u32]>,
+ after: Option<impl Iterator<Item = u32>>,
+ ) -> bool {
+ let state = context.state;
+ let pseudo_entries = |entries: &mut dyn Iterator<Item = u32>| -> SmallVec<[u32; 8]> {
+ entries
+ .filter(|&entry| context.index.entries.view(entry as usize).pseudo_element())
+ .collect()
+ };
+ let (Some(before), Some(after)) = (before, after) else {
+ return true;
+ };
+ let before = pseudo_entries(&mut before.iter().copied());
+ let after = pseudo_entries(&mut after.into_iter());
+ if before == after {
+ return false;
+ }
+ let moved_kinds: SmallVec<[u8; 4]> = before
+ .iter()
+ .filter(|entry| !after.contains(entry))
+ .chain(after.iter().filter(|entry| !before.contains(entry)))
+ .map(|&entry| context.index.entries.view(entry as usize).pseudo_kind())
+ .collect();
+ let tree = &state.projection;
+ tree.shadow_root_of(node).is_some_and(|root| {
+ tree.preorder(root).skip(1).any(|element| {
+ state
+ .projection
+ .associated_pseudo_kind(element)
+ .is_some_and(|kind| moved_kinds.contains(&kind))
+ })
+ })
+ }
+
+ /// Cascade `node` from its matches, or from the matches of the shadow host whose
+ /// pseudo-element it stands for where it is `backed`, and answer whether it matched.
+ fn cascade_element(
+ &mut self,
+ context: &PassContext<'_>,
+ node: StyleNodeID,
+ backed: Option<(u8, StyleNodeID)>,
+ ) -> bool {
+ let state = context.state;
+ let Some((kind, host)) = backed else {
+ let matches = match self.gated {
+ true => &self.applied,
+ false => &self.matches,
+ };
+ self.cascade.cascade_element(state, context.index, node, matches);
+ return true;
+ };
+ let projection = &state.projection;
+ let Some(host_facts) = projection.facts(host) else {
+ return false;
+ };
+ // The host is matched in its own tree, against the keys of its ancestors there.
+ let mut filter = AncestorFilter::new();
+ for row in projection
+ .ancestors(host)
+ .filter_map(|ancestor| projection.row_of(ancestor))
+ {
+ for key in super::ancestor_keys_of(row) {
+ filter.insert(key);
+ }
+ }
+ let mut host_matches = Vec::new();
+ let matched = self
+ .matcher
+ .match_element(host, host_facts, &filter, &mut host_matches)
+ .is_ok();
+ // The host's rules for its pseudo-element apply where their container conditions hold
+ // for that pseudo-element.
+ let index = context.index;
+ if index.has_gates() {
+ let mut last: Option<(ContainerGateID, bool)> = None;
+ host_matches.retain(|matched| {
+ let Some(gate) = index.gate_of_entry(matched.entry) else {
+ return true;
+ };
+ match last {
+ Some((last_gate, holds)) if last_gate == gate => holds,
+ _ => {
+ let verdict = gate_verdict(context, gate, host, true);
+ let holds = verdict.matches;
+ self.container_reads.get_or_insert_default().add_reads(verdict);
+ last = Some((gate, holds));
+ holds
+ }
+ }
+ });
+ }
+ if matched {
+ self.cascade
+ .cascade_backing_element(state, context.index, node, &host_matches, kind);
+ }
+ matched
+ }
+
+ /// Compute the styles of the pseudo-elements of `node` that generate a box, one kind at a time,
+ /// each cascading its own rules over the element's style. Returns whether any of their records
+ /// computes against the element itself, such as its place among its siblings.
+ fn compute_pseudo_elements(&mut self, context: &PassContext<'_>, node: StyleNodeID) -> bool {
+ let waiting = self.statistics.waiting_pseudo_elements.len();
+ let Some((pseudo_element_records, element_dependent)) = self.styled_pseudo_elements(context, node) else {
+ return false;
+ };
+ // A pass that suspends styles the pseudo-elements of an element again in its next round
+ // where some waited, and holds back their records until then.
+ if context.suspends && self.statistics.waiting_pseudo_elements.len() != waiting {
+ self.statistics
+ .suspended
+ .push(Suspended::PseudoElements(SuspendedPseudoElements {
+ node,
+ matches: self.matches.clone(),
+ applied: match self.gated {
+ true => self.applied.clone(),
+ false => Vec::new(),
+ },
+ gated: self.gated,
+ records: pseudo_element_records,
+ }));
+ return element_dependent;
+ }
+ context
+ .records
+ .insert_pseudo_element_records(node, pseudo_element_records);
+ element_dependent
+ }
+
+ /// Style the pseudo-elements of an element a round before styled but for some of them, from
+ /// the matches it styled them from, now that what they waited on resolved.
+ fn resume_pseudo_elements(&mut self, context: &PassContext<'_>, suspended: SuspendedPseudoElements) {
+ let SuspendedPseudoElements {
+ node,
+ matches,
+ applied,
+ gated,
+ records: _,
+ } = suspended;
+ self.matches = matches;
+ self.applied = applied;
+ self.gated = gated;
+ self.container_reads = None;
+ self.pseudo_element_cache_hits.clear();
+ self.compute_pseudo_elements(context, node);
+ // NB: The round before kept what the container conditions of the element's rules read,
+ // which reading them again here repeats.
+ self.container_reads = None;
+ }
+
+ /// The records of the pseudo-elements of `node` that generate a box, over the record `context`
+ /// holds for it, and whether any of them computes against the element itself, or none where
+ /// it holds no record.
+ fn styled_pseudo_elements(
+ &mut self,
+ context: &PassContext<'_>,
+ node: StyleNodeID,
+ ) -> Option<(super::records::PseudoElementRecords, bool)> {
+ let mut pseudo_element_records = super::records::PseudoElementRecords::new();
+ let mut element_dependent = false;
+ let element = context.records.get_shared(node).cloned()?;
+ if element.facts().display().is_none() {
+ return Some((pseudo_element_records, element_dependent));
+ }
+ // NB: Only what a rule styles generates a box here, the marker of a list item and the
+ // highlights the host shows in the element apart, each of which is unstyled otherwise.
+ let matches = match self.gated {
+ true => &self.applied,
+ false => &self.matches,
+ };
+ let mut kinds = matches.iter().fold(0_u32, |kinds, matched| {
+ kinds | 1_u32.checked_shl(u32::from(matched.pseudo_kind)).unwrap_or(0)
+ });
+ if element.facts().display().is_list_item() {
+ kinds |= 1 << super::super::publication::pseudo_kind::MARKER;
+ }
+ if context.state.highlight_observers.kinds_of(node) != 0 {
+ for kind in super::HIGHLIGHT_KINDS {
+ if context.state.highlight_observers.observes(node, kind) {
+ kinds |= 1 << kind;
+ }
+ }
+ }
+ if kinds == 0 {
+ return Some((pseudo_element_records, element_dependent));
+ }
+ let inherited = PseudoElementInheritance::of(context, node, &element);
+ // The conditions of a pseudo-element's rules ask about its element's record first.
+ self.apply_container_gates(context, node, true);
+ for kind in super::PSEUDO_ELEMENT_KINDS {
+ if kinds & (1 << kind) == 0 {
+ continue;
+ }
+ match self.compute_pseudo_element(context, node, &element, &inherited, kind, PseudoElementRead::Generating)
+ {
+ PseudoElementOutcome::Computed {
+ record,
+ element_dependent: dependent,
+ } => {
+ element_dependent |= dependent;
+ pseudo_element_records.push((kind, record));
+ }
+ PseudoElementOutcome::Declined => self.statistics.pseudo_elements_declined += 1,
+ // A pseudo-element waiting on a font or a random base value is styled again with
+ // its element once those resolved. Until then its element shares its records with
+ // no other.
+ PseudoElementOutcome::Waiting => element_dependent = true,
+ PseudoElementOutcome::Unstyled | PseudoElementOutcome::GeneratesNoBox => {}
+ }
+ }
+ Some((pseudo_element_records, element_dependent))
+ }
+
+ /// Compute the style of the pseudo-element of `kind` of `node`, whose record is `element`, from the
+ /// rules it matched for it, cascaded over what it inherits, `inherited`. Which pseudo-elements
+ /// are styled is what `read` says.
+ fn compute_pseudo_element(
+ &mut self,
+ context: &PassContext<'_>,
+ node: StyleNodeID,
+ element: &std::sync::Arc<Record>,
+ inherited: &PseudoElementInheritance,
+ kind: u8,
+ read: PseudoElementRead,
+ ) -> PseudoElementOutcome {
+ let state = context.state;
+ let matches: &[ElementMatch] = match self.gated {
+ true => &self.applied,
+ false => &self.matches,
+ };
+ let has_rules = matches.iter().any(|matched| matched.pseudo_kind == kind);
+ let generating = read == PseudoElementRead::Generating;
+ let highlight = super::HIGHLIGHT_KINDS.contains(&kind);
+ // A pass styles the highlight pseudo-elements of the elements the host shows a highlight
+ // of their kind in, and a read of their styles those of any other.
+ if generating && highlight && !state.highlight_observers.observes(node, kind) {
+ return PseudoElementOutcome::Unstyled;
+ }
+ // https://drafts.csswg.org/css-position-4/#backdrop
+ // Only an element rendered in the top layer generates a ::backdrop box.
+ if generating
+ && kind == super::super::publication::pseudo_kind::BACKDROP
+ && state.projection.adjustment_facts(node) & bridge::element_adjustment_fact::RENDERED_IN_TOP_LAYER == 0
+ {
+ return PseudoElementOutcome::Unstyled;
+ }
+ // https://drafts.csswg.org/css-pseudo-4/#highlight-cascade
+ // A highlight pseudo-element no rule styles still inherits the one of an ancestor.
+ let highlight_parent = highlight
+ .then(|| context.records.highlight_inheritance_parent(node, kind))
+ .flatten();
+ if !read.styles(kind, has_rules || highlight_parent.is_some(), element) {
+ return PseudoElementOutcome::Unstyled;
+ }
+ self.cascade
+ .cascade_pseudo_element(state, context.index, node, matches, kind);
+ // A pseudo-element's own custom properties resolve over what its element hands down,
+ // as a child's do.
+ let subject = SubstitutionSubject::new(context, node, Some(kind));
+ let custom_properties_read_subject = self
+ .cascade
+ .custom_winners
+ .iter()
+ .any(|(_, value)| value_reads_substitution_subject(value.data()));
+ let Some(custom_properties) = state.custom_property_store(
+ inherited.handed_down.as_ref(),
+ inherited.held.as_ref(),
+ &self.cascade.custom_winners,
+ &mut self.custom_property_stores,
+ &subject,
+ ) else {
+ return PseudoElementOutcome::Declined;
+ };
+ if generating && !state.pseudo_content_generates(&self.cascade.winners, kind) {
+ return PseudoElementOutcome::GeneratesNoBox;
+ }
+ // https://drafts.css-houdini.org/css-properties-values-api-1/#animation-behavior-of-custom-properties
+ // The pseudo-element's other properties substitute the animated values of its custom
+ // properties, which the host sampled over the environment it holds, as an element's do.
+ let sampled_custom_properties = context.records.sampled_pseudo_element_custom_properties(node, kind);
+ let key = PseudoElementKey {
+ kind,
+ inherited_groups: inherited.groups,
+ color: inherited.color,
+ inherited_values: inherited.inherited_values,
+ element_dependency_flags: inherited.dependency_flags,
+ display: {
+ let display = element.facts().display();
+ [
+ display.tag,
+ display.outside,
+ display.inside,
+ u8::from(display.list_item),
+ display.internal,
+ display.box_value,
+ ]
+ },
+ custom_properties: inherited
+ .handed_down
+ .as_ref()
+ .map_or(0, |store| std::sync::Arc::as_ptr(store) as usize),
+ winners: self.cascade.winners.clone(),
+ custom_winners: self
+ .cascade
+ .custom_winners
+ .iter()
+ .map(|(declaration, value)| (*declaration, value.pointer() as usize))
+ .collect(),
+ animation_name_scope: self.cascade.animation_name_scope,
+ highlight_parent: highlight_parent.map_or(0, super::records::HighlightParent::identity),
+ counter_style_environment: state.counter_style_environment_identity_of(node),
+ };
+ if sampled_custom_properties.is_none()
+ && context.uses_caches
+ && let Some(record) = self.pseudo_elements.get(&key)
+ {
+ if self.cache_audit.is_some() {
+ self.pseudo_element_cache_hits.push(kind);
+ }
+ return PseudoElementOutcome::Computed {
+ record: record.clone(),
+ element_dependent: false,
+ };
+ }
+ let group_seeds = context
+ .initial
+ .group_seeds(context.records.get_shared(inherited.parent));
+ let requested = self.requested();
+ // NB: The pseudo-element's custom properties above resolved their style queries against
+ // its element's record, as it computed nothing yet.
+ subject.asked_pseudo_element_style.set(false);
+ let driven = drive_with_registered_properties(|computed_store| {
+ let mut suspended_font = None;
+ let substituted = computed_store.unwrap_or(&custom_properties);
+ let sampled = sampled_custom_properties
+ .as_ref()
+ .map(|sampled| sampled.animation_overlay_over(substituted.as_ref()));
+ let driven = state.drive_element(
+ context.records,
+ node,
+ Some((inherited.parent, inherited.color)),
+ context.initial,
+ &self.cascade.winners,
+ &super::cascade::CascadeBelow {
+ cascade: &self.cascade,
+ state,
+ node,
+ },
+ &mut suspended_font,
+ &mut self.statistics.random_requests,
+ super::custom_properties::CustomPropertyStores {
+ own: sampled.as_ref().or(substituted.as_ref()),
+ inherited: inherited.held.as_ref(),
+ substitutions: &self.substitutions,
+ subject: &subject,
+ },
+ &mut self.groups,
+ &mut self.absolutized,
+ kind,
+ context.root_font(),
+ group_seeds,
+ );
+ if let Some(request) = suspended_font {
+ self.statistics.font_requests.push(request);
+ }
+ let Ok(mut computed) = driven else {
+ return Err(match self.pseudo_element_waits(node, requested) {
+ true => PseudoElementOutcome::Waiting,
+ false => PseudoElementOutcome::Declined,
+ });
+ };
+ computed.element_dependent |= custom_properties_read_subject;
+ let registered = state.registered_custom_property_store(
+ node,
+ inherited.handed_down.as_ref(),
+ inherited.held.as_ref(),
+ &self.cascade.custom_winners,
+ &mut computed,
+ &subject,
+ &mut self.statistics.random_requests,
+ );
+ if self.pseudo_element_waits(node, requested) {
+ return Err(PseudoElementOutcome::Waiting);
+ }
+ let computes_again = subject
+ .computes_again_against_own_style(&computed.groups, computed.facts.publication_dependency_flags());
+ Ok(DrivenWithRegisteredProperties {
+ computed,
+ registered,
+ computes_again,
+ })
+ });
+ let (mut computed, registered) = match driven {
+ Ok(driven) => driven,
+ Err(outcome) => return outcome,
+ };
+ let custom_properties = registered.unwrap_or(custom_properties);
+ if let Some(reads) = subject.container_reads.into_inner() {
+ self.container_reads.get_or_insert_default().add_reads(reads);
+ }
+ computed.reads.reads_attributes = Self::note_substitution_reads(&mut computed, &self.cascade.custom_winners);
+ let value_of = |property| computed.groups.value(property);
+ let counter_style_environment_identity = state.values_counter_style_environment_identity(
+ super::super::computed::ComputedStyleTarget::new(node, kind),
+ |property| {
+ computed
+ .value_facts
+ .value_read_in_place(property)
+ .unwrap_or_else(|| value_of(property))
+ },
+ );
+ let table_flags = self.shared_table_flags(computed.flags);
+ let record = std::sync::Arc::new(Record {
+ payloads: Self::interned_rare(
+ &mut self.rare_facts,
+ RareStyleFacts::of_computation(
+ super::records::InheritableCustomProperties::Held,
+ counter_style_environment_identity,
+ table_flags,
+ computed.value_facts,
+ computed.custom_property_reads,
+ computed.reads,
+ self.cascade.animation_name_scope,
+ ),
+ computed.groups.adopt_sharing(&[
+ context
+ .records
+ .get_shared(inherited.parent)
+ .map(|parent| &parent.payloads),
+ Some(&context.initial.payloads),
+ self.last_record.as_ref().map(|record| &record.payloads),
+ ]),
+ &self.cascade.custom_winners,
+ )
+ .with_custom_properties(custom_properties.as_ref()),
+ header: super::records::RecordHeader::new(computed.facts),
+ });
+ if context.uses_caches
+ && !computed.element_dependent
+ && computed.reads.parent_reset_groups == 0
+ && sampled_custom_properties.is_none()
+ {
+ if self.pseudo_elements.len() == 1024 {
+ self.pseudo_elements.clear();
+ }
+ self.pseudo_elements.insert(key, record.clone());
+ }
+ PseudoElementOutcome::Computed {
+ record,
+ element_dependent: computed.element_dependent,
+ }
+ }
+
+ /// Decide the container conditions of the rules `node` matched for the element itself, or
+ /// for its pseudo-elements once the element holds its record, which their conditions ask
+ /// about first. The matches whose conditions hold are `applied`, and what the conditions read
+ /// of the containers is kept in `container_reads`.
+ fn apply_container_gates(&mut self, context: &PassContext<'_>, node: StyleNodeID, pseudo_elements: bool) {
+ let index = context.index;
+ if !index.has_gates() {
+ return;
+ }
+ if !pseudo_elements {
+ self.gated = self
+ .matches
+ .iter()
+ .any(|matched| index.gate_of_entry(matched.entry).is_some());
+ if !self.gated {
+ return;
+ }
+ self.applied.clear();
+ self.applied.extend_from_slice(&self.matches);
+ } else if !self.gated {
+ return;
+ }
+ // A rule's entries for one target are adjacent, and decide alike.
+ let mut last: Option<(ContainerGateID, bool)> = None;
+ let reads = &mut self.container_reads;
+ self.applied.retain(|matched| {
+ let Some(gate) = index.gate_of_entry(matched.entry) else {
+ return true;
+ };
+ let is_pseudo_element = matched.pseudo_kind != u8::MAX;
+ if is_pseudo_element != pseudo_elements {
+ return true;
+ }
+ match last {
+ Some((last_gate, holds)) if last_gate == gate => holds,
+ _ => {
+ let verdict = gate_verdict(context, gate, node, is_pseudo_element);
+ let holds = verdict.matches;
+ reads.get_or_insert_default().add_reads(verdict);
+ last = Some((gate, holds));
+ holds
+ }
+ }
+ });
+ }
+
+ /// Have `node`, whose parent hands down other custom properties than it did and nothing else
+ /// it computes from moved, take them without computing again: its own custom properties are
+ /// built anew over them, and it keeps its style otherwise, where it substitutes none that
+ /// moved. Answers whether it did.
+ fn move_custom_properties(&mut self, context: &PassContext<'_>, node: StyleNodeID) -> bool {
+ let state = context.state;
+ let records = context.records;
+ let (Some(parent), Some(old)) = (state.projection.inheritance_parent(node), records.get_shared(node)) else {
+ return false;
+ };
+ let reads = match &old.rare().custom_property_reads {
+ LonghandCustomPropertyReads::None => &[][..],
+ LonghandCustomPropertyReads::Named(names) => &names[..],
+ LonghandCustomPropertyReads::Any => return false,
+ };
+ // What the element's pseudo-elements and animations compute reads the element's custom
+ // properties beyond its own record, as do transitions, which start from the values that
+ // moved. A registered custom property computes against the element's own context.
+ if !records.pseudo_element_records(node).is_empty()
+ || records.composition(node).is_some()
+ || records.sampled_custom_properties(node).is_some()
+ || state.projection.adjustment_facts(node) & bridge::element_adjustment_fact::HAS_ANIMATIONS != 0
+ || !crate::css::style_compute::transition_delay_and_duration_values_are_single_zero(
+ old.longhand(LonghandID::new(
+ crate::css::property_metadata::property_id::TRANSITION_DELAY,
+ )),
+ old.longhand(LonghandID::new(
+ crate::css::property_metadata::property_id::TRANSITION_DURATION,
+ )),
+ )
+ || state
+ .document_style_computation_inputs
+ .custom_property_registry()
+ .has_registrations()
+ {
+ return false;
+ }
+ let Some((handed_down, held)) = records.custom_stores_of(parent) else {
+ return false;
+ };
+ let custom_properties = match &old.custom_declarations() {
+ Some(declarations) => {
+ match state.custom_property_store(
+ handed_down.as_deref(),
+ held.as_deref(),
+ declarations,
+ &mut self.custom_property_stores,
+ &SubstitutionSubject::new(context, node, None),
+ ) {
+ Some(store) => store,
+ None => return false,
+ }
+ }
+ None => handed_down.as_deref().cloned(),
+ };
+ let moved = self
+ .moved_names
+ .between(old.custom_properties(), custom_properties.as_ref());
+ if moved.is_empty() {
+ // The element holds the values it held: the move stops here.
+ return self.keep_moved(records, node, old.clone());
+ }
+ if !super::custom_property_moves::reads_none_moved(
+ reads,
+ &moved,
+ old.custom_properties(),
+ custom_properties.as_ref(),
+ ) {
+ return false;
+ }
+ let inheritable = super::records::InheritableCustomProperties::of(
+ custom_properties.as_ref(),
+ state.inheritable_custom_property_store(custom_properties.as_ref(), handed_down.as_deref()),
+ );
+ let record = std::sync::Arc::new(Record {
+ payloads: old
+ .payloads
+ .clone()
+ .with_rare_facts(
+ old.rare().with_inheritable_custom_properties(inheritable),
+ old.custom_declarations().cloned(),
+ &[],
+ )
+ .with_custom_properties(custom_properties.as_ref()),
+ header: super::records::RecordHeader::new(old.facts()),
+ });
+ self.keep_moved(records, node, record)
+ }
+
+ fn keep_moved(&mut self, records: &Records<'_>, node: StyleNodeID, record: std::sync::Arc<Record>) -> bool {
+ let kept = records.keep_previous_over_moved_custom_properties(node, record);
+ if kept {
+ self.statistics.moved_custom_properties.push(node);
+ }
+ kept
+ }
+
+ fn children_are_styled(context: &PassContext<'_>, node: StyleNodeID) -> bool {
+ // The descendants of an element that is not displayed have no style to compute.
+ !context
+ .records
+ .assigned_record_view(node)
+ .is_none_or(|view| view.longhands().effective_display(None).is_none())
+ }
+
+ /// Compute the style of `node` from its cascade into a record.
+ fn compute(
+ &mut self,
+ context: &PassContext<'_>,
+ node: StyleNodeID,
+ ) -> Result<(std::sync::Arc<Record>, ComputedFacts), Outcome> {
+ let state = context.state;
+ let inheritance_parent = state.projection.inheritance_parent(node);
+ let parent = match inheritance_parent {
+ Some(parent) => match context.records.current_color_of(parent) {
+ Some(color) => Some((parent, color)),
+ None => return Err(Outcome::ComputeDeclined),
+ },
+ None => None,
+ };
+ // The custom properties the parent hands down, and the ones it holds, which an inheriting
+ // lookup reads.
+ let (parent_store, parent_held) = match inheritance_parent {
+ Some(parent) => match context.records.custom_stores_of(parent) {
+ Some(stores) => stores,
+ None => return Err(Outcome::ComputeDeclined),
+ },
+ None => (None, None),
+ };
+ let subject = SubstitutionSubject::new(context, node, None);
+ // A custom property substituting something of the element itself is the element's alone.
+ let custom_properties_read_subject = self
+ .cascade
+ .custom_winners
+ .iter()
+ .any(|(_, value)| value_reads_substitution_subject(value.data()));
+ let Some(custom_properties) = state.custom_property_store(
+ parent_store.as_deref(),
+ parent_held.as_deref(),
+ &self.cascade.custom_winners,
+ &mut self.custom_property_stores,
+ &subject,
+ ) else {
+ return Err(Outcome::ComputeDeclined);
+ };
+
+ // https://drafts.css-houdini.org/css-properties-values-api-1/#animation-behavior-of-custom-properties
+ // The element's other properties substitute the animated values of its custom properties,
+ // which the host sampled over the environment the element holds. Where this pass moves
+ // the element's own custom properties, they lie over what it resolved, and the host
+ // samples its animations over the record the pass installs.
+ let sampled_custom_properties = context.records.sampled_custom_properties(node).flatten();
+
+ // Elements styled by rules alone repeat; one with its own declarations mostly does not.
+ let declares_own = self
+ .cascade
+ .winners
+ .iter()
+ .any(|winner| matches!(winner.source, WinnerSource::Element(_)));
+ let result_context = (context.uses_caches
+ && sampled_custom_properties.is_none()
+ && !custom_properties_read_subject
+ && (!declares_own || self.results.worth_looking()))
+ .then(|| self.result_context(context, node, inheritance_parent, custom_properties.as_ref()))
+ .flatten();
+ if let Some(result_context) = &result_context
+ && let Some(record) = self.results.find(
+ state,
+ node,
+ &self.cascade.winners,
+ self.cascade.animation_name_scope,
+ result_context,
+ )
+ // NB: An element declaring other custom properties than the one whose result it is
+ // may resolve to the same ones, but declares its own, which a move of the custom
+ // properties it inherits builds them anew from.
+ && declares_the_custom_properties_of(&record, &self.cascade.custom_winners)
+ {
+ return Ok((
+ record,
+ ComputedFacts {
+ directly: false,
+ element_dependent: false,
+ reused: true,
+ },
+ ));
+ }
+
+ let group_seeds = context
+ .initial
+ .group_seeds(parent.and_then(|(parent, _)| context.records.get_shared(parent)));
+ let requested = self.requested();
+ // The store the result context names, which the registered values of the element may
+ // compute to another.
+ let result_custom_properties = result_context.as_ref().and_then(|_| custom_properties.clone());
+ let (mut computed, registered) = drive_with_registered_properties(|computed_store| {
+ let mut suspended_font = None;
+ let substituted = computed_store.unwrap_or(&custom_properties);
+ let sampled = sampled_custom_properties
+ .as_ref()
+ .map(|sampled| sampled.animation_overlay_over(substituted.as_ref()));
+ let driven = state.drive_element(
+ context.records,
+ node,
+ parent,
+ context.initial,
+ &self.cascade.winners,
+ &super::cascade::CascadeBelow {
+ cascade: &self.cascade,
+ state,
+ node,
+ },
+ &mut suspended_font,
+ &mut self.statistics.random_requests,
+ super::custom_properties::CustomPropertyStores {
+ own: sampled.as_ref().or(substituted.as_ref()),
+ inherited: parent_held.as_deref(),
+ substitutions: &self.substitutions,
+ subject: &subject,
+ },
+ &mut self.groups,
+ &mut self.absolutized,
+ u8::MAX,
+ context.root_font(),
+ group_seeds,
+ );
+ if let Some(request) = suspended_font {
+ self.statistics.font_requests.push(request);
+ }
+ self.waits(node, requested);
+ let Ok(mut computed) = driven else {
+ return Err(Outcome::ComputeDeclined);
+ };
+ computed.element_dependent |= custom_properties_read_subject;
+ let registered = state.registered_custom_property_store(
+ node,
+ parent_store.as_deref(),
+ parent_held.as_deref(),
+ &self.cascade.custom_winners,
+ &mut computed,
+ &subject,
+ &mut self.statistics.random_requests,
+ );
+ if self.waits(node, requested) {
+ return Err(Outcome::ComputeDeclined);
+ }
+ Ok(DrivenWithRegisteredProperties {
+ computed,
+ registered,
+ computes_again: false,
+ })
+ })?;
+ let custom_properties = registered.unwrap_or(custom_properties);
+ if let Some(reads) = subject.container_reads.into_inner() {
+ self.container_reads.get_or_insert_default().add_reads(reads);
+ }
+ computed.reads.reads_attributes = Self::note_substitution_reads(&mut computed, &self.cascade.custom_winners);
+ let value_of = |property| computed.groups.value(property);
+ let counter_style_environment_identity = state.values_counter_style_environment_identity(
+ super::super::computed::ComputedStyleTarget::new(node, u8::MAX),
+ |property| {
+ computed
+ .value_facts
+ .value_read_in_place(property)
+ .unwrap_or_else(|| value_of(property))
+ },
+ );
+ let table_flags = self.shared_table_flags(computed.flags);
+ let record = std::sync::Arc::new(Record {
+ header: super::records::RecordHeader::new(computed.facts),
+ payloads: Self::interned_rare(
+ &mut self.rare_facts,
+ RareStyleFacts::of_computation(
+ super::records::InheritableCustomProperties::of(
+ custom_properties.as_ref(),
+ state.inheritable_custom_property_store(custom_properties.as_ref(), parent_store.as_deref()),
+ ),
+ counter_style_environment_identity,
+ table_flags,
+ computed.value_facts,
+ computed.custom_property_reads,
+ computed.reads,
+ self.cascade.animation_name_scope,
+ ),
+ computed.groups.adopt_sharing(&[
+ parent
+ .and_then(|(parent, _)| context.records.get_shared(parent))
+ .map(|parent| &parent.payloads),
+ Some(&context.initial.payloads),
+ self.last_record.as_ref().map(|record| &record.payloads),
+ ]),
+ &self.cascade.custom_winners,
+ )
+ .with_custom_properties(custom_properties.as_ref()),
+ });
+ // NB: An element computing what an installed record holds, as the clone of an element does,
+ // holds that record: installing it takes the slot the record names, and the children of
+ // the element are computed from the record the children of the original were.
+ self.last_record = Some(record.clone());
+ let record = state
+ .computed_group_sets
+ .installed_record_holding_the_same_style_as(&record)
+ .cloned()
+ .unwrap_or(record);
+ // A result reading the parent's values of properties that are not inherited depends on
+ // more of the parent than the key holds.
+ if let Some(result_context) = result_context
+ && !computed.element_dependent
+ && computed.reads.parent_reset_groups == 0
+ {
+ self.results.insert(
+ node,
+ &self.cascade.winners,
+ result_context,
+ result_custom_properties,
+ record.clone(),
+ );
+ }
+ Ok((
+ record,
+ ComputedFacts {
+ directly: computed.directly,
+ element_dependent: computed.element_dependent,
+ reused: false,
+ },
+ ))
+ }
+
+ /// How many fonts and random base values the elements styled so far waited on.
+ fn requested(&self) -> (usize, usize) {
+ (
+ self.statistics.font_requests.len(),
+ self.statistics.random_requests.len(),
+ )
+ }
+
+ /// Whether the style of `node` waits on a font or a random base value requested since
+ /// `requested`, noting that it does.
+ fn waits(&mut self, node: StyleNodeID, requested: (usize, usize)) -> bool {
+ let waits = self.requested() != requested;
+ if waits && self.statistics.waiting.last() != Some(&node) {
+ self.statistics.waiting.push(node);
+ }
+ waits
+ }
+
+ /// Whether the style of a pseudo-element of `node` waits on a font or a random base value
+ /// requested since `requested`, noting that it does.
+ fn pseudo_element_waits(&mut self, node: StyleNodeID, requested: (usize, usize)) -> bool {
+ let waits = self.requested() != requested;
+ if waits && self.statistics.waiting_pseudo_elements.last() != Some(&node) {
+ self.statistics.waiting_pseudo_elements.push(node);
+ }
+ waits
+ }
+
+ /// Note in `computed` what the substitutions of its winners and of the custom properties
+ /// `custom_winners` it declares read beyond its custom properties, and answer whether they
+ /// read its attributes.
+ fn note_substitution_reads(
+ computed: &mut super::compute::ComputedElement,
+ custom_winners: &[(CustomDeclaration, RetainedStyleValueData)],
+ ) -> bool {
+ use super::super::bridge::FfiNodeRecordReads;
+ let reads = custom_winners
+ .iter()
+ .fold(computed.substitution_reads, |reads, (_, value)| {
+ reads | super::super::custom_property_cascade::substitution_reads(value.data())
+ });
+ // https://drafts.csswg.org/css-values-5/#if-notation
+ // The media features an `if()` or a custom function reads move with the viewport, which
+ // restyles the element, and the lengths its style queries compare may count the element's
+ // siblings.
+ if reads & (FfiNodeRecordReads::IfFunction as u8 | FfiNodeRecordReads::CustomFunction as u8) != 0 {
+ computed
+ .facts
+ .add_dependency_flags(crate::css::computed_longhand_table::DEPENDS_ON_VIEWPORT_METRICS);
+ computed.reads.reads_sibling_position = true;
+ computed.reads.environment_reads |= crate::css::style::input_types::StyleEnvironment::MEDIA_FEATURES
+ | crate::css::style::input_types::StyleEnvironment::VIEWPORT;
+ }
+ reads & FfiNodeRecordReads::Attributes as u8 != 0
+ }
+
+ /// What the computation of `node` reads besides its winners, where its result may be reused:
+ /// it has a parent this pass styled, and no winner computes in the font phases, which can read
+ /// the cascaded font sizes of ancestors beyond the parent.
+ fn result_context(
+ &self,
+ context: &PassContext<'_>,
+ node: StyleNodeID,
+ inheritance_parent: Option<StyleNodeID>,
+ custom_properties: Option<&std::sync::Arc<crate::css::custom_properties::CustomPropertyStore>>,
+ ) -> Option<ResultContext> {
+ let state = context.state;
+ if self
+ .cascade
+ .winners
+ .iter()
+ .any(|winner| crate::css::style_compute::computes_in_font_phases(winner.property))
+ {
+ return None;
+ }
+ let parent = inheritance_parent?;
+ let parent_record = context.records.get(parent)?;
+ // What a child computes under the composition of its parent's animations is not the
+ // parent's record's alone.
+ if context.records.composition(parent).is_some() {
+ return None;
+ }
+ let facts = state.projection.facts(node)?;
+ // A parent that generates no box makes the box its child would be in an ancestor's.
+ let parent_display = parent_record.facts().display();
+ if parent_display.is_contents() {
+ return None;
+ }
+ let result_context = ResultContext {
+ parent_inherited_groups: std::array::from_fn(|group| parent_record.payloads[group].as_ptr() as usize),
+ parent_color: parent_record.payloads.current_color(),
+ parent_inherited_values: parent_record.payloads.inherited_values(),
+ parent_dependency_flags: parent_record.facts().publication_dependency_flags(),
+ parent_display,
+ custom_properties: custom_properties.map_or(0, |store| std::sync::Arc::as_ptr(store) as usize),
+ adjustment_facts: state.projection.adjustment_facts(node),
+ language: facts.language(),
+ directionality: facts.directionality(),
+ counter_style_environment: state.counter_style_environment_identity_of(node),
+ hash: 0,
+ };
+ Some(result_context.hashed(state, node, &self.cascade.winners))
+ }
+}
+
+/// What the container conditions of `gate` say for `subject`, or for its pseudo-elements, over the
+/// records of the pass, which hold the containers above the subject.
+///
+/// NB: Conditions the records cannot decide, as about a container whose record holds no font to
+/// resolve a length against, do not hold, and read nothing the host restyles the subject for.
+/// The query containers of the elements a pass computes, as its records have them, with the font
+/// of the document element as the pass computed it, which a `rem` in a query resolves against.
+struct PassContainerRecords<'c, 'p>(&'c PassContext<'p>);
+
+impl ContainerRecords for PassContainerRecords<'_, '_> {
+ fn query_row(&self, node: StyleNodeID) -> Option<super::super::tree::ContainerQueryInputs<'_>> {
+ self.0.records.query_row(node)
+ }
+
+ fn any_element_row(&self, node: StyleNodeID) -> Option<super::super::tree::ContainerQueryInputs<'_>> {
+ self.0.records.any_element_row(node)
+ }
+
+ fn record_view(
+ &self,
+ node: StyleNodeID,
+ row: super::super::tree::ContainerQueryInputs<'_>,
+ ) -> Option<super::super::computed::StyleRecordView<'_>> {
+ self.0.records.record_view(node, row)
+ }
+
+ fn custom_store(
+ &self,
+ node: StyleNodeID,
+ row: super::super::tree::ContainerQueryInputs<'_>,
+ ) -> Option<Option<&crate::css::custom_properties::CustomPropertyStore>> {
+ self.0.records.custom_store(node, row)
+ }
+
+ fn root_font(&self) -> Option<RootFontInputs> {
+ self.0.root_font()
+ }
+}
+
+/// What a substitution for an element, or one of its pseudo-elements, reads of it in a pass.
+struct SubstitutionSubject<'c, 'p> {
+ context: &'c PassContext<'p>,
+ node: StyleNodeID,
+ pseudo_kind: Option<u8>,
+ /// What the container conditions of the custom functions the element calls read of its
+ /// containers.
+ container_reads: std::cell::RefCell<Option<ContainerVerdict>>,
+ /// The groups and dependency flags a pseudo-element computed, which its style queries resolve
+ /// against once it computed them, and whether a style query asked for them before.
+ pseudo_element_style: std::cell::OnceCell<(crate::css::computed_values::StyleGroups, u8)>,
+ asked_pseudo_element_style: std::cell::Cell<bool>,
+}
+
+impl<'c, 'p> SubstitutionSubject<'c, 'p> {
+ fn new(context: &'c PassContext<'p>, node: StyleNodeID, pseudo_kind: Option<u8>) -> Self {
+ Self {
+ context,
+ node,
+ pseudo_kind,
+ container_reads: std::cell::RefCell::new(None),
+ pseudo_element_style: std::cell::OnceCell::new(),
+ asked_pseudo_element_style: std::cell::Cell::new(false),
+ }
+ }
+
+ /// Whether a style query of the pseudo-element asked for the style it computes before it
+ /// computed it, and so resolved against its element's: answering it with the style it computed
+ /// now, `groups` with `dependency_flags`, it computes again.
+ fn computes_again_against_own_style(
+ &self,
+ groups: &crate::css::computed_values::ComputedGroups,
+ dependency_flags: u8,
+ ) -> bool {
+ if !self.asked_pseudo_element_style.take() || self.pseudo_element_style.get().is_some() {
+ return false;
+ }
+ // SAFETY: The pseudo-element's groups are live payloads of each group.
+ let groups =
+ unsafe { crate::css::computed_values::StyleGroups::retained(groups.pointers(), groups.style_bits()) };
+ let _ = self.pseudo_element_style.set((groups, dependency_flags));
+ true
+ }
+}
+
+impl SubstitutingSubject for SubstitutionSubject<'_, '_> {
+ fn target(&self) -> (StyleNodeID, Option<u8>) {
+ (self.node, self.pseudo_kind)
+ }
+
+ /// The conditions compute against the style the element inherits: its parent's record. A
+ /// pseudo-element's compute against the style it computes itself, its own font for its
+ /// lengths: until it computed that, against its element's record, which this pass computed
+ /// before it.
+ fn style_query_inputs(&self) -> Option<crate::css::cascaded_properties::StyleQueryInputs> {
+ let state = self.context.state;
+ let records = self.context.records;
+ let pseudo_element_style = self.pseudo_element_style.get();
+ let view = match self.pseudo_kind {
+ Some(_) => match pseudo_element_style {
+ Some((payloads, dependency_flags)) => Some((payloads, *dependency_flags)),
+ None => {
+ self.asked_pseudo_element_style.set(true);
+ records
+ .assigned_record_view(self.node)
+ .map(|view| (view.payloads, view.dependency_flags))
+ }
+ },
+ None => state
+ .projection
+ .inheritance_parent(self.node)
+ .and_then(|parent| records.assigned_record_view(parent))
+ .map(|view| (view.payloads, view.dependency_flags)),
+ };
+ let mut inputs = state.style_query_inputs_of(view, self.node)?;
+ // A `rem` resolves against the document element's font as the pass computed it.
+ if let Some(root_font) = self.context.root_font() {
+ (
+ inputs.length.root_font_metrics,
+ inputs.length.root_font_metrics_depend_on_viewport_metrics,
+ ) = root_font.font_metrics();
+ }
+ Some(inputs)
+ }
+
+ /// A pseudo-element's container-relative lengths resolve against its element's query
+ /// containers, the element itself included.
+ fn apply_container_unit_bases(&self, length: &mut crate::css::style_compute::FfiLengthResolutionContext) {
+ self.context
+ .state
+ .container_unit_bases_with(
+ &PassContainerRecords(self.context),
+ self.node,
+ self.pseudo_kind.is_some(),
+ )
+ .apply_to(length);
+ }
+
+ fn custom_functions(&self) -> Option<PreparedCustomFunctions<'_>> {
+ let state = self.context.state;
+ let mut functions =
+ state.prepare_custom_functions_with(&state.document_functions, self.node, |containers| {
+ Some(
+ state
+ .container_conditions_verdict_with(
+ &PassContainerRecords(self.context),
+ containers,
+ self.node,
+ self.pseudo_kind.is_some(),
+ )
+ .unwrap_or_else(|| undecided_verdict(containers)),
+ )
+ })?;
+ if let Some(effects) = functions.container_effects.take() {
+ self.container_reads
+ .borrow_mut()
+ .get_or_insert_default()
+ .add_reads(effects);
+ }
+ Some(functions)
+ }
+}
+
+/// What container conditions the engine cannot decide for their subject read: they do not hold.
+fn undecided_verdict(
+ conditions: &[std::sync::Arc<crate::css::container_conditions::ContainerConditionsData>],
+) -> ContainerVerdict {
+ ContainerVerdict {
+ matches: false,
+ depends_on_size: conditions.iter().any(|conditions| conditions.contains_size_feature()),
+ depends_on_style: super::super::container_queries::conditions_ask_container_style(conditions),
+ ..Default::default()
+ }
+}
+
+fn gate_verdict(
+ context: &PassContext<'_>,
+ gate: ContainerGateID,
+ subject: StyleNodeID,
+ subject_is_pseudo_element: bool,
+) -> ContainerVerdict {
+ let conditions = context.index.gate(gate);
+ context
+ .state
+ .container_conditions_verdict_with(
+ &PassContainerRecords(context),
+ conditions,
+ subject,
+ subject_is_pseudo_element,
+ )
+ .unwrap_or_else(|| undecided_verdict(conditions))
+}
+
+/// Whether `record` holds `custom_winners` as the custom declarations it was computed from.
+fn declares_the_custom_properties_of(
+ record: &Record,
+ custom_winners: &[(CustomDeclaration, crate::css::style_value::RetainedStyleValueData)],
+) -> bool {
+ let declarations = record
+ .custom_declarations()
+ .map_or(&[][..], |declarations| &declarations[..]);
+ declarations.len() == custom_winners.len()
+ && declarations.iter().zip(custom_winners).all(|(declared, winner)| {
+ declared.0 == winner.0 && (declared.1.pointer() == winner.1.pointer() || declared.1 == winner.1)
+ })
+}
+
+/// What a pseudo-element's style is computed from, besides the facts its element's style already
+/// holds.
+#[derive(PartialEq, Eq, Hash)]
+struct PseudoElementKey {
+ kind: u8,
+ inherited_groups: [usize; super::super::computed::ENGINE_INHERITED_GROUP_COUNT],
+ color: u32,
+ inherited_values: crate::css::computed_value_types::InheritedSetValues,
+ /// What the element's style depends on, part of which its pseudo-elements take on, as being in a
+ /// `display: none` subtree.
+ element_dependency_flags: u8,
+ display: [u8; 6],
+ custom_properties: usize,
+ winners: Vec<super::cascade::Winner>,
+ /// The pseudo-element's own custom declarations, by declaration and value address, which its
+ /// winners do not hold: a `::first-letter` whose longhands all lose still differs by these.
+ custom_winners: Vec<(CustomDeclaration, usize)>,
+ /// Where the winning `animation-name` was declared, which the winners do not tell apart for a
+ /// sheet several shadow roots adopt.
+ animation_name_scope: super::super::animations::DeclarationScope,
+ /// The record a highlight pseudo-element inherits from, or zero.
+ highlight_parent: usize,
+ /// The identity of the counter-style registry of the element's style scope, which a `::marker`
+ /// or generated content may resolve its counter styles against.
+ counter_style_environment: u64,
+}
+
+/// What a pseudo-element inherits from its originating element.
+struct PseudoElementInheritance {
+ /// The element inherited from: the originating element, or for a `::first-letter` the element
+ /// containing the letter.
+ parent: StyleNodeID,
+ /// The inherited longhands that element holds as bits, and its effective zoom.
+ inherited_values: crate::css::computed_value_types::InheritedSetValues,
+ /// What a view of that element says its style depends on.
+ dependency_flags: u8,
+ groups: [usize; super::super::computed::ENGINE_INHERITED_GROUP_COUNT],
+ color: u32,
+ /// The custom properties the element hands down, and the ones it holds.
+ handed_down: super::records::HeldCustomProperties,
+ held: super::records::HeldCustomProperties,
+}
+
+impl PseudoElementInheritance {
+ // https://drafts.csswg.org/css-pseudo-4/#treelike
+ // A pseudo-element inherits from its originating element, the animated values of the
+ // composition the host lays over the element's record included, as a child does.
+ fn of(context: &PassContext<'_>, node: StyleNodeID, element: &Record) -> Self {
+ let composition = context.records.composition(node);
+ let inherited_payloads: &crate::css::computed_values::StyleGroups = match &composition {
+ Some(view) => view.payloads,
+ None => &element.payloads,
+ };
+ let (handed_down, held) = match context.records.custom_stores_of(node) {
+ Some((handed_down, held)) => (handed_down.map(Cow::into_owned), held.map(Cow::into_owned)),
+ None => (
+ element.inheritable_custom_properties().cloned(),
+ element.custom_properties().cloned(),
+ ),
+ };
+ Self {
+ parent: node,
+ inherited_values: inherited_payloads.inherited_values(),
+ dependency_flags: composition.as_ref().map_or_else(
+ || element.facts().publication_dependency_flags(),
+ |view| view.dependency_flags,
+ ),
+ groups: std::array::from_fn(|group| inherited_payloads[group].as_ptr() as usize),
+ color: context
+ .records
+ .current_color_of(node)
+ .unwrap_or(element.payloads.current_color()),
+ handed_down,
+ held,
+ }
+ }
+}
+
+/// Which pseudo-elements a computation styles.
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(super) enum PseudoElementRead {
+ /// Those that generate a box: a `::marker` of a list item, and a `::before` or `::after` a rule
+ /// styles whose content generates something.
+ Generating,
+ /// Those a rule styles, and the `::marker` of a list item, whether or not they generate a box.
+ Styled,
+ /// Any, as a read of what a pseudo-element computes to does whether or not a rule styles it.
+ Any,
+}
+
+impl PseudoElementRead {
+ /// Whether the read styles the pseudo-element of `kind` of an element whose record is
+ /// `element`, where `has_rules` says whether a rule matched for it, or, for a highlight
+ /// pseudo-element, whether it inherits one of an ancestor.
+ fn styles(self, kind: u8, has_rules: bool, element: &Record) -> bool {
+ use super::super::publication::pseudo_kind::MARKER;
+ // A list item generates a marker whatever rules match for it, and no other element does.
+ let list_item_marker = kind == MARKER && element.facts().display().is_list_item();
+ match self {
+ Self::Generating => match kind {
+ MARKER => list_item_marker,
+ _ => has_rules,
+ },
+ Self::Styled => has_rules || list_item_marker,
+ Self::Any => true,
+ }
+ }
+}
+
+/// What came of computing the style of a pseudo-element.
+enum PseudoElementOutcome {
+ Computed {
+ record: std::sync::Arc<Record>,
+ /// Whether the record computes against the element itself, such as its place among its
+ /// siblings.
+ element_dependent: bool,
+ },
+ /// No rule styles it.
+ Unstyled,
+ /// A `::before` or `::after` whose content generates nothing.
+ GeneratesNoBox,
+ /// The style waits on fonts or random base values the pass requested.
+ Waiting,
+ /// The style needed what the pass does not do.
+ Declined,
+}
+
+/// What came of computing an element besides its record.
+struct ComputedFacts {
+ directly: bool,
+ element_dependent: bool,
+ /// Whether the record is one computed for an element before, reused.
+ reused: bool,
+}
+
+// SAFETY: A thread's scratch moves to the thread that styles with it and stays there; its payload
+// buffer holds no reference between elements.
+unsafe impl Send for Scratch<'_> {}
+
+/// The scratch of every thread of the pool, plus one for a traversal on the calling thread.
+struct Scratches<'a> {
+ pool: Option<&'a rayon::ThreadPool>,
+ slots: Vec<Mutex<Option<Scratch<'a>>>>,
+}
+
+impl<'a> Scratches<'a> {
+ fn with<R>(&self, context: &PassContext<'a>, run: impl FnOnce(&mut Scratch<'a>) -> R) -> R {
+ let index = self
+ .pool
+ .and_then(rayon::ThreadPool::current_thread_index)
+ .unwrap_or(self.slots.len() - 1);
+ let mut slot = self.slots[index]
+ .lock()
+ .expect("a thread's scratch is only ever held by that thread");
+ run(slot.get_or_insert_with(|| {
+ let mut scratch = Scratch::new(context);
+ if context.uses_caches
+ && let Some(cache) = context.group_caches.and_then(|caches| caches.get(index))
+ {
+ scratch.groups = std::mem::take(&mut *cache.lock().expect("no thread panicked while styling"));
+ }
+ scratch
+ }))
+ }
+}
+
+/// `hint`, rematching what it restyles against the whole rule index.
+pub(super) fn rematched_in_full(hint: HintBits) -> HintBits {
+ let mut hint = hint;
+ if hint & RESTYLE_SELF != 0 {
+ hint |= MATCH_SELF;
+ }
+ if hint & RESTYLE_DESCENDANTS != 0 {
+ hint |= MATCH_DESCENDANTS;
+ }
+ hint
+}
+
+/// An element to style, with the hint its ancestors pass it and the entries they restyle it for.
+#[derive(Clone)]
+pub(super) struct Queued {
+ node: StyleNodeID,
+ hint: HintBits,
+ reasons: Option<super::records::MatchList>,
+}
+
+/// Hands the elements of `given` and their descendants to other tasks, a work unit each.
+fn hand_off<'scope, 'a: 'scope>(
+ scope: &rayon::ScopeFifo<'scope>,
+ context: &'scope PassContext<'a>,
+ scratches: &'scope Scratches<'a>,
+ mut given: VecDeque<Queued>,
+) {
+ while !given.is_empty() {
+ let unit: VecDeque<Queued> = given.drain(..WORK_UNIT.min(given.len())).collect();
+ scope.spawn_fifo(move |scope| {
+ style_trees(Some(scope), context, scratches, unit, 0, usize::MAX);
+ });
+ }
+}
+
+/// Style the elements of `discovered` and their descendants breadth-first, handing the children
+/// discovered at each level beyond `local_queue_size` elements to other tasks once they make up at
+/// least a work unit. Without a scope to hand them to, stops once `hand_off_size` elements are
+/// queued, and answers those.
+fn style_trees<'scope, 'a: 'scope>(
+ scope: Option<&rayon::ScopeFifo<'scope>>,
+ context: &'scope PassContext<'a>,
+ scratches: &'scope Scratches<'a>,
+ mut discovered: VecDeque<Queued>,
+ local_queue_size: usize,
+ hand_off_size: usize,
+) -> VecDeque<Queued> {
+ scratches.with(context, |scratch| {
+ let mut remaining_at_current_depth = discovered.len();
+ while let Some(Queued {
+ node,
+ hint: inherited,
+ reasons: inherited_reasons,
+ }) = discovered.pop_front()
+ {
+ context.state.element_declarations.prefetch([
+ discovered.front().map(|queued| queued.node),
+ discovered.get(1).map(|queued| queued.node),
+ discovered.get(2).map(|queued| queued.node),
+ ]);
+ // What the element's ancestors ask of it, and what it asks of its descendants.
+ let mut hint = context.hint(node) | inherited;
+ // An element reading the containers above it reads them anew where one moved.
+ if hint & (CONTAINERS_MOVED | RESTYLE_SELF) == CONTAINERS_MOVED && context.records.reads_containers(node) {
+ hint |= RESTYLE_SELF;
+ }
+ // An element reading the root element's font reads it anew where it moved.
+ if hint & (ROOT_FONT_MOVED | RESTYLE_SELF) == ROOT_FONT_MOVED && context.reads_root_font_move(node) {
+ hint |= RESTYLE_SELF;
+ }
+ // An element that takes the custom properties its parent hands down now without
+ // computing again hands its own down in turn.
+ let moved_custom_properties = hint & (PARENT_CUSTOM_PROPERTIES_MOVED | RESTYLES_SELF)
+ == PARENT_CUSTOM_PROPERTIES_MOVED
+ && scratch.move_custom_properties(context, node);
+ if moved_custom_properties {
+ scratch.audit_caches(context, node, cache_audit::Reuse::MovedCustomProperties);
+ }
+ if hint & PARENT_CUSTOM_PROPERTIES_MOVED != 0 && !moved_custom_properties {
+ hint |= RESTYLE_SELF | PARENT_CHANGED;
+ }
+ if hint & RESTYLE_PSEUDO_ELEMENTS != 0 {
+ if hint & RESTYLE_SELF == 0 {
+ scratch.statistics.restyled_for_pseudo_elements.push(node);
+ }
+ hint |= RESTYLE_SELF | PARENT_CHANGED;
+ }
+ let restyled = hint & RESTYLE_SELF != 0;
+ let styles_children = match restyled {
+ true => {
+ let own = context.reasons.and_then(|reasons| Reasons::of(reasons.own, node));
+ let rematch = union(inherited_reasons.clone(), own.as_ref());
+ let reasons = match hint & MATCH_SELF {
+ 0 => Some(rematch.as_ref().map_or(&[][..], |rematch| &rematch[..])),
+ _ => None,
+ };
+ scratch.style_element(
+ context,
+ node,
+ reasons,
+ hint & (PARENT_CHANGED | PARENT_RESTYLED | CONTAINERS_MOVED | RECOMPUTE_SELF),
+ )
+ }
+ false => Scratch::children_are_styled(context, node),
+ };
+ // An element waiting on a font or a random base value is styled in the next round of
+ // a pass that suspends, with what its ancestors ask of it.
+ if restyled
+ && context.suspends
+ && !styles_children
+ && scratch.statistics.waiting.last() == Some(&node)
+ && !context.records.computed(node)
+ {
+ scratch.statistics.suspended.push(Suspended::Element(Queued {
+ node,
+ hint: inherited,
+ reasons: inherited_reasons.clone(),
+ }));
+ }
+ let record_moved = restyled || moved_custom_properties;
+ // Every element under a document element whose font moved that resolves root-relative
+ // lengths against what moved resolves them again. What the others inherit moves with
+ // their parents.
+ if restyled && context.root_font_moved() != RootFontReads::None && is_document_element(context.state, node)
+ {
+ hint |= ROOT_FONT_MOVED;
+ }
+ // The elements of a shadow tree standing for its host's pseudo-elements are styled
+ // from the host's matches for them.
+ if restyled && std::mem::take(&mut scratch.backing_elements_moved) {
+ hint |= RESTYLE_DESCENDANTS | MATCH_DESCENDANTS;
+ }
+ // The elements below one displayed again were not styled while it was not, whatever
+ // changed for them meanwhile.
+ if restyled && context.records.revealed(node) {
+ hint |= RESTYLE_DESCENDANTS | MATCH_DESCENDANTS;
+ }
+ if styles_children {
+ // The elements below one that describes another container than it did, or below
+ // such an element, read their containers anew.
+ let containers_moved = match hint & CONTAINERS_MOVED != 0
+ || record_moved
+ && context
+ .records
+ .container_moved(node, context.index.gates_ask_container_style)
+ {
+ true => CONTAINERS_MOVED,
+ false => 0,
+ };
+ let impact = match record_moved && hint & RESTYLE_DESCENDANTS == 0 {
+ true => context.records.child_impact(node),
+ false => ChildImpact::None,
+ };
+ scratch.statistics.changed_elements += u64::from(impact != ChildImpact::None);
+ let children = match hint & RESTYLE_DESCENDANTS != 0 {
+ true => {
+ RESTYLE_SELF
+ | RESTYLE_DESCENDANTS
+ | if record_moved { PARENT_RESTYLED } else { 0 }
+ | match hint & MATCH_DESCENDANTS {
+ 0 => 0,
+ _ => MATCH_SELF | MATCH_DESCENDANTS,
+ }
+ }
+ false if impact == ChildImpact::All => RESTYLE_SELF | PARENT_CHANGED,
+ // A `display: contents` element generates no box, so its children's boxes are
+ // in its parent's, whose display they read (blockification, for one) where
+ // it changed, whether or not this element's own record did.
+ false
+ if restyled
+ && hint & PARENT_CHANGED != 0
+ && context
+ .records
+ .get(node)
+ .is_some_and(|record| record.facts().display().is_contents()) =>
+ {
+ RESTYLE_SELF | PARENT_CHANGED
+ }
+ false
+ if matches!(
+ impact,
+ ChildImpact::CustomProperties | ChildImpact::ResetReadersAndCustomProperties
+ ) =>
+ {
+ PARENT_CUSTOM_PROPERTIES_MOVED
+ }
+ false => 0,
+ } | containers_moved
+ | hint & ROOT_FONT_MOVED;
+ let children_reasons = match hint & RESTYLE_DESCENDANTS != 0 {
+ true => union(
+ inherited_reasons,
+ context
+ .reasons
+ .and_then(|reasons| Reasons::of(reasons.descendants, node))
+ .as_ref(),
+ ),
+ false => None,
+ };
+ // The children of an element whose record moved beneath the composition of its
+ // animations inherit the composition, which the host lays over the new record once
+ // it is installed: they wait for the next pass.
+ let defers_children =
+ restyled && context.hints.is_some() && context.records.moves_beneath_a_composition(node);
+ if children != 0 || impact != ChildImpact::None || hint & DIRTY_DESCENDANTS != 0 {
+ // The traversal walks the flat tree, where an element's children are the
+ // ones that inherit from it.
+ for current in context.state.projection.style_children(node) {
+ let children = match impact {
+ ChildImpact::ResetReaders | ChildImpact::ResetReadersAndCustomProperties
+ if context
+ .records
+ .get(current)
+ .is_none_or(|record| context.state.reads_parent_reset_values(current, record)) =>
+ {
+ RESTYLE_SELF | PARENT_CHANGED | containers_moved | hint & ROOT_FONT_MOVED
+ }
+ _ => children,
+ };
+ if children != 0 || context.hint(current) != 0 {
+ match defers_children {
+ // NB: The next pass rematches the child against the whole index,
+ // as it keeps no reasons.
+ true => scratch.statistics.deferred.push((current, rematched_in_full(children))),
+ false => discovered.push_back(Queued {
+ node: current,
+ hint: children,
+ reasons: children_reasons.clone(),
+ }),
+ }
+ }
+ }
+ }
+ }
+ remaining_at_current_depth -= 1;
+ let discovered_children = discovered.len() - remaining_at_current_depth;
+ if let Some(scope) = scope
+ && discovered_children >= WORK_UNIT
+ && discovered.len() >= local_queue_size + WORK_UNIT
+ {
+ let kept = remaining_at_current_depth.max(local_queue_size);
+ hand_off(scope, context, scratches, discovered.split_off(kept));
+ }
+ if scope.is_none() && discovered.len() >= hand_off_size {
+ break;
+ }
+ if remaining_at_current_depth == 0 {
+ remaining_at_current_depth = discovered.len();
+ }
+ }
+ discovered
+ })
+}
+
+/// Style every element of the document tree under `root`.
+pub(super) fn style_document(
+ context: &PassContext<'_>,
+ pool: Option<&rayon::ThreadPool>,
+ root: StyleNodeID,
+) -> Statistics {
+ style_subtrees(context, pool, &[root])
+}
+
+/// Style the elements under each of `roots`, none of which is under another, as the hints of the
+/// pass ask.
+pub(super) fn style_subtrees(
+ context: &PassContext<'_>,
+ pool: Option<&rayon::ThreadPool>,
+ roots: &[StyleNodeID],
+) -> Statistics {
+ style_queued(
+ context,
+ pool,
+ roots,
+ |&root| Queued {
+ node: root,
+ hint: 0,
+ reasons: None,
+ },
+ Vec::new(),
+ )
+}
+
+/// Style what the round before suspended, now that the fonts and random base values it waited on
+/// resolved: the pseudo-elements of the elements it styled but for those, and the elements, with
+/// the elements under them, as the round before would have.
+pub(super) fn resume(
+ context: &PassContext<'_>,
+ pool: Option<&rayon::ThreadPool>,
+ suspended: Vec<Suspended>,
+) -> Statistics {
+ let mut elements = Vec::new();
+ let mut pseudo_elements = Vec::new();
+ for suspended in suspended {
+ match suspended {
+ Suspended::Element(queued) => elements.push(queued),
+ Suspended::PseudoElements(suspended) => pseudo_elements.push(suspended),
+ }
+ }
+ style_queued(context, pool, &elements, Queued::clone, pseudo_elements)
+}
+
+/// Keep the records of the pseudo-elements `suspended` holds back that did not wait, as no round
+/// resumes them: the next pass styles the others.
+pub(super) fn settle_suspended(context: &PassContext<'_>, suspended: Vec<Suspended>) {
+ for suspended in suspended {
+ if let Suspended::PseudoElements(suspended) = suspended {
+ context
+ .records
+ .insert_pseudo_element_records(suspended.node, suspended.records);
+ }
+ }
+}
+
+/// Style the pseudo-elements of `pseudo_elements`, and the elements `queued` makes of `elements`
+/// with the elements under them.
+fn style_queued<T: Sync>(
+ context: &PassContext<'_>,
+ pool: Option<&rayon::ThreadPool>,
+ elements: &[T],
+ queued: impl Fn(&T) -> Queued + Copy + Send,
+ pseudo_elements: Vec<SuspendedPseudoElements>,
+) -> Statistics {
+ let workers = pool.map_or(0, rayon::ThreadPool::current_num_threads);
+ let scratches = Scratches {
+ pool,
+ slots: (0..=workers).map(|_| Mutex::new(None)).collect(),
+ };
+ if !pseudo_elements.is_empty() {
+ scratches.with(context, |scratch| {
+ for suspended in pseudo_elements {
+ scratch.resume_pseudo_elements(context, suspended);
+ }
+ });
+ }
+ // The calling thread styles the first elements, and the pool joins in for the others, or once
+ // a level of the tree is wide enough to spare work for it.
+ let mut units = elements.chunks(WORK_UNIT);
+ let first: VecDeque<Queued> = units.next().unwrap_or_default().iter().map(queued).collect();
+ match pool {
+ // A pass with few roots runs on the calling thread until it finds enough to style for the
+ // pool's threads to join in.
+ Some(pool) if elements.len() < PARALLEL_PASS_SIZE => {
+ let roots = elements.iter().map(queued).collect();
+ let mut left = style_trees(
+ None,
+ context,
+ &scratches,
+ roots,
+ CALLING_THREAD_QUEUE_SIZE,
+ PARALLEL_PASS_SIZE,
+ );
+ if !left.is_empty() {
+ pool.in_place_scope_fifo(|scope| {
+ let scratches = &scratches;
+ hand_off(
+ scope,
+ context,
+ scratches,
+ left.split_off(CALLING_THREAD_QUEUE_SIZE.min(left.len())),
+ );
+ style_trees(
+ Some(scope),
+ context,
+ scratches,
+ left,
+ CALLING_THREAD_QUEUE_SIZE,
+ usize::MAX,
+ );
+ });
+ }
+ }
+ Some(pool) => pool.in_place_scope_fifo(|scope| {
+ let scratches = &scratches;
+ for unit in units {
+ let unit: VecDeque<Queued> = unit.iter().map(queued).collect();
+ scope.spawn_fifo(move |scope| {
+ style_trees(Some(scope), context, scratches, unit, 0, usize::MAX);
+ });
+ }
+ style_trees(
+ Some(scope),
+ context,
+ scratches,
+ first,
+ CALLING_THREAD_QUEUE_SIZE,
+ usize::MAX,
+ );
+ }),
+ None => {
+ for unit in std::iter::once(first).chain(units.map(|unit| unit.iter().map(queued).collect())) {
+ style_trees(None, context, &scratches, unit, CALLING_THREAD_QUEUE_SIZE, usize::MAX);
+ }
+ }
+ }
+ let mut statistics = Statistics::default();
+ for (index, scratch) in scratches.slots.into_iter().enumerate() {
+ let Some(mut scratch) = scratch.into_inner().expect("no thread panicked while styling") else {
+ continue;
+ };
+ if context.uses_caches
+ && let Some(cache) = context.group_caches.and_then(|caches| caches.get(index))
+ {
+ *cache.lock().expect("no thread panicked while styling") = std::mem::take(&mut scratch.groups).kept();
+ }
+ statistics.add(scratch);
+ }
+ statistics.cache_audit.conclude(context.cache_audit);
+ statistics
+}
+
+/// Style each element of `chain` in turn, each the parent the next one inherits from, matching it
+/// against the whole rule index whatever the display of the elements above it, for a read of the
+/// style of the last one. The elements after one left without a record are not styled.
+pub(super) fn style_chain(context: &PassContext<'_>, chain: &[StyleNodeID]) -> Statistics {
+ let mut scratch = Scratch::new(context);
+ for &node in chain {
+ scratch.style_element(context, node, None, PARENT_CHANGED);
+ if !context.records.computed(node) {
+ break;
+ }
+ }
+ let mut statistics = Statistics::default();
+ statistics.add(scratch);
+ statistics.cache_audit.conclude(context.cache_audit);
+ statistics
+}
+
+/// What a read of the style of one pseudo-element finds.
+pub(super) enum DemandedPseudoElement {
+ Styled(std::sync::Arc<Record>),
+ /// No rule styles it.
+ Unstyled,
+ /// Its style waits on the fonts and random base values it asks for.
+ Waiting(Vec<font_resolution::FontRequest>, Vec<RandomBaseRequest>),
+ Declined,
+}
+
+/// Style the pseudo-element of `kind` of `node` for a read of its style, whether or not it
+/// generates a box, from the rules the element matches for it, over the record `context` holds for
+/// `node`, which it inherits from. Which pseudo-elements are styled is what `read` says.
+pub(super) fn style_pseudo_element(
+ context: &PassContext<'_>,
+ node: StyleNodeID,
+ kind: u8,
+ read: PseudoElementRead,
+) -> DemandedPseudoElement {
+ style_pseudo_element_inheriting_from(context, node, kind, read, None)
+}
+
+/// Style the pseudo-element of `kind` of `node` as [`style_pseudo_element`] does, inheriting from
+/// `inheritance_parent` rather than from `node` where it names an element.
+pub(super) fn style_pseudo_element_inheriting_from(
+ context: &PassContext<'_>,
+ node: StyleNodeID,
+ kind: u8,
+ read: PseudoElementRead,
+ inheritance_parent: Option<StyleNodeID>,
+) -> DemandedPseudoElement {
+ let Some(element) = context.records.get_shared(node).cloned() else {
+ return DemandedPseudoElement::Declined;
+ };
+ let state = context.state;
+ let Some(facts) = state.projection.facts(node) else {
+ return DemandedPseudoElement::Unstyled;
+ };
+ let mut scratch = Scratch::new(context);
+ scratch.enter_parent(context, state.projection.parent(node));
+ if scratch
+ .matcher
+ .match_element(node, facts, &scratch.filter, &mut scratch.matches)
+ .is_err()
+ {
+ return DemandedPseudoElement::Declined;
+ }
+ scratch.apply_container_gates(context, node, false);
+ scratch.apply_container_gates(context, node, true);
+ let inherited = match inheritance_parent {
+ Some(parent) => {
+ let Some(parent_record) = context.records.get_shared(parent).cloned() else {
+ return DemandedPseudoElement::Declined;
+ };
+ PseudoElementInheritance::of(context, parent, &parent_record)
+ }
+ None => PseudoElementInheritance::of(context, node, &element),
+ };
+ let outcome = scratch.compute_pseudo_element(context, node, &element, &inherited, kind, read);
+ if !scratch.statistics.font_requests.is_empty() || !scratch.statistics.random_requests.is_empty() {
+ return DemandedPseudoElement::Waiting(
+ std::mem::take(&mut scratch.statistics.font_requests),
+ std::mem::take(&mut scratch.statistics.random_requests),
+ );
+ }
+ match outcome {
+ PseudoElementOutcome::Computed { record, .. } => DemandedPseudoElement::Styled(record),
+ PseudoElementOutcome::Unstyled | PseudoElementOutcome::GeneratesNoBox => DemandedPseudoElement::Unstyled,
+ PseudoElementOutcome::Waiting | PseudoElementOutcome::Declined => DemandedPseudoElement::Declined,
+ }
+}
+
+impl Statistics {
+ /// Take what the pass suspended, for its next round to resume, with the fonts and random base
+ /// values it waits on. The elements it resumes wait no longer, and the round styles them.
+ pub(super) fn take_suspended(
+ &mut self,
+ ) -> (
+ Vec<Suspended>,
+ Vec<font_resolution::FontRequest>,
+ Vec<RandomBaseRequest>,
+ ) {
+ let suspended = std::mem::take(&mut self.suspended);
+ let elements: HashSet<StyleNodeID> = suspended
+ .iter()
+ .filter(|suspended| matches!(suspended, Suspended::Element(_)))
+ .map(Suspended::node)
+ .collect();
+ let pseudo_elements: HashSet<StyleNodeID> = suspended
+ .iter()
+ .filter(|suspended| matches!(suspended, Suspended::PseudoElements(_)))
+ .map(Suspended::node)
+ .collect();
+ self.styled.retain(|node| !elements.contains(node));
+ self.waiting.retain(|node| !elements.contains(node));
+ self.waiting_with_kept_matches.retain(|node| !elements.contains(node));
+ self.waiting_pseudo_elements
+ .retain(|node| !pseudo_elements.contains(node));
+ (
+ suspended,
+ std::mem::take(&mut self.font_requests),
+ std::mem::take(&mut self.random_requests),
+ )
+ }
+
+ /// Add what a round resuming what this one suspended measured and gathered.
+ pub(super) fn add_round(&mut self, round: Statistics) {
+ let statistics = self;
+ statistics.match_counters.add(&round.match_counters);
+ statistics.cascade_counters.add(&round.cascade_counters);
+ statistics.font_requests.extend(round.font_requests);
+ statistics.random_requests.extend(round.random_requests);
+ statistics.waiting.extend(round.waiting);
+ statistics.suspended.extend(round.suspended);
+ statistics
+ .waiting_with_kept_matches
+ .extend(round.waiting_with_kept_matches);
+ statistics.waiting_pseudo_elements.extend(round.waiting_pseudo_elements);
+ statistics.pseudo_elements_declined += round.pseudo_elements_declined;
+ statistics.styled.extend(round.styled);
+ statistics.moved_custom_properties.extend(round.moved_custom_properties);
+ statistics.changed_elements += round.changed_elements;
+ statistics.deferred.extend(round.deferred);
+ statistics
+ .restyled_for_pseudo_elements
+ .extend(round.restyled_for_pseudo_elements);
+ statistics.outcomes.add(&round.outcomes);
+ statistics.cache_audit.add(round.cache_audit);
+ }
+
+ /// Add what a thread's scratch measured and gathered.
+ fn add(&mut self, scratch: Scratch<'_>) {
+ self.match_counters.add(&scratch.matcher.counters());
+ self.cascade_counters.add(&scratch.cascade.statistics);
+ self.add_round(scratch.statistics);
+ if let Some(audit) = scratch.cache_audit {
+ self.cache_audit.add(*audit);
+ }
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/winner_store.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/winner_store.rs
new file mode 100644
index 00000000000..f5509063d31
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/winner_store.rs
@@ -0,0 +1,523 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The winning declarations of one element's drive, with values borrowed from the committed
+//! declaration inputs. Only substituted values need ownership here. A view cannot outlive its
+//! input borrow.
+
+use super::super::*;
+use super::compute::ReadsNoResourceContexts;
+use crate::css::cascaded_properties::{CascadedValues, WinningDeclaration};
+use crate::css::style_compute::{ExternalValueDependencies, RootFontReads};
+use crate::css::style_value::ShorthandPayload;
+use crate::css::style_value::{RetainedStyleValueData, StyleValueData};
+use std::cell::Cell;
+
+pub(in crate::css::style) enum WinnerValue {
+ Written {
+ node: StyleNodeID,
+ source: WinnerSource,
+ index: usize,
+ },
+ /// A value substituted from what `source` declared, which keeps the sheet a `url()` in it
+ /// resolves against.
+ Substituted {
+ value: RetainedStyleValueData,
+ source: WinnerSource,
+ },
+}
+
+pub(in crate::css::style) struct WinnerDeclaration {
+ pub(in crate::css::style) property: u16,
+ pub(in crate::css::style) important: bool,
+ pub(in crate::css::style) value: WinnerValue,
+ /// The origin of the winning declaration.
+ pub(in crate::css::style) origin: CascadeOrigin,
+ /// `external_value_dependencies(value)`, memoized, packed into one word with a bit saying
+ /// it has been computed.
+ dependencies: Cell<u32>,
+}
+
+/// Set on a packed `ExternalValueDependencies` word that has been computed.
+pub(in crate::css::style) const DEPENDENCIES_COMPUTED: u32 = 1 << 31;
+
+/// The bits a packed `ExternalValueDependencies` word may set: those `pack_dependencies` sets.
+pub(in crate::css::style) const DEPENDENCY_BITS: u32 = DEPENDENCIES_COMPUTED | ((1 << 21) - 1);
+
+pub(in crate::css::style) fn pack_dependencies(dependencies: ExternalValueDependencies) -> u32 {
+ let ExternalValueDependencies {
+ uses_tree_counting_function,
+ container_relative_length_unit_mask,
+ has_unfixed_random_sharing,
+ uses_random_function,
+ needs_document_base_url,
+ may_need_style_sheet_resource_context,
+ inheritance_dependent,
+ root_font_reads,
+ font_metric_relative_length,
+ color_scheme_dependent,
+ device_pixel_ratio_dependent,
+ viewport_axes,
+ } = dependencies;
+ DEPENDENCIES_COMPUTED
+ | u32::from(container_relative_length_unit_mask)
+ | (u32::from(uses_tree_counting_function) << 8)
+ | (u32::from(has_unfixed_random_sharing) << 9)
+ | (u32::from(uses_random_function) << 10)
+ | (u32::from(needs_document_base_url) << 11)
+ | (u32::from(may_need_style_sheet_resource_context) << 12)
+ | (u32::from(inheritance_dependent) << 13)
+ | (u32::from(root_font_reads as u8) << 14)
+ | (u32::from(color_scheme_dependent) << 17)
+ | (u32::from(device_pixel_ratio_dependent) << 18)
+ | (u32::from(viewport_axes) << 19)
+ | (u32::from(font_metric_relative_length) << 16)
+}
+
+pub(in crate::css::style) fn unpack_dependencies(bits: u32) -> ExternalValueDependencies {
+ ExternalValueDependencies {
+ uses_tree_counting_function: bits & (1 << 8) != 0,
+ container_relative_length_unit_mask: (bits & 0xff) as u8,
+ has_unfixed_random_sharing: bits & (1 << 9) != 0,
+ uses_random_function: bits & (1 << 10) != 0,
+ needs_document_base_url: bits & (1 << 11) != 0,
+ may_need_style_sheet_resource_context: bits & (1 << 12) != 0,
+ inheritance_dependent: bits & (1 << 13) != 0,
+ root_font_reads: match (bits >> 14) & 0b11 {
+ 0 => RootFontReads::None,
+ 1 => RootFontReads::FontSize,
+ _ => RootFontReads::Metrics,
+ },
+ font_metric_relative_length: bits & (1 << 16) != 0,
+ color_scheme_dependent: bits & (1 << 17) != 0,
+ device_pixel_ratio_dependent: bits & (1 << 18) != 0,
+ viewport_axes: ((bits >> 19) & 0b11) as u8,
+ }
+}
+
+impl WinnerDeclaration {
+ pub(in crate::css::style) fn new(
+ property: u16,
+ important: bool,
+ value: WinnerValue,
+ origin: CascadeOrigin,
+ ) -> Self {
+ Self {
+ property,
+ important,
+ value,
+ origin,
+ dependencies: Cell::new(0),
+ }
+ }
+}
+
+#[derive(Default)]
+pub(in crate::css::style) struct WinnerStore {
+ // NB: Cascade order supplies both source slots and logical/physical tie breaking.
+ declarations: Vec<WinnerDeclaration>,
+ by_property: Vec<u16>,
+}
+
+impl WinnerStore {
+ pub(in crate::css::style) fn new(declarations: Vec<WinnerDeclaration>) -> Self {
+ let mut by_property = vec![u16::MAX; crate::css::property_metadata::NUMBER_OF_LONGHAND_PROPERTIES];
+ for (index, declaration) in declarations.iter().enumerate() {
+ by_property
+ [usize::from(declaration.property - crate::css::property_metadata::FIRST_LONGHAND_PROPERTY_ID)] =
+ u16::try_from(index).expect("winner count exceeds longhand count");
+ }
+ Self {
+ declarations,
+ by_property,
+ }
+ }
+
+ /// The proof that no value the store holds resolves a `url()`, or `None` when one may.
+ pub(in crate::css::style) fn reads_no_resource_contexts(
+ &self,
+ engine: &RetainedState,
+ ) -> Option<ReadsNoResourceContexts> {
+ let view = self.view(engine);
+ (!self
+ .declarations
+ .iter()
+ .any(|declaration| view.dependencies(declaration).may_need_style_sheet_resource_context))
+ .then_some(ReadsNoResourceContexts(()))
+ }
+
+ /// The container-relative units the values the store holds resolve, as a
+ /// `container_relative_length_unit_mask`.
+ pub(in crate::css::style) fn container_unit_mask(&self, engine: &RetainedState) -> u8 {
+ let view = self.view(engine);
+ self.declarations.iter().fold(0, |mask, declaration| {
+ mask | view.dependencies(declaration).container_relative_length_unit_mask
+ })
+ }
+
+ pub(in crate::css::style) fn view<'a>(&'a self, engine: &'a RetainedState) -> WinnerView<'a> {
+ WinnerView { store: self, engine }
+ }
+
+ fn declaration(&self, property: u16) -> Option<(usize, &WinnerDeclaration)> {
+ let index = usize::from(*self.by_property.get(usize::from(
+ property.checked_sub(crate::css::property_metadata::FIRST_LONGHAND_PROPERTY_ID)?,
+ ))?);
+ self.declarations.get(index).map(|declaration| (index, declaration))
+ }
+}
+
+pub(in crate::css::style) struct WinnerView<'a> {
+ store: &'a WinnerStore,
+ engine: &'a RetainedState,
+}
+
+pub(in crate::css::style) fn shorthand_longhand_data(
+ property: u16,
+ data: &StyleValueData,
+) -> Option<&RetainedStyleValueData> {
+ let StyleValueData::Shorthand(shorthand_payload) = data else {
+ return None;
+ };
+ let ShorthandPayload {
+ sub_properties, values, ..
+ } = &**shorthand_payload;
+ for (&sub_property, sub_value) in sub_properties.as_slice().iter().zip(values.as_slice()) {
+ if sub_property == property {
+ return Some(sub_value);
+ }
+ if let Some(found) = shorthand_longhand_data(property, sub_value.data()) {
+ return Some(found);
+ }
+ }
+ None
+}
+
+impl WinnerView<'_> {
+ fn value<'a>(&'a self, declaration: &'a WinnerDeclaration) -> &'a RetainedStyleValueData {
+ let written = match &declaration.value {
+ WinnerValue::Substituted { value, .. } => return value,
+ WinnerValue::Written { node, source, index } => match source {
+ WinnerSource::Rule(rule) => &self.engine.rules.written_values_of(*rule)[*index],
+ WinnerSource::Element(kind) => self
+ .engine
+ .element_declarations
+ .declarations(*node, *kind)
+ .expect("a written winner's declarations are held")
+ .written(*index),
+ },
+ };
+ match written.data() {
+ data @ StyleValueData::Shorthand { .. } => {
+ shorthand_longhand_data(declaration.property, data).expect("validated shorthand winner")
+ }
+ _ => written,
+ }
+ }
+}
+
+impl WinnerStore {
+ /// The resource context of each declaration, in cascade order, as the drive reads a winner's
+ /// source slot. Empty, and no allocation, when no declaration may read one.
+ pub(in crate::css::style) fn drive_resource_contexts(
+ &self,
+ engine: &RetainedState,
+ ) -> Vec<crate::css::style_compute::FfiStyleSheetResourceContext> {
+ if self.reads_no_resource_contexts(engine).is_some() {
+ return Vec::new();
+ }
+ let view = self.view(engine);
+ self.declarations
+ .iter()
+ .map(|declaration| {
+ view.resource_context(declaration).map_or(
+ crate::css::style_compute::FfiStyleSheetResourceContext::empty(),
+ |context| context.as_drive_context(),
+ )
+ })
+ .collect()
+ }
+}
+
+impl WinnerStore {
+ /// The random sharings of the declarations' random functions whose random base value is not
+ /// fixed, as the drive finds their base values: by pointer.
+ fn unfixed_random_sharings(&self, engine: &RetainedState) -> Vec<*const StyleValueData> {
+ let view = self.view(engine);
+ let mut sharings = Vec::new();
+ for declaration in &self.declarations {
+ if view.dependencies(declaration).has_unfixed_random_sharing {
+ crate::css::style_compute::collect_unfixed_random_sharings_in_value(
+ view.value(declaration).data(),
+ &mut sharings,
+ );
+ }
+ }
+ sharings
+ }
+
+ /// The random caching key of every random function in the declarations that has not got a
+ /// base value yet, for a drive of `node`'s record.
+ pub(in crate::css::style) fn undrawn_random_keys(
+ &self,
+ engine: &RetainedState,
+ node: StyleNodeID,
+ ) -> Vec<crate::css::style::random_bases::RandomBaseRequest> {
+ self.unfixed_random_sharings(engine)
+ .into_iter()
+ .filter_map(|sharing| {
+ // SAFETY: The declarations retain every value a sharing is part of.
+ let (name, element_shared) = crate::css::style_compute::random_caching_key(unsafe { &*sharing });
+ engine
+ .drawn_random_base_value(node, name, element_shared)
+ .is_none()
+ .then(|| crate::css::style::random_bases::RandomBaseRequest {
+ node,
+ name: name.into(),
+ element_shared,
+ })
+ })
+ .collect()
+ }
+
+ /// The random base values of the declarations' random functions for a drive of `node`'s
+ /// record. Empty, and no allocation, when they hold none; `None` when one was not drawn for
+ /// the node.
+ pub(in crate::css::style) fn drive_random_base_values(
+ &self,
+ engine: &RetainedState,
+ node: StyleNodeID,
+ ) -> Option<Vec<crate::css::style_compute::FfiRandomBaseValue>> {
+ self.unfixed_random_sharings(engine)
+ .into_iter()
+ .map(|sharing| {
+ // SAFETY: The declarations retain every value a sharing is part of.
+ let (name, element_shared) = crate::css::style_compute::random_caching_key(unsafe { &*sharing });
+ Some(crate::css::style_compute::FfiRandomBaseValue {
+ source: sharing.cast(),
+ value: engine.random_base_values.get(node, name, element_shared)?,
+ })
+ })
+ .collect()
+ }
+}
+
+impl<'a> WinnerView<'a> {
+ fn dependencies(&self, declaration: &WinnerDeclaration) -> ExternalValueDependencies {
+ let memoized = declaration.dependencies.get();
+ if memoized & DEPENDENCIES_COMPUTED != 0 {
+ return unpack_dependencies(memoized);
+ }
+ // A written value's dependencies were prepared with the declaration it was written in.
+ if let WinnerValue::Written { node, source, index } = &declaration.value {
+ let prepared = match source {
+ WinnerSource::Rule(rule) => self.engine.rules.written_value_checks(*rule, *index).dependencies(),
+ WinnerSource::Element(kind) => self
+ .engine
+ .element_declarations
+ .declarations(*node, *kind)
+ .map_or(0, |declarations| declarations.checks(*index).dependencies()),
+ };
+ if prepared & DEPENDENCIES_COMPUTED != 0 {
+ declaration.dependencies.set(prepared);
+ return unpack_dependencies(prepared);
+ }
+ }
+ // A value whose independence is not known reads its parent, conservatively.
+ let dependencies = crate::css::style_compute::try_external_value_dependencies(self.value(declaration).data())
+ .unwrap_or(ExternalValueDependencies {
+ inheritance_dependent: true,
+ ..ExternalValueDependencies::default()
+ });
+ declaration.dependencies.set(pack_dependencies(dependencies));
+ dependencies
+ }
+
+ /// The resource context of the sheet a rule declaration came from, written or substituted. An
+ /// element's own declarations resolve against the document's base URL, as they do in the
+ /// host's cascade.
+ fn resource_context(
+ &self,
+ declaration: &WinnerDeclaration,
+ ) -> Option<&'a super::resource_contexts::StyleSheetResourceContext> {
+ let (WinnerValue::Written {
+ source: WinnerSource::Rule(rule),
+ ..
+ }
+ | WinnerValue::Substituted {
+ source: WinnerSource::Rule(rule),
+ ..
+ }) = declaration.value
+ else {
+ return None;
+ };
+ let engine: &'a RetainedState = self.engine;
+ engine
+ .document_resource_contexts
+ .for_source(engine.rule_source_identity(rule)?)
+ }
+}
+
+impl CascadedValues for WinnerView<'_> {
+ fn winning_declaration(&self, property: u16) -> Option<WinningDeclaration<'_>> {
+ let (index, declaration) = self.store.declaration(property)?;
+ Some((
+ self.value(declaration),
+ declaration.important,
+ u32::try_from(index).unwrap(),
+ self.resource_context(declaration).is_some(),
+ self.dependencies(declaration),
+ ))
+ }
+
+ fn winning_origin(&self, property: u16) -> Option<CascadeOrigin> {
+ Some(self.store.declaration(property)?.1.origin)
+ }
+
+ fn property_with_higher_priority(&self, first: u16, second: u16) -> u16 {
+ match (self.store.declaration(first), self.store.declaration(second)) {
+ (Some((first_index, _)), Some((second_index, _))) if first_index >= second_index => first,
+ (Some(_), None) => first,
+ _ => second,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::css::property_metadata::property_id;
+ use crate::css::style_value::{ImagePayload, StyleValueBox, UrlPayload};
+
+ #[test]
+ fn only_urls_without_resource_dependencies_read_no_resource_contexts() {
+ use crate::css::style_value::{ImageResourceContext, RetainedRequestUrlModifierList, RetainedString};
+
+ let store = |property, value| {
+ WinnerStore::new(vec![WinnerDeclaration::new(
+ property,
+ false,
+ WinnerValue::Substituted {
+ value: RetainedStyleValueData::from_owned(value),
+ source: WinnerSource::Element(ElementDeclarationKind::InlineStyle),
+ },
+ CascadeOrigin::Author,
+ )])
+ };
+ let engine = StyleEngine::new();
+ for (url, can_reuse) in [
+ ("https://example.com/paint.svg#fill", true),
+ ("data:image/svg+xml,paint", true),
+ ("paint.svg#fill", false),
+ ("/paint.svg#fill", false),
+ ("//example.com/paint.svg#fill", false),
+ ] {
+ let url_value = || {
+ StyleValueData::Url(StyleValueBox::new(UrlPayload {
+ url: RetainedString::from_ascii(url.to_owned()),
+ url_type: 0,
+ modifiers: RetainedRequestUrlModifierList::from_retained_modifiers(Vec::new()),
+ }))
+ };
+ let first = store(property_id::FILL, url_value());
+ assert_eq!(
+ first.reads_no_resource_contexts(&engine.retained).is_some(),
+ can_reuse,
+ "{url}"
+ );
+ }
+
+ let image_value = |base_url: &str, origin_clean| {
+ StyleValueData::Image(StyleValueBox::new(ImagePayload {
+ url: RetainedString::from_ascii("https://example.com/image.png".to_owned()),
+ url_type: 0,
+ url_modifiers: RetainedRequestUrlModifierList::from_retained_modifiers(Vec::new()),
+ resource_context: ImageResourceContext {
+ base_url: RetainedString::from_ascii(base_url.to_owned()),
+ has_base_url: true,
+ has_parent_style_sheet_origin_clean: true,
+ parent_style_sheet_origin_clean: origin_clean,
+ should_absolutize_url_for_computed_value: true,
+ },
+ }))
+ };
+ let first = store(
+ property_id::BACKGROUND_IMAGE,
+ image_value("https://example.com/first.css", true),
+ );
+ assert!(first.reads_no_resource_contexts(&engine.retained).is_none());
+ }
+
+ #[test]
+ fn winner_view_borrows_written_spelling_and_preserves_cascade_order() {
+ let mut engine = StyleEngine::new();
+ let node = StyleNodeID::element(1);
+ let kind = ElementDeclarationKind::InlineStyle;
+ let properties = [property_id::MARGIN_LEFT, property_id::MARGIN_INLINE_START];
+ let written = [1.25, 2.5].map(|value| RetainedStyleValueData::from_owned(StyleValueData::Number { value }));
+ let mut owned = CascadedPropertyStore::new();
+ for (&property, value) in properties.iter().zip(&written) {
+ owned.seed_retained_property(property, value.clone_retained(), true, false);
+ }
+ let observer = written[0].clone_retained().into_arc();
+ engine.element_declarations.set(
+ node,
+ kind,
+ properties
+ .iter()
+ .map(|&property| DeclarationEntry::new(property, true, CascadeOperator::Declared))
+ .zip(written)
+ .collect(),
+ );
+ let owners = crate::css::style_value_arc::StyleValueArc::strong_count(&observer);
+ let store = WinnerStore::new(
+ properties
+ .iter()
+ .enumerate()
+ .map(|(index, &property)| {
+ WinnerDeclaration::new(
+ property,
+ true,
+ WinnerValue::Written {
+ node,
+ source: WinnerSource::Element(kind),
+ index,
+ },
+ CascadeOrigin::Author,
+ )
+ })
+ .collect(),
+ );
+ let view = store.view(&engine);
+ for property in properties {
+ let actual = view.winning_declaration(property).unwrap();
+ let expected = owned.winning_declaration(property).unwrap();
+ assert_eq!(
+ (actual.0.pointer(), actual.1, actual.2, actual.3),
+ (expected.0.pointer(), expected.1, expected.2, expected.3)
+ );
+ assert!(matches!(view.winning_origin(property), Some(CascadeOrigin::Author)));
+ }
+ assert_eq!(
+ view.property_with_higher_priority(properties[0], properties[1]),
+ properties[1]
+ );
+ assert_eq!(
+ view.property_with_higher_priority(properties[1], properties[0]),
+ properties[1]
+ );
+ assert!(view.winning_declaration(property_id::OPACITY).is_none());
+ assert_eq!(
+ crate::css::style_value_arc::StyleValueArc::strong_count(&observer),
+ owners
+ );
+ drop(store);
+ assert_eq!(
+ crate::css::style_value_arc::StyleValueArc::strong_count(&observer),
+ owners
+ );
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/write_once.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/write_once.rs
new file mode 100644
index 00000000000..473b8110f2f
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/write_once.rs
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! A slot one thread writes once, which other threads read after it is written: what a the engine
+//! pass keeps per element, written by the thread styling the element and read by those styling its
+//! descendants. Writing it takes one atomic compare-exchange and one store, where a `OnceLock` goes
+//! through `Once`.
+
+use std::cell::UnsafeCell;
+use std::mem::MaybeUninit;
+use std::sync::atomic::{AtomicU8, Ordering};
+
+const EMPTY: u8 = 0;
+const WRITING: u8 = 1;
+const WRITTEN: u8 = 2;
+
+pub(super) struct WriteOnce<T> {
+ state: AtomicU8,
+ value: UnsafeCell<MaybeUninit<T>>,
+}
+
+impl<T> Default for WriteOnce<T> {
+ fn default() -> Self {
+ Self {
+ state: AtomicU8::new(EMPTY),
+ value: UnsafeCell::new(MaybeUninit::uninit()),
+ }
+ }
+}
+
+impl<T> WriteOnce<T> {
+ pub(super) fn get(&self) -> Option<&T> {
+ // SAFETY: A written value is initialized and never written again, and the acquire load
+ // sees the writes that made it.
+ (self.state.load(Ordering::Acquire) == WRITTEN).then(|| unsafe { (*self.value.get()).assume_init_ref() })
+ }
+
+ /// Write the slot, or hand the value back where it was written before.
+ pub(super) fn set(&self, value: T) -> Result<(), T> {
+ if self
+ .state
+ .compare_exchange(EMPTY, WRITING, Ordering::Acquire, Ordering::Relaxed)
+ .is_err()
+ {
+ return Err(value);
+ }
+ // SAFETY: Only the thread that moved the slot from empty to writing writes it, and no
+ // reader reads it before it is marked written.
+ unsafe { (*self.value.get()).write(value) };
+ self.state.store(WRITTEN, Ordering::Release);
+ Ok(())
+ }
+}
+
+impl<T> WriteOnce<T> {
+ /// Take the value, where the slot was written, leaving it empty.
+ pub(super) fn take(&mut self) -> Option<T> {
+ let written = *self.state.get_mut() == WRITTEN;
+ *self.state.get_mut() = EMPTY;
+ // SAFETY: A written value is initialized, and marking the slot empty keeps it from being
+ // read or dropped again.
+ written.then(|| unsafe { self.value.get_mut().assume_init_read() })
+ }
+}
+
+impl<T> Drop for WriteOnce<T> {
+ fn drop(&mut self) {
+ if *self.state.get_mut() == WRITTEN {
+ // SAFETY: The value was written and is dropped once, with the slot.
+ unsafe { self.value.get_mut().assume_init_drop() };
+ }
+ }
+}
+
+// SAFETY: The slot hands out shared references to its value across threads and drops it on the
+// thread dropping the slot, as a `OnceLock` does.
+unsafe impl<T: Send + Sync> Sync for WriteOnce<T> {}
+unsafe impl<T: Send> Send for WriteOnce<T> {}
diff --git a/Libraries/LibWeb/Rust/src/css/style/planning.rs b/Libraries/LibWeb/Rust/src/css/style/planning.rs
deleted file mode 100644
index 6b14d1e3a90..00000000000
--- a/Libraries/LibWeb/Rust/src/css/style/planning.rs
+++ /dev/null
@@ -1,1365 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-use super::column::EpochColumn;
-use super::column::PagedColumn;
-use super::column::PagedColumnPage;
-use super::column::advance_epoch;
-use super::program::EntryID;
-use super::shared_vector::{SharedVector, SharedVectorPool};
-use super::sorted_merge::SortedMergeEntry;
-use super::sorted_merge::merge_sorted_by;
-use super::*;
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
-pub(super) struct PendingRoute {
- pub(super) route: RouteID,
- pub(super) exact_tree_evaluation: Option<ExactTreeEvaluation>,
-}
-
-#[derive(Clone, Copy)]
-pub(super) struct PendingPrefixProducer {
- pub(super) node: StyleNodeID,
- pub(super) producer: PrefixProducer,
-}
-
-#[derive(Clone, Copy)]
-pub(super) enum RetainedWinnerProbe {
- Node(StyleNodeID),
- AllResident { resident_count: usize },
-}
-
-pub(super) struct RemainingPosting {
- nodes: Vec<StyleNodeID>,
- plan_generation: u64,
- pruned_nodes: Vec<StyleNodeID>,
-}
-
-#[derive(Default)]
-pub(super) struct RemainingPostingDirectory {
- entries: Vec<(PostingKey, RemainingPosting)>,
-}
-
-impl RemainingPostingDirectory {
- fn entry(&mut self, key: PostingKey) -> Option<&mut RemainingPosting> {
- self.entries
- .iter_mut()
- .find(|(candidate, _)| *candidate == key)
- .map(|(_, posting)| posting)
- }
-
- fn insert(&mut self, key: PostingKey, posting: RemainingPosting) -> &mut RemainingPosting {
- self.entries.push((key, posting));
- &mut self.entries.last_mut().unwrap().1
- }
-}
-
-#[derive(Default)]
-pub(super) struct ImpactPlanningWorkspace {
- pub(super) batches: HashMap<Box<[ImpactRegion]>, Arc<ImpactRegionBatch>>,
- // Fact postings cannot change while one transaction is being planned, and the exact-node plan
- // only grows. Removing planned nodes here is therefore permanent for the lifetime of this
- // workspace: later routes see the posting members that can still contribute, not the same
- // already-planned prefix over and over.
- pub(super) remaining_postings: RemainingPostingDirectory,
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
-pub(super) enum SetChange {
- Added,
- Removed,
-}
-
-/// Exact old/new evaluation was unavailable, so conservative planning still treats the entry as
-/// changed but retained-answer maintenance must use its upquery fallback.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub(super) struct ExactEntryGap;
-
-pub(super) type ExactEntryResult = Lookup<SetChange, ExactEntryGap>;
-
-pub(super) fn exact_entry_changed(result: ExactEntryResult) -> bool {
- !matches!(result, Lookup::KnownAbsent)
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
-pub(super) struct SelectorTruthDelta {
- pub(super) node: StyleNodeID,
- pub(super) rule: RuleID,
- pub(super) entry: EntryID,
- pub(super) change: SetChange,
- /// Activation changes the active-match join, not selector truth itself.
- pub(super) selector_truth_changed: bool,
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
-pub(super) struct SelectorTruthRefresh {
- pub(super) node: StyleNodeID,
- pub(super) rule: Option<(RuleID, EntryID)>,
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
-pub(super) struct AlreadyPlannedSelectorTruthCandidate {
- pub(super) node: StyleNodeID,
- pub(super) exact_entry: Option<(RuleID, EntryID)>,
- pub(super) exact_tree_evaluation: Option<ExactTreeEvaluation>,
-}
-
-/// A transaction batch whose common singleton form neither allocates nor sorts.
-#[derive(Clone, Default)]
-pub(super) enum DeltaBatch<T> {
- #[default]
- Empty,
- One(T),
- Many(Vec<T>),
-}
-
-impl<T> DeltaBatch<T> {
- pub(super) fn push(&mut self, item: T) {
- match std::mem::replace(self, Self::Empty) {
- Self::Empty => *self = Self::One(item),
- Self::One(first) => *self = Self::Many(vec![first, item]),
- Self::Many(mut items) => {
- items.push(item);
- *self = Self::Many(items);
- }
- }
- }
-
- #[must_use]
- pub(super) fn as_slice(&self) -> &[T] {
- match self {
- Self::Empty => &[],
- Self::One(item) => std::slice::from_ref(item),
- Self::Many(items) => items,
- }
- }
-}
-
-impl<T: Ord> DeltaBatch<T> {
- pub(super) fn consolidate(&mut self) {
- if let Self::Many(items) = self {
- items.sort_unstable();
- items.dedup();
- }
- }
-}
-
-/// Exact selector changes and the exceptional requests that must refresh missing truth.
-///
-/// An exact change is both the retained-answer maintenance payload and its provenance. A route
-/// records a refresh only when it cannot preserve that old/new pair. Nodes reached through broad
-/// impact regions need no entry here because the region itself is already the refresh request.
-#[derive(Clone, Default)]
-pub(super) struct SelectorTruthChanges {
- pub(super) deltas: DeltaBatch<SelectorTruthDelta>,
- pub(super) refreshes: DeltaBatch<SelectorTruthRefresh>,
-}
-
-#[derive(Clone, Copy)]
-pub(super) enum SelectorTruthPatch<'a> {
- Full,
- Direct(&'a [SelectorTruthDelta]),
- Refresh {
- deltas: &'a [SelectorTruthDelta],
- refreshes: &'a [SelectorTruthRefresh],
- },
- /// The node is covered by rule-attributed regions: only those rules and the node's own
- /// deltas can have moved its truth, so the patch re-derives that union instead of the
- /// transaction's whole affected set.
- Attributed {
- deltas: &'a [SelectorTruthDelta],
- refreshes: &'a [SelectorTruthRefresh],
- rules: &'a [(RuleID, EntryID)],
- },
-}
-
-impl RetainedState {
- /// Streams the element descendants of `root` in flat-tree inheritance order without asking the
- /// DOM to rediscover slot and shadow relations already resident in the engine.
- pub(super) fn for_each_flat_tree_descendant(&mut self, root: StyleNodeID, mut visit: impl FnMut(StyleNodeID)) {
- let mut pending: Vec<_> = self.tree.flat_tree_children(root).collect();
-
- while let Some(node) = pending.pop() {
- // A text node holds a place among a slot's assigned nodes, but it has no style of its
- // own and owns no child sequence the flat tree descends into.
- if node.element_index().is_none() {
- continue;
- }
- visit(node);
-
- pending.extend(self.tree.flat_tree_children(node));
- }
- }
-
- /// Record that a route needs exact selector truth refreshed for a planned node.
- pub(super) fn record_selector_truth_refresh(&mut self, node: StyleNodeID, rule: Option<(RuleID, EntryID)>) {
- if self.selector_truth_changes_active {
- self.selector_truth_changes
- .refreshes
- .push(SelectorTruthRefresh { node, rule });
- }
- }
-
- pub(super) fn record_exact_selector_truth_change(
- &mut self,
- node: StyleNodeID,
- site: &RoutingSite<'_>,
- result: ExactEntryResult,
- ) {
- if !self.selector_truth_changes_active {
- return;
- }
- let Some((rule, entry)) = site.exact_entry else {
- self.record_selector_truth_refresh(node, site.refresh_rule);
- return;
- };
- match result {
- Lookup::Known(kind) => {
- self.selector_truth_changes.deltas.push(SelectorTruthDelta {
- node,
- rule,
- entry,
- change: kind,
- selector_truth_changed: true,
- });
- }
- Lookup::KnownAbsent => {}
- Lookup::Missing(_) => self.record_selector_truth_refresh(node, Some((rule, entry))),
- }
- }
-
- /// Preserve the exact contribution of a route whose candidate is already in the impact set.
- ///
- /// The earlier route proves only that the node needs style work. Defer this route until all
- /// symbolic coverage is known, so a coarse region can absorb it without an entry evaluation.
- pub(super) fn record_already_planned_selector_truth(&mut self, node: StyleNodeID, site: &RoutingSite<'_>) {
- if !self.selector_truth_changes_active {
- return;
- }
- // This relation exists only to patch the node's retained exact answer. A node without
- // both sides of that retained identity will be cold-completed if it survives the plan,
- // so expanding every route which also reaches it into selector-truth scratch has no
- // consumer. StyleBench sibling routes can otherwise manufacture hundreds of thousands
- // of rows for nodes whose retained payload was never admitted.
- if !matches!(self.retained_match_answer(node), Lookup::Known(_))
- || !matches!(self.retained_match_answers.cascade_input_lookup(node), Lookup::Known(_))
- {
- return;
- }
- self.already_planned_selector_truth
- .push(AlreadyPlannedSelectorTruthCandidate {
- node,
- exact_entry: site.exact_entry,
- exact_tree_evaluation: site.exact_tree_evaluation,
- });
- }
-
- /// Resolve deferred exact-node routes after the plan's symbolic coverage is final.
- pub(super) fn resolve_already_planned_selector_truth(
- &mut self,
- regions: &ImpactRegions,
- coarse_cover: Option<&ImpactRegionBatch>,
- ) {
- let candidates = std::mem::take(&mut self.already_planned_selector_truth);
-
- for candidate in candidates.as_slice() {
- if coarse_cover.is_some_and(|cover| regions.batch_contains_node(cover, candidate.node)) {
- continue;
- }
- let site = RoutingSite {
- subject: &[],
- subject_required: &[],
- position: SubjectPosition::UNBOUNDED,
- path: &[],
- waypoints: &[],
- in_flux: None,
- exact_entry: candidate.exact_entry,
- exact_tree_evaluation: candidate.exact_tree_evaluation,
- refresh_rule: None,
- };
- let result = self.candidate_changes_exact_entry(candidate.node, &site);
- self.record_exact_selector_truth_change(candidate.node, &site, result);
- }
- }
-}
-
-/// Record the rules of every dispatch entry in exactly one of two match sets.
-///
-/// Both sets belong to one prefix-state interner, which stores their entries in canonical order.
-pub(super) fn record_match_set_difference(
- changes: &mut SelectorTruthChanges,
- active: bool,
- node: StyleNodeID,
- old_matches: &[EntryID],
- new_matches: &[EntryID],
- dispatch: &RuleDispatch,
- program: &StyleSheetProgram,
-) {
- if !active {
- return;
- }
- let mut record = |entry: EntryID, kind| {
- let mut previous_rule = None;
- for candidate in dispatch.entries_for_identity(entry) {
- // Prefix truth is independent of activation. Only deciding rules belong in an
- // exact cascade answer, just as when ordinary matching consumes these identities.
- if !program.rule_can_decide(candidate.rule) {
- continue;
- }
- if previous_rule == Some(candidate.rule) {
- continue;
- }
- previous_rule = Some(candidate.rule);
- changes.deltas.push(SelectorTruthDelta {
- node,
- rule: candidate.rule,
- entry,
- change: kind,
- selector_truth_changed: true,
- });
- }
- };
- debug_assert!(old_matches.is_sorted());
- debug_assert!(new_matches.is_sorted());
- for entry in merge_sorted_by(old_matches, new_matches, Ord::cmp) {
- match entry {
- SortedMergeEntry::Left(&entry) => record(entry, SetChange::Removed),
- SortedMergeEntry::Right(&entry) => record(entry, SetChange::Added),
- SortedMergeEntry::Both(_, _) => {}
- }
- }
-}
-
-/// Difference two exact per-node match relations into signed selector truth.
-pub(super) fn repaired_selector_truth_deltas(
- node: StyleNodeID,
- old_matches: &[RetainedRuleMatch],
- new_matches: &mut [RuleMatch],
- programs: &SelectorPrograms,
-) -> Option<Vec<SelectorTruthDelta>> {
- const LINEAR_SEARCH_COMPARISONS: usize = 16;
- let retained_key = |entry: &RetainedRuleMatch| (entry.rule, entry.program, entry.entry);
- let current_key = |entry: &RuleMatch| (entry.rule, entry.program, entry.entry);
- let retained_is_sorted = old_matches
- .windows(2)
- .all(|pair| retained_key(&pair[0]) < retained_key(&pair[1]));
- if retained_is_sorted && old_matches.len().saturating_mul(new_matches.len()) > LINEAR_SEARCH_COMPARISONS {
- new_matches.sort_unstable_by_key(current_key);
- debug_assert!(
- !new_matches
- .windows(2)
- .any(|pair| current_key(&pair[0]) == current_key(&pair[1]))
- );
- let mut deltas = Vec::new();
- for entry in merge_sorted_by(old_matches, new_matches, |old, new| {
- retained_key(old).cmp(&current_key(new))
- }) {
- match entry {
- SortedMergeEntry::Both(old, new) => {
- if old.scope_proximity != new.scope_proximity {
- return None;
- }
- }
- SortedMergeEntry::Left(old) => {
- deltas.push(SelectorTruthDelta {
- node,
- rule: old.rule,
- entry: programs.entry_id(old.program, old.entry),
- change: SetChange::Removed,
- selector_truth_changed: true,
- });
- }
- SortedMergeEntry::Right(new) => {
- deltas.push(SelectorTruthDelta {
- node,
- rule: new.rule,
- entry: programs.entry_id(new.program, new.entry),
- change: SetChange::Added,
- selector_truth_changed: true,
- });
- }
- }
- }
- return Some(deltas);
- }
-
- let mut deltas = Vec::new();
- for entry in old_matches {
- let current = new_matches
- .iter()
- .find(|candidate| current_key(candidate) == retained_key(entry));
- if current.is_some_and(|current| current.scope_proximity != entry.scope_proximity) {
- return None;
- }
- if current.is_none() {
- deltas.push(SelectorTruthDelta {
- node,
- rule: entry.rule,
- entry: programs.entry_id(entry.program, entry.entry),
- change: SetChange::Removed,
- selector_truth_changed: true,
- });
- }
- }
- for entry in new_matches {
- let retained = old_matches
- .iter()
- .any(|candidate| retained_key(candidate) == current_key(entry));
- if !retained {
- deltas.push(SelectorTruthDelta {
- node,
- rule: entry.rule,
- entry: programs.entry_id(entry.program, entry.entry),
- change: SetChange::Added,
- selector_truth_changed: true,
- });
- }
- }
- deltas.sort_unstable();
- Some(deltas)
-}
-
-impl SelectorTruthChanges {
- pub(super) fn consolidate(&mut self, counters: &Counters) {
- match &mut self.deltas {
- DeltaBatch::Empty => {}
- DeltaBatch::One(delta) => {
- if delta.selector_truth_changed {
- counters.bump(match delta.change {
- SetChange::Added => Counter::SelectorTruthAdditions,
- SetChange::Removed => Counter::SelectorTruthRemovals,
- });
- }
- }
- DeltaBatch::Many(deltas) => {
- deltas.sort_unstable();
- let mut read = 0;
- let mut write = 0;
- while read < deltas.len() {
- let first = deltas[read];
- let key = (first.node, first.rule, first.entry);
- let mut added = false;
- let mut removed = false;
- let mut selector_truth_changed = false;
- while read < deltas.len() && (deltas[read].node, deltas[read].rule, deltas[read].entry) == key {
- match deltas[read].change {
- SetChange::Added => added = true,
- SetChange::Removed => removed = true,
- }
- selector_truth_changed |= deltas[read].selector_truth_changed;
- read += 1;
- }
- if added && removed {
- counters.bump(Counter::SelectorTruthCancellations);
- continue;
- }
- let change = if added {
- if selector_truth_changed {
- counters.bump(Counter::SelectorTruthAdditions);
- }
- SetChange::Added
- } else {
- if selector_truth_changed {
- counters.bump(Counter::SelectorTruthRemovals);
- }
- SetChange::Removed
- };
- deltas[write] = SelectorTruthDelta {
- node: first.node,
- rule: first.rule,
- entry: first.entry,
- change,
- selector_truth_changed,
- };
- write += 1;
- }
- deltas.truncate(write);
- }
- }
- self.refreshes.consolidate();
- counters.add(Counter::SelectorTruthRefreshes, self.refreshes.as_slice().len() as u64);
- }
-
- pub(super) fn range_for_node<T>(
- items: &[T],
- node: StyleNodeID,
- node_of: impl Fn(&T) -> StyleNodeID,
- ) -> std::ops::Range<usize> {
- let start = items.partition_point(|item| node_of(item) < node);
- let end = start + items[start..].partition_point(|item| node_of(item) == node);
- start..end
- }
-
- #[must_use]
- pub(super) fn deltas_for(&self, node: StyleNodeID) -> &[SelectorTruthDelta] {
- let items = self.deltas.as_slice();
- &items[Self::range_for_node(items, node, |delta| delta.node)]
- }
-
- #[must_use]
- pub(super) fn refreshes_for(&self, node: StyleNodeID) -> &[SelectorTruthRefresh] {
- let items = self.refreshes.as_slice();
- &items[Self::range_for_node(items, node, |refresh| refresh.node)]
- }
-}
-
-impl ImpactPlanningWorkspace {
- pub(super) fn insert_batch(&mut self, regions: &[ImpactRegion], batch: Arc<ImpactRegionBatch>) {
- let regions: Box<[ImpactRegion]> = regions.into();
- let previous = self.batches.insert(regions, batch);
- assert!(
- previous.is_none(),
- "region batches are inserted only after a cache miss"
- );
- }
-
- pub(super) fn extend_remaining_posting(
- &mut self,
- key: PostingKey,
- postings: &FeaturePostings,
- plan: &ImpactRegions,
- candidates: &mut Vec<StyleNodeID>,
- pruned_nodes: Option<&mut Vec<StyleNodeID>>,
- ) -> Result<(bool, usize, usize, usize), PostingKey> {
- let posting = match postings.lookup(key) {
- Lookup::Known(posting) => posting,
- Lookup::KnownAbsent => return Ok((false, 0, 0, 0)),
- Lookup::Missing(gap) => return Err(gap),
- };
- let (remaining, was_present, copied) = match self.remaining_postings.entry(key) {
- Some(remaining) => (remaining, true, 0),
- None => {
- let candidates: Vec<StyleNodeID> = posting.candidates().collect();
-
- let remaining = self.remaining_postings.insert(
- key,
- RemainingPosting {
- nodes: candidates,
- plan_generation: u64::MAX,
- pruned_nodes: Vec::new(),
- },
- );
- (remaining, false, posting.len())
- }
- };
- let posting = &mut remaining.nodes;
- let mut inspected = 0;
- let mut pruned = 0;
- let plan_generation = plan.exact_node_generation();
- if remaining.plan_generation != plan_generation {
- let pruned_this_call = &mut remaining.pruned_nodes;
- let previous_pruned_length = pruned_this_call.len();
- let point_removed = plan.for_each_exact_node_added_after(
- remaining.plan_generation,
- MAX_POINT_REMOVED_EXACT_NODES,
- |node| {
- if let Ok(index) = posting.binary_search(&node) {
- posting.remove(index);
- pruned_this_call.push(node);
- }
- },
- );
- if point_removed {
- pruned = pruned_this_call.len() - previous_pruned_length;
- } else {
- inspected = posting.len();
- let previous_length = posting.len();
- posting.retain(|&node| {
- let keep = !plan.contains_node(node);
- if !keep {
- pruned_this_call.push(node);
- }
- keep
- });
- pruned = previous_length - posting.len();
- }
- remaining.plan_generation = plan_generation;
- }
- // Every route consuming this posting reports the full pruned history: nodes dropped for
- // an earlier route are invisible to this one too. Without a consumer the history is
- // still kept, but nothing is copied or walked.
- if let Some(pruned_nodes) = pruned_nodes {
- pruned_nodes.extend_from_slice(&remaining.pruned_nodes);
- }
- candidates.extend_from_slice(posting);
- Ok((was_present, copied, inspected, pruned))
- }
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
-pub(super) enum SiblingRouteKind {
- Full,
- BeyondSibling,
- Departure,
- ExactUnion,
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
-pub(super) struct PendingSiblingRoute {
- pub(super) route: RouteID,
- pub(super) kind: SiblingRouteKind,
- pub(super) exact_tree_evaluation: Option<ExactTreeEvaluation>,
-}
-
-#[derive(Clone, Copy, Default)]
-pub(super) struct PrefixConvergenceOutcome {
- pub(super) sibling_routes_are_covered: bool,
- /// Whether the walk re-compared every member of every touched child sequence, so the
- /// positional truth movements of admitted entries are already exact planned regions and
- /// their deferred sequence routes need no generic narrowing.
- pub(super) positional_routes_are_covered: bool,
-}
-
-#[derive(Clone, Copy)]
-pub(super) struct PendingPrefixNode {
- pub(super) node: StyleNodeID,
- pub(super) entering_deltas: PrefixEnteringDeltas,
-}
-
-pub(super) trait PendingRouteKey: Copy + Ord {
- fn route(self) -> RouteID;
-}
-
-impl PendingRouteKey for PendingRoute {
- fn route(self) -> RouteID {
- self.route
- }
-}
-
-impl PendingRouteKey for PendingSiblingRoute {
- fn route(self) -> RouteID {
- self.route
- }
-}
-
-pub(super) const PENDING_ROUTE_PAGE_SHIFT: usize = 6;
-pub(super) const PENDING_ROUTE_PAGE_SIZE: usize = 1 << PENDING_ROUTE_PAGE_SHIFT;
-pub(super) const NO_PENDING_ROUTE: u32 = u32::MAX;
-
-struct SparseIndexPage {
- entries: [u32; PENDING_ROUTE_PAGE_SIZE],
-}
-
-impl Default for SparseIndexPage {
- fn default() -> Self {
- Self {
- entries: [u32::MAX; PENDING_ROUTE_PAGE_SIZE],
- }
- }
-}
-
-impl PagedColumnPage for SparseIndexPage {
- type Value = u32;
-
- const SHIFT: usize = PENDING_ROUTE_PAGE_SHIFT;
-
- fn get(&self, index: usize) -> Option<u32> {
- (self.entries[index] != u32::MAX).then_some(self.entries[index])
- }
-
- fn insert(&mut self, index: usize, value: u32) {
- self.entries[index] = value;
- }
-}
-
-pub(super) struct PendingRegionEntry<K> {
- pub(super) key: K,
- pub(super) regions: Vec<ImpactRegion>,
- pub(super) next_for_route: u32,
-}
-
-pub(super) struct PendingRegionTable<K> {
- pages: PagedColumn<SparseIndexPage>,
- pub(super) entries: Vec<PendingRegionEntry<K>>,
-}
-
-impl<K> Default for PendingRegionTable<K> {
- fn default() -> Self {
- Self {
- pages: PagedColumn::default(),
- entries: Vec::new(),
- }
- }
-}
-
-impl<K: PendingRouteKey> PendingRegionTable<K> {
- pub(super) fn new() -> Self {
- Self::default()
- }
-
- pub(super) fn head(&self, route: RouteID) -> u32 {
- let index = route.index();
- self.pages.get(index).unwrap_or(NO_PENDING_ROUTE)
- }
-
- pub(super) fn set_head(&mut self, route: RouteID, head: u32) {
- let index = route.index();
- self.pages.insert(index, head);
- }
-
- pub(super) fn regions_for(&mut self, key: K) -> &mut Vec<ImpactRegion> {
- let mut entry = self.head(key.route());
- while entry != NO_PENDING_ROUTE {
- let index = entry as usize;
- if self.entries[index].key == key {
- return &mut self.entries[index].regions;
- }
- entry = self.entries[index].next_for_route;
- }
-
- let next_for_route = self.head(key.route());
- let entry = u32::try_from(self.entries.len()).expect("pending route space exhausted");
- self.entries.push(PendingRegionEntry {
- key,
- regions: Vec::new(),
- next_for_route,
- });
- self.set_head(key.route(), entry);
- &mut self.entries[entry as usize].regions
- }
-
- pub(super) fn rebuild_index(&mut self) {
- for page in self.pages.pages_mut() {
- page.entries.fill(NO_PENDING_ROUTE);
- }
- for entry in 0..self.entries.len() {
- let route = self.entries[entry].key.route();
- let next = self.head(route);
- self.entries[entry].next_for_route = next;
- self.set_head(route, u32::try_from(entry).expect("pending route space exhausted"));
- }
- }
-
- pub(super) fn finish(&mut self) {
- self.entries.sort_unstable_by_key(|entry| entry.key);
- self.rebuild_index();
- }
-
- pub(super) fn keys(&self) -> impl Iterator<Item = K> + '_ {
- self.entries.iter().map(|entry| entry.key)
- }
-
- pub(super) fn iter_mut(&mut self) -> impl Iterator<Item = (K, &mut Vec<ImpactRegion>)> {
- self.entries.iter_mut().map(|entry| (entry.key, &mut entry.regions))
- }
-
- pub(super) fn retain(&mut self, mut keep: impl FnMut(K, &mut Vec<ImpactRegion>) -> bool) {
- self.entries.retain_mut(|entry| keep(entry.key, &mut entry.regions));
- self.rebuild_index();
- }
-
- pub(super) fn is_empty(&self) -> bool {
- self.entries.is_empty()
- }
-
- pub(super) fn len(&self) -> usize {
- self.entries.len()
- }
-}
-
-pub(super) type PendingRoutes = PendingRegionTable<PendingRoute>;
-pub(super) type PendingSiblingRoutes = PendingRegionTable<PendingSiblingRoute>;
-
-/// What one transaction did to one child sequence.
-///
-/// A sequence that changed several times before anything observed it moved once, by as much as all
-/// of those changes together. Measuring each change against the sequence as it ends up answers a
-/// question nobody asked: two rows appended move `:last-child` two positions, so the row that
-/// stopped being last is two away from the end and not one.
-#[derive(Clone)]
-pub(super) struct SequenceChange {
- /// The final child sequence, shared with exact evaluation and the following matching pass.
- pub(super) children: Arc<[StyleNodeID]>,
- pub(super) arrivals: u32,
- pub(super) departures: u32,
- /// The earliest and latest place in the final sequence that a change happened at.
- pub(super) span: Option<(usize, usize)>,
- /// Set when a change's place could not be found, which leaves the whole sequence moved.
- pub(super) unlocated: bool,
- /// The latest place an element that was already alive landed in. An element created here has no
- /// count to have moved, but one that moved into the place does, and nothing after it moved at
- /// all - so this is the one position on the far side of the span that a count from the end can
- /// still have crossed.
- pub(super) last_relocation: Option<usize>,
- /// The qualified types that joined or left this sequence. An `of-type` position can move only
- /// for children of one of these types, so retaining this transaction-local summary avoids
- /// routing every other type through every positional route.
- pub(super) changed_types: Vec<(StyleAtomID, StyleAtomID)>,
- /// A missing fact row must not make the type summary reject anything.
- pub(super) has_unidentified_type: bool,
- /// Newly allocated children have no old count to compare. Their subtree is already in the
- /// plan, but structural routing still needs to keep them as possible relational witnesses.
- /// Recorded unsorted with duplicates; `SequenceChanges::finish` normalizes for membership
- /// queries so a batch of k arrivals does not pay k linear scans here.
- pub(super) arriving_nodes: Vec<StyleNodeID>,
- /// Position index over `children`, built from the second located record on: one batch of k
- /// changes would otherwise pay O(k * n) placement scans against the final sequence.
- pub(super) positions: Option<HashMap<StyleNodeID, u32>>,
- pub(super) located_records: u32,
- /// Where in the final sequence each relational seam is, and which way it moved. Recorded only
- /// while some relational route is attached, and consumed once per parent by the deferred
- /// relational sequence pass. A record that could not be located carries
- /// `RELATIONAL_RECORD_UNLOCATED` and widens to the whole sequence.
- pub(super) relational_records: Vec<(u32, SequenceSide)>,
-}
-
-impl SequenceChange {
- pub(super) fn new(children: Arc<[StyleNodeID]>) -> Self {
- Self {
- children,
- arrivals: 0,
- departures: 0,
- span: None,
- unlocated: false,
- last_relocation: None,
- changed_types: Vec::new(),
- has_unidentified_type: false,
- arriving_nodes: Vec::new(),
- positions: None,
- located_records: 0,
- relational_records: Vec::new(),
- }
- }
-
- pub(super) fn record(
- &mut self,
- relations: TreeRelations,
- arriving: bool,
- relocated: bool,
- changed_type: Option<(StyleAtomID, StyleAtomID)>,
- changed_node: StyleNodeID,
- relational: Option<SequenceSide>,
- ) {
- match arriving {
- true => self.arrivals += 1,
- false => self.departures += 1,
- }
- match changed_type {
- Some(changed_type) if !self.changed_types.contains(&changed_type) => {
- self.changed_types.push(changed_type);
- }
- Some(_) => {}
- None => self.has_unidentified_type = true,
- }
- if arriving && !relocated {
- self.arriving_nodes.push(changed_node);
- }
- let located = self.locate(relations);
- match located {
- Some(at) => {
- self.span = Some(match self.span {
- Some((first, last)) => (first.min(at), last.max(at)),
- None => (at, at),
- });
- if arriving && relocated {
- self.last_relocation = Some(match self.last_relocation {
- Some(latest) => latest.max(at),
- None => at,
- });
- }
- }
- None => self.unlocated = true,
- }
- if let Some(side) = relational {
- let at = located.map_or(RELATIONAL_RECORD_UNLOCATED, |at| at as u32);
- self.relational_records.push((at, side));
- }
- }
-
- /// Where in the sequence as it ends up a change with these relations happened.
- ///
- /// The sibling a change names is normally still there, and the place is beside it. When it is
- /// not - because it left in this same transaction - the sibling on the other side answers, and a
- /// change at either end of the sequence needs no sibling to place it at all. Only a change
- /// between two elements that both left is unplaceable.
- pub(super) fn locate(&mut self, relations: TreeRelations) -> Option<usize> {
- self.located_records = self.located_records.saturating_add(1);
- match relations.previous_element_sibling {
- None => return Some(0),
- Some(previous) => {
- if let Some(at) = self.position_of(previous) {
- return Some(at + 1);
- }
- }
- }
- match relations.next_element_sibling {
- None => Some(self.children.len()),
- Some(next) => self.position_of(next),
- }
- }
-
- /// Where one child sits in the final sequence. The first record scans, since one change is
- /// the common shape and a scan reaches exactly as far as its place; from the second record on
- /// the sequence is indexed once so a batch of k changes costs O(n + k) rather than O(k * n).
- pub(super) fn position_of(&mut self, child: StyleNodeID) -> Option<usize> {
- if self.located_records <= 1 && self.positions.is_none() {
- return self.children.iter().position(|&candidate| candidate == child);
- }
- let positions = self.positions.get_or_insert_with(|| {
- self.children
- .iter()
- .enumerate()
- .map(|(at, &candidate)| (candidate, at as u32))
- .collect()
- });
- positions.get(&child).map(|&at| at as usize)
- }
-}
-
-/// The position of a relational sequence record that could not be located in the final sequence,
-/// which happens only for a change between two elements that both left. It widens every candidate
-/// range derived from positions to the whole sequence.
-pub(super) const RELATIONAL_RECORD_UNLOCATED: u32 = u32::MAX;
-
-/// What one transaction did to the child sequences it touched, keyed by dense parent identity.
-///
-/// Direct pages make repeated mutation-time updates constant-time. Entries stay packed and are
-/// sorted once before routing, so region emission retains deterministic parent order.
-#[derive(Default)]
-pub(super) struct SequenceChanges {
- pages: PagedColumn<SparseIndexPage>,
- pub(super) entries: Vec<(StyleNodeID, SequenceChange)>,
-}
-
-impl SequenceChanges {
- pub(super) fn new() -> Self {
- Self::default()
- }
-
- pub(super) fn entry_index(&self, parent: StyleNodeID) -> Option<usize> {
- let index = parent.element_index()? as usize;
- self.pages.get(index).map(|entry| entry as usize)
- }
-
- pub(super) fn get_or_insert_with(
- &mut self,
- parent: StyleNodeID,
- make_change: impl FnOnce() -> SequenceChange,
- ) -> &mut SequenceChange {
- if let Some(index) = self.entry_index(parent) {
- return &mut self.entries[index].1;
- }
-
- let element_index = parent
- .element_index()
- .expect("only elements can own sibling sequence changes") as usize;
- let entry = u32::try_from(self.entries.len()).expect("sequence change space exhausted");
- self.pages.insert(element_index, entry);
- self.entries.push((parent, make_change()));
- &mut self.entries[entry as usize].1
- }
-
- pub(super) fn finish(&mut self) {
- for (_, change) in &mut self.entries {
- change.arriving_nodes.sort_unstable();
- change.arriving_nodes.dedup();
- }
- self.entries.sort_unstable_by_key(|&(parent, _)| parent);
- for (entry, &(parent, _)) in self.entries.iter().enumerate() {
- let element_index = parent.element_index().unwrap() as usize;
- self.pages.insert(
- element_index,
- u32::try_from(entry).expect("sequence change space exhausted"),
- );
- }
- }
-
- pub(super) fn iter(&self) -> impl Iterator<Item = (StyleNodeID, &SequenceChange)> {
- self.entries.iter().map(|(parent, change)| (*parent, change))
- }
-
- pub(super) fn get(&self, parent: StyleNodeID) -> Option<&SequenceChange> {
- let element_index = parent.element_index()? as usize;
- let entry = self.pages.get(element_index)?;
- Some(&self.entries[entry as usize].1)
- }
-}
-
-#[derive(Clone)]
-
-pub(super) struct SiblingCandidateWorkspace {
- entry_by_route: SharedVector<u32>,
- pub(super) candidate_epochs: EpochColumn,
- pub(super) candidates: Vec<usize>,
- pub(super) epoch: u32,
-}
-
-impl SiblingCandidateWorkspace {
- pub(super) fn new(entries: &[SiblingEntry], entry_map_pool: &mut SharedVectorPool<u32>) -> Self {
- let route_count = entries.iter().map(|entry| entry.route.index() + 1).max().unwrap_or(0);
- let mut entry_by_route: SharedVector<u32> = (0..route_count).map(|_| u32::MAX).collect();
- for (index, entry) in entries.iter().enumerate() {
- let index = u32::try_from(index).expect("sibling entry space exhausted");
- assert_ne!(index, u32::MAX, "sibling entry space exhausted");
- entry_by_route.make_mut()[entry.route.index()] = index;
- }
- entry_by_route.share(entry_map_pool);
- Self {
- entry_by_route,
- candidate_epochs: {
- let mut column = EpochColumn::default();
- column.ensure_len(entries.len());
- column
- },
- candidates: Vec::with_capacity(entries.len()),
- epoch: 0,
- }
- }
-
- pub(super) fn begin(&mut self) {
- advance_epoch(&mut self.epoch, 1, &mut [&mut self.candidate_epochs]);
- self.candidates.clear();
- }
-
- pub(super) fn append(&mut self, route: RouteID) {
- let Some(&candidate) = self.entry_by_route.get(route.index()) else {
- return;
- };
- if candidate == u32::MAX || !self.candidate_epochs.mark(candidate as usize, self.epoch) {
- return;
- }
- self.candidates.push(candidate as usize);
- }
-}
-
-impl SiblingEntry {
- pub(super) fn site<'a>(
- &self,
- routing: &'a RoutingRegistry,
- exact_tree_evaluation: Option<ExactTreeEvaluation>,
- ) -> RoutingSite<'a> {
- let mut site = route_site(routing, self.route);
- site.exact_entry = exact_tree_evaluation.and(site.refresh_rule);
- site.exact_tree_evaluation = exact_tree_evaluation;
- site
- }
-
- /// The same site for a walk that starts where the sibling step already landed.
- ///
- /// The waypoints are the compounds the path passes through, checked by walking back from a
- /// candidate; dropping the step drops the compound it stood for. A registry that reports the two
- /// at different lengths is telling `path_meets_waypoints` not to walk at all, and that stays
- /// true of the tails.
- pub(super) fn site_beyond_the_sibling_step<'a>(
- &self,
- routing: &'a RoutingRegistry,
- exact_tree_evaluation: Option<ExactTreeEvaluation>,
- ) -> RoutingSite<'a> {
- let mut site = self.site(routing, exact_tree_evaluation);
- if site.waypoints.len() == site.path.len() {
- site.waypoints = &site.waypoints[1..];
- }
- site.path = &site.path[1..];
- site.exact_entry = site.refresh_rule;
- site
- }
-}
-
-/// One live structural route used by every sequence touched by a transaction.
-#[derive(Clone)]
-pub(super) struct SequenceEntry {
- pub(super) route: RouteID,
- pub(super) operator: SelectorOp,
- pub(super) can_compare_exactly: bool,
-}
-
-/// Sequence routes whose entries the prefix automaton answers exactly, held back until the
-/// convergence walk reports whether its exact per-member diffs subsumed them. The held entries
-/// are not routed until then: `entries` is the complete live entry list, so the shared entry
-/// index applies to it, and `deferred` marks the ones held back.
-#[derive(Default)]
-pub(super) struct DeferredSequenceRoutes {
- pub(super) entries: Vec<SequenceEntry>,
- pub(super) deferred: Vec<bool>,
-}
-
-impl DeferredSequenceRoutes {}
-
-/// Which sequence entries one routing pass handles: the ones the convergence walk cannot answer
-/// on the immediate pass, and the held-back ones when the walk failed to cover them.
-#[derive(Clone, Copy)]
-pub(super) struct SequenceEntrySelection<'a> {
- pub(super) mask: &'a [bool],
- pub(super) route_masked: bool,
-}
-
-impl SequenceEntrySelection<'_> {
- #[must_use]
- pub(super) fn selects(self, entry_index: usize) -> bool {
- self.mask[entry_index] == self.route_masked
- }
-}
-
-#[derive(Clone)]
-
-pub(super) struct NthSequenceEntryIndex {
- pub(super) nth: NthPosition,
- pub(super) unindexed: Vec<usize>,
- pub(super) by_origin: HashMap<DispatchKey, Vec<usize>>,
- pub(super) candidate_epochs: EpochColumn,
- pub(super) candidates: Vec<usize>,
- pub(super) epoch: u32,
-}
-
-#[derive(Clone, Default)]
-pub(super) struct SequenceEntryIndex {
- pub(super) empty: Vec<usize>,
- pub(super) nth: Vec<NthSequenceEntryIndex>,
-}
-
-impl SequenceEntryIndex {
- pub(super) fn build(entries: &[SequenceEntry], routing: &RoutingRegistry) -> Self {
- let mut index = Self::default();
- let mut nth_groups = HashMap::default();
- for (entry_index, entry) in entries.iter().enumerate() {
- let SelectorOp::NthPosition(nth) = entry.operator else {
- index.empty.push(entry_index);
- continue;
- };
- let group_index = *nth_groups.entry(nth).or_insert_with(|| {
- index.nth.push(NthSequenceEntryIndex {
- nth,
- unindexed: Vec::new(),
- by_origin: HashMap::default(),
- candidate_epochs: {
- let mut column = EpochColumn::default();
- column.ensure_len(entries.len());
- column
- },
- candidates: Vec::with_capacity(entries.len()),
- epoch: 0,
- });
- index.nth.len() - 1
- });
- let group = &mut index.nth[group_index];
- let point = routing.route(entry.route);
- let origin = routing.origin_dispatch_of(entry.route);
- // A relative positional input is a possible witness, so its originating compound
- // cannot reject it from the final tree alone. Non-resident dispatch keys likewise
- // cannot be used to enumerate all possible origins.
- if point.anchor.is_some() || origin.is_empty() || origin.iter().any(|key| !key.has_selector_posting()) {
- group.unindexed.push(entry_index);
- continue;
- }
- for &key in origin {
- group.by_origin.entry(key).or_default().push(entry_index);
- }
- }
- index
- }
-}
-
-impl SequenceEntry {
- pub(super) fn site<'a>(&self, routing: &'a RoutingRegistry) -> RoutingSite<'a> {
- let mut site = route_site(routing, self.route);
- if self.can_compare_exactly {
- site.exact_entry = site.refresh_rule;
- site.exact_tree_evaluation = Some(ExactTreeEvaluation::BeforeSiblingRelations);
- }
- site
- }
-}
-
-/// The routing site of one route, which is how its regions are narrowed.
-pub(super) fn route_site(routing: &RoutingRegistry, route: RouteID) -> RoutingSite<'_> {
- let point = routing.route(route);
- RoutingSite {
- subject: routing.subject_dispatch_of(route),
- subject_required: routing.subject_required_of(route),
- position: routing.subject_position_of(route),
- path: routing.path_of(route),
- waypoints: routing.waypoints_of(route),
- in_flux: None,
- exact_entry: None,
- exact_tree_evaluation: None,
- refresh_rule: Some((routing.rule_of(route), point.entry)),
- }
-}
-
-/// What a routed input's transpose site says about where its subjects are.
-///
-/// The subject compound to enumerate by, the position in a sibling sequence the subject is allowed
-/// to hold, the inverse path back to it, the compounds that path has to pass through, and the one
-/// element whose fact is mid-change. Every step of routing needs all of it, so it travels together.
-#[derive(Clone, Copy)]
-pub(super) struct RoutingSite<'a> {
- pub(super) subject: &'a [DispatchKey],
- pub(super) subject_required: &'a [DispatchKey],
- pub(super) position: SubjectPosition,
- pub(super) path: &'a [InverseStep],
- pub(super) waypoints: &'a [DispatchKey],
- pub(super) in_flux: Option<(StyleNodeID, DispatchKey)>,
- pub(super) exact_entry: Option<(RuleID, EntryID)>,
- pub(super) exact_tree_evaluation: Option<ExactTreeEvaluation>,
- /// The one rule this route can move when it cannot name an exact entry, for refresh and
- /// patch-cover attribution. A route that knows neither poisons covered answers to full
- /// re-derivation.
- pub(super) refresh_rule: Option<(RuleID, EntryID)>,
-}
-
-impl RoutingSite<'_> {
- /// The rule this route attributes its coverage to, from the exact entry when it has one.
- #[must_use]
- pub(super) fn attribution(&self) -> Option<(RuleID, EntryID)> {
- self.exact_entry.or(self.refresh_rule)
- }
-}
-
-/// Whether completion must preserve the full selector answer for retention.
-#[derive(Clone, Copy, PartialEq, Eq)]
-pub(super) enum CompletionExactness {
- Exact,
- AllowPruning,
-}
-
-/// The transaction-local output and retry state of one cold scope ask.
-pub(super) struct BatchMatchAttempt<'a> {
- pub(super) matches: &'a mut RuleMatches,
- pub(super) requests: Option<&'a mut Vec<Incomplete>>,
- pub(super) completed: Option<&'a mut [bool]>,
- pub(super) deferred_prefix_matches: Option<&'a mut Option<PrefixMatchSetID>>,
- pub(super) answer_is_exact: Option<&'a mut bool>,
- pub(super) cascade_only: bool,
-}
-
-pub(super) struct BatchMatchRetry<'a> {
- pub(super) requests: Option<&'a mut Vec<Incomplete>>,
- pub(super) completed: Option<&'a mut Vec<bool>>,
- pub(super) deferred_prefix_matches: Option<&'a mut Option<PrefixMatchSetID>>,
- pub(super) answer_is_exact: Option<&'a mut bool>,
- pub(super) cascade_only: bool,
-}
-
-#[derive(Clone, Copy)]
-pub(super) struct TreeRoutingMode<'a> {
- pub(super) use_exact: bool,
- pub(super) has_before_sibling_relations: bool,
- pub(super) transaction_inputs: &'a [NormalizedInput],
-}
-
-impl TreeRoutingMode<'_> {
- pub(super) fn tree_position_changed(self, node: StyleNodeID) -> bool {
- let Ok(index) = self
- .transaction_inputs
- .binary_search_by_key(&InputKey::TreeRelations(node), |input| input.key)
- else {
- return false;
- };
- let relations = |value| match value {
- InputValue::TreeRelations(relations) => relations,
- _ => None,
- };
- let old = relations(self.transaction_inputs[index].old);
- let new = relations(self.transaction_inputs[index].new);
- old.and_then(|relations| relations.parent) != new.and_then(|relations| relations.parent)
- || old.and_then(|relations| relations.next_element_sibling)
- != new.and_then(|relations| relations.next_element_sibling)
- }
-}
-
-pub(super) struct ProgramRoutingContext<'a> {
- pub(super) resident_nodes: Option<&'a [StyleNodeID]>,
- pub(super) winner_program_version: Option<ProgramVersion>,
- pub(super) document_root: StyleNodeID,
- pub(super) attachment_scopes: Option<&'a [TreeScopeID]>,
- pub(super) removed_rules_requiring_refresh: &'a mut Vec<RuleID>,
-}
-
-/// Which exact tree comparison a routed candidate can use.
-#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
-#[repr(usize)]
-pub(super) enum ExactTreeEvaluation {
- Arrival,
- MonotonicArrival,
- MonotonicDeparture,
- BeforeSiblingRelations,
-}
-
-impl ExactTreeEvaluation {
- #[allow(clippy::too_many_arguments)]
- pub(super) fn candidate_changes(
- self,
- tree: &StyleNodeTree,
- facts: &StyleNodeFacts,
- program: (&SelectorProgram, &selector::SelectorEntry),
- node: StyleNodeID,
- old_matches: Option<bool>,
- transaction_fact_view: Option<&TransactionFactView>,
- match_workspace: &mut MatchScratch,
- counters: &Counters,
- ) -> Result<ExactEntryResult, Incomplete> {
- let (compiled, entry) = program;
- // The new side reads the authoritative tree, which every candidate of this transaction
- // shares. The workspace's current tree side was reset when the transaction began, so the
- // sibling positions it memoizes were all measured in this topology, and a sequence that
- // several positional entries ask about is counted once rather than once per candidate.
- let evaluate_new = |match_workspace: &mut MatchScratch, counters: &Counters| {
- MatchEvaluator::new(tree, facts)
- .with_match_workspace(match_workspace, MatchEvaluationSide::Current)
- .indexing_stepped_positions_only()
- .matches_entry(compiled, entry, node, counters)
- };
- let evaluate_old = |match_workspace: &mut MatchScratch, view: &TransactionFactView, counters: &Counters| {
- match view.is_present(tree, TransactionFactSide::Before, node) {
- false => Ok(false),
- true => MatchEvaluator::new(tree, facts)
- .with_transaction_fact_view(view, TransactionFactSide::Before)
- .with_match_workspace(match_workspace, MatchEvaluationSide::OldTree)
- .matches_entry(compiled, entry, node, counters),
- }
- };
- match self {
- Self::Arrival => match evaluate_new(match_workspace, counters)? {
- true => Ok(Lookup::Known(SetChange::Added)),
- false => Ok(Lookup::KnownAbsent),
- },
- Self::MonotonicArrival | Self::MonotonicDeparture | Self::BeforeSiblingRelations => {
- let old = match old_matches {
- Some(old) => old,
- None => {
- let Some(view) = transaction_fact_view.filter(|view| view.before_sibling_relations_available)
- else {
- return Ok(Lookup::Missing(ExactEntryGap));
- };
- evaluate_old(match_workspace, view, counters)?
- }
- };
- let new = evaluate_new(match_workspace, counters)?;
- let change = match (old, new) {
- (false, true) => Lookup::Known(SetChange::Added),
- (true, false) => Lookup::Known(SetChange::Removed),
- _ => Lookup::KnownAbsent,
- };
- Ok(change)
- }
- }
- }
-}
-
-pub(super) fn mark_element_visited(visited: &mut Vec<bool>, node: StyleNodeID) -> bool {
- let index = node.element_index().expect("prefix convergence visits only elements") as usize;
- if visited.len() <= index {
- visited.resize(index + 1, false);
- }
- if visited[index] {
- return false;
- }
- visited[index] = true;
- true
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
-pub(super) struct PrefixAnswerKey<'a> {
- pub(super) prefix_contribution: MatchAnswerID,
- pub(super) non_prefix_matches: &'a [RetainedRuleMatch],
- pub(super) non_prefix_hash: u64,
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub(super) struct PrefixContributionKey {
- pub(super) program: ScopeProgramID,
- pub(super) matches: PrefixMatchSetID,
-}
diff --git a/Libraries/LibWeb/Rust/src/css/style/position_try.rs b/Libraries/LibWeb/Rust/src/css/style/position_try.rs
index c8940efc32c..71266eb9951 100644
--- a/Libraries/LibWeb/Rust/src/css/style/position_try.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/position_try.rs
@@ -12,30 +12,57 @@ use super::HashMap;
use super::RetainedState;
use super::layout_style::LayoutStyle;
use super::tree::{StyleNodeID, TreeScopeID};
-use crate::css::computed_longhand_table::ComputedLonghandTable;
+use crate::css::animated_overlay::{AnimatedOverlay, overlay_wins};
use crate::css::computed_value_types::{AnchorValues, FontValues};
-use crate::css::computed_values::InheritedBoxValues;
+use crate::css::computed_values::GroupValuesWriter;
use crate::css::css_enums::{anchor_size, keyword, position_area, try_tactic, writing_mode};
-use crate::css::declaration_block::DeclarationBlockData;
+use crate::css::declaration_block::SharedDeclarationBlock;
use crate::css::property_metadata::property_id;
+use crate::css::property_metadata::{FIRST_LONGHAND_PROPERTY_ID, LAST_LONGHAND_PROPERTY_ID};
+use crate::css::style_value::{AnchorPayload, AnchorSizePayload, CalculatedPayload, StyleValueBox};
use crate::css::style_value::{RetainedStyleValueData, StyleValueData};
+use crate::css::style_value_arc::StyleValueArc;
use crate::css::table_group_builder::group_index;
use std::sync::Arc;
/// One style scope's `@position-try` rules: the declarations of the rule each name resolves to.
-pub(crate) type PositionTryRow = HashMap<Box<[u16]>, Arc<DeclarationBlockData>>;
+pub(crate) type PositionTryRow = HashMap<Box<[u16]>, PositionTryRule>;
+
+/// One `@position-try` rule as a scope resolved it.
+#[derive(Clone)]
+pub(crate) struct PositionTryRule {
+ declarations: SharedDeclarationBlock,
+ id: PositionTryRuleID,
+}
+
+impl PositionTryRule {
+ pub(crate) fn declarations(&self) -> &SharedDeclarationBlock {
+ &self.declarations
+ }
+}
+
+/// What names one `@position-try` rule's declarations for as long as they stay, and never any declarations after
+/// them, as a box's last successful position option remembers it across layouts holding nothing of the rule.
+/// `NONE` stands for no rule.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub(crate) struct PositionTryRuleID(u64);
+
+impl PositionTryRuleID {
+ pub(crate) const NONE: Self = Self(0);
+}
/// The `@position-try` rules every style scope of the document defines, as each scope's rule cache resolved them.
#[derive(Clone, Default)]
pub(crate) struct PositionTryRules {
scopes: HashMap<TreeScopeID, PositionTryRow>,
+ last_id: u64,
}
impl PositionTryRules {
/// The row of the names, packed into one buffer of code units with a length each, and the declarations of each.
///
/// # Safety
- /// Each declaration pointer must be a live `Arc<DeclarationBlockData>`.
+ /// Each declaration pointer must point at the header of a live declaration block.
pub(crate) unsafe fn row(
name_lengths: &[u32],
name_units: &[u16],
@@ -50,27 +77,40 @@ impl PositionTryRules {
let units = &name_units[offset..offset + length as usize];
offset += length as usize;
// SAFETY: Guaranteed by the caller; the row takes a reference of its own.
- let declarations = unsafe {
- let declarations = declarations.cast::<DeclarationBlockData>();
- Arc::increment_strong_count(declarations);
- Arc::from_raw(declarations)
- };
- (Box::from(units), declarations)
+ let declarations = unsafe { SharedDeclarationBlock::retain(declarations.cast()) };
+ (
+ Box::from(units),
+ PositionTryRule {
+ declarations,
+ id: PositionTryRuleID::NONE,
+ },
+ )
})
.collect()
}
/// Replaces one scope's row. An empty row gives the scope's row up.
- pub(crate) fn set(&mut self, tree_scope: TreeScopeID, row: PositionTryRow) {
+ pub(crate) fn set(&mut self, tree_scope: TreeScopeID, mut row: PositionTryRow) {
if row.is_empty() {
self.scopes.remove(&tree_scope);
return;
}
+ let previous = self.scopes.get(&tree_scope);
+ for (name, rule) in &mut row {
+ rule.id = match previous.and_then(|previous| previous.get(name)) {
+ // NB: The row held these declarations, which no others can have taken the address of.
+ Some(held) if held.declarations.as_ptr() == rule.declarations.as_ptr() => held.id,
+ _ => {
+ self.last_id += 1;
+ PositionTryRuleID(self.last_id)
+ }
+ };
+ }
self.scopes.insert(tree_scope, row);
}
- /// The declarations of the `@position-try` rule of this name that the tree scope `scope` defines.
- fn in_scope(&self, scope: TreeScopeID, name: &[u16]) -> Option<&Arc<DeclarationBlockData>> {
+ /// The `@position-try` rule of this name that the tree scope `scope` defines.
+ fn in_scope(&self, scope: TreeScopeID, name: &[u16]) -> Option<&PositionTryRule> {
self.scopes.get(&scope)?.get(name)
}
}
@@ -318,66 +358,75 @@ impl TacticContext {
/// anchor-size() functions in it changed to maintain the same relative relationship to the new direction.
fn moved_value(self, value: &RetainedStyleValueData, side: Side) -> RetainedStyleValueData {
match value.optional_data().and_then(|data| self.moved_function(data, side)) {
- Some(moved) => RetainedStyleValueData::from_arc(Arc::new(moved)),
+ Some(moved) => RetainedStyleValueData::from_arc(StyleValueArc::new(moved)),
None => value.clone_retained(),
}
}
fn moved_function(self, data: &StyleValueData, side: Side) -> Option<StyleValueData> {
match data {
- StyleValueData::Anchor {
- has_anchor_name,
- anchor_name,
- anchor_side,
- fallback_value,
- } => Some(StyleValueData::Anchor {
- has_anchor_name: *has_anchor_name,
- anchor_name: anchor_name.clone(),
- anchor_side: match anchor_side
- .optional_data()
- .and_then(|data| self.anchor_side(data, side))
- {
- Some(moved) => RetainedStyleValueData::from_arc(Arc::new(moved)),
- None => anchor_side.clone_retained(),
- },
- fallback_value: fallback_value.clone_retained(),
- }),
- StyleValueData::AnchorSize {
- has_anchor_name,
- anchor_name,
- has_anchor_size,
- anchor_size: size,
- fallback_value,
- } if *has_anchor_size && self.mapping.transposes() => Some(StyleValueData::AnchorSize {
- has_anchor_name: *has_anchor_name,
- anchor_name: anchor_name.clone(),
- has_anchor_size: true,
- anchor_size: match *size {
- anchor_size::WIDTH => anchor_size::HEIGHT,
- anchor_size::HEIGHT => anchor_size::WIDTH,
- anchor_size::BLOCK => anchor_size::INLINE,
- anchor_size::INLINE => anchor_size::BLOCK,
- anchor_size::SELF_BLOCK => anchor_size::SELF_INLINE,
- anchor_size::SELF_INLINE => anchor_size::SELF_BLOCK,
- size => size,
- },
- fallback_value: fallback_value.clone_retained(),
- }),
- StyleValueData::Calculated {
- resolve_as_is_number,
- resolve_as_base,
- has_percentages_resolve_as,
- percentages_resolve_as,
- resolve_numbers_as_integers,
- rust_calculation,
- resolved_type,
- accepted_ranges,
- } => {
+ StyleValueData::Anchor(anchor_payload) => {
+ let AnchorPayload {
+ has_anchor_name,
+ anchor_name,
+ anchor_side,
+ fallback_value,
+ } = &**anchor_payload;
+ Some(StyleValueData::Anchor(StyleValueBox::new(AnchorPayload {
+ has_anchor_name: *has_anchor_name,
+ anchor_name: anchor_name.clone(),
+ anchor_side: match anchor_side
+ .optional_data()
+ .and_then(|data| self.anchor_side(data, side))
+ {
+ Some(moved) => RetainedStyleValueData::from_arc(StyleValueArc::new(moved)),
+ None => anchor_side.clone_retained(),
+ },
+ fallback_value: fallback_value.clone_retained(),
+ })))
+ }
+ StyleValueData::AnchorSize(anchor_size_payload)
+ if anchor_size_payload.has_anchor_size && self.mapping.transposes() =>
+ {
+ let AnchorSizePayload {
+ has_anchor_name,
+ anchor_name,
+ anchor_size: size,
+ fallback_value,
+ ..
+ } = &**anchor_size_payload;
+ Some(StyleValueData::AnchorSize(StyleValueBox::new(AnchorSizePayload {
+ has_anchor_name: *has_anchor_name,
+ anchor_name: anchor_name.clone(),
+ has_anchor_size: true,
+ anchor_size: match *size {
+ anchor_size::WIDTH => anchor_size::HEIGHT,
+ anchor_size::HEIGHT => anchor_size::WIDTH,
+ anchor_size::BLOCK => anchor_size::INLINE,
+ anchor_size::INLINE => anchor_size::BLOCK,
+ anchor_size::SELF_BLOCK => anchor_size::SELF_INLINE,
+ anchor_size::SELF_INLINE => anchor_size::SELF_BLOCK,
+ size => size,
+ },
+ fallback_value: fallback_value.clone_retained(),
+ })))
+ }
+ StyleValueData::Calculated(calculated_payload) => {
+ let CalculatedPayload {
+ resolve_as_is_number,
+ resolve_as_base,
+ has_percentages_resolve_as,
+ percentages_resolve_as,
+ resolve_numbers_as_integers,
+ rust_calculation,
+ resolved_type,
+ accepted_ranges,
+ } = &**calculated_payload;
let root = crate::css::calc::map_calc_size_leaves(&rust_calculation.node_arc(), &|leaf| match leaf {
crate::css::calc::CalcNode::NonMathFunction { value, numeric_type } => {
let moved = self.moved_function(value.optional_data()?, side)?;
Some(Arc::new(crate::css::calc::CalcNode::NonMathFunction {
- value: RetainedStyleValueData::from_arc(Arc::new(moved)),
+ value: RetainedStyleValueData::from_arc(StyleValueArc::new(moved)),
numeric_type: *numeric_type,
}))
}
@@ -386,7 +435,7 @@ impl TacticContext {
if Arc::ptr_eq(&root, &rust_calculation.node_arc()) {
return None;
}
- Some(StyleValueData::Calculated {
+ Some(StyleValueData::Calculated(StyleValueBox::new(CalculatedPayload {
resolve_as_is_number: *resolve_as_is_number,
resolve_as_base: *resolve_as_base,
has_percentages_resolve_as: *has_percentages_resolve_as,
@@ -395,7 +444,7 @@ impl TacticContext {
rust_calculation: crate::css::calc::CalcNodeHandle::from_arc(root),
resolved_type: *resolved_type,
accepted_ranges: accepted_ranges.clone(),
- })
+ })))
}
_ => None,
}
@@ -478,7 +527,7 @@ impl TacticContext {
.map(|item| match item.optional_data() {
Some(StyleValueData::Keyword { keyword: code }) if moved_keyword(*code) != *code => {
changed = true;
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Keyword {
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Keyword {
keyword: moved_keyword(*code),
}))
}
@@ -494,7 +543,7 @@ impl TacticContext {
_ => None,
};
match moved {
- Some(moved) => RetainedStyleValueData::from_arc(Arc::new(moved)),
+ Some(moved) => RetainedStyleValueData::from_arc(StyleValueArc::new(moved)),
None => value.clone_retained(),
}
}
@@ -502,15 +551,15 @@ impl TacticContext {
/// https://drafts.csswg.org/css-anchor-position-1/#execute-a-try-tactic
/// Swap the values of `table` between the associated properties corresponding to the directions, and modify the
/// values of the properties as they swap to match the new directions.
- fn execute(self, base: &ComputedLonghandTable, table: &mut ComputedLonghandTable) {
+ fn execute(self, base: &GroupValuesWriter<'_>, table: &mut GroupValuesWriter<'_>) {
let value = |property: u16| base.get(property).map(RetainedStyleValueData::clone_retained);
for side in Side::ALL {
let destination = self.mapping.get(side);
if let Some(inset) = value(side.inset_property()) {
- table.set(destination.inset_property(), self.moved_value(&inset, side), -1);
+ table.set(destination.inset_property(), self.moved_value(&inset, side));
}
if let Some(margin) = value(side.margin_property()) {
- table.set(destination.margin_property(), self.moved_value(&margin, side), -1);
+ table.set(destination.margin_property(), self.moved_value(&margin, side));
}
}
let size_pairs = [
@@ -525,10 +574,10 @@ impl TacticContext {
(horizontal, vertical)
};
if let Some(size) = value(horizontal) {
- table.set(horizontal_destination, self.moved_value(&size, Side::Left), -1);
+ table.set(horizontal_destination, self.moved_value(&size, Side::Left));
}
if let Some(size) = value(vertical) {
- table.set(vertical_destination, self.moved_value(&size, Side::Top), -1);
+ table.set(vertical_destination, self.moved_value(&size, Side::Top));
}
}
// NB: justify-self aligns in the inline axis of the containing block, and align-self in its block axis.
@@ -548,11 +597,11 @@ impl TacticContext {
};
if let Some(justify_self) = value(property_id::JUSTIFY_SELF) {
let moved = self.moved_self_alignment(&justify_self, inline_start, destination_start(justify_destination));
- table.set(justify_destination, moved, -1);
+ table.set(justify_destination, moved);
}
if let Some(align_self) = value(property_id::ALIGN_SELF) {
let moved = self.moved_self_alignment(&align_self, block_start, destination_start(align_destination));
- table.set(align_destination, moved, -1);
+ table.set(align_destination, moved);
}
}
@@ -636,8 +685,13 @@ impl RetainedState {
/// https://drafts.csswg.org/css-anchor-position-1/#position-options-list
/// The first `limit` entries of the `position-try-fallbacks` of the box of `node`, whose record is `record`, that
/// add a position option to its position options list: the index of each, and the identity of the `@position-try`
- /// rule it names, or 0 for an entry that names none.
- pub(crate) fn position_option_entries(&self, node: StyleNodeID, record: u64, limit: usize) -> Vec<(usize, usize)> {
+ /// rule it names, or none for an entry that names none.
+ pub(crate) fn position_option_entries(
+ &self,
+ node: StyleNodeID,
+ record: u64,
+ limit: usize,
+ ) -> Vec<(usize, PositionTryRuleID)> {
let Some(view) = self.computed_group_sets.style_record_view(record) else {
return Vec::new();
};
@@ -651,12 +705,12 @@ impl RetainedState {
.filter_map(|(index, fallback)| {
let name = fallback.name.to_utf16();
if name.is_empty() {
- return Some((index, 0));
+ return Some((index, PositionTryRuleID::NONE));
}
// <dashed-ident>: If there is a @position-try rule with the given name, its associated position
// option is added to the position options list. Otherwise, this value has no effect.
- let declarations = self.resolve_position_try_rule(node, &name)?;
- Some((index, Arc::as_ptr(&declarations) as usize))
+ let rule = self.resolve_position_try_rule(node, &name)?;
+ Some((index, rule.id))
})
.take(limit)
.collect()
@@ -677,20 +731,14 @@ impl RetainedState {
containing_block_direction: u8,
) -> Option<PositionOptionStyle> {
let view = self.computed_group_sets.style_record_view(record)?;
- let base = view.longhand_table?;
+ let base = view.longhands();
// SAFETY: A live record's payloads are live payloads of their groups.
- let (anchor, inherited_box) = unsafe {
- (
- view.payloads[group_index::ANCHOR].cast::<AnchorValues>().deref(),
- view.payloads[group_index::INHERITED_BOX]
- .cast::<InheritedBoxValues>()
- .deref(),
- )
- };
+ let anchor = unsafe { view.payloads[group_index::ANCHOR].cast::<AnchorValues>().deref() };
+ let inherited_bits = view.payloads.inherited_bits();
let fallback = anchor.position_try_fallbacks.as_slice().get(index)?;
let own = WritingModeSides {
- writing_mode: inherited_box.writing_mode,
- direction: inherited_box.direction,
+ writing_mode: inherited_bits.writing_mode(),
+ direction: inherited_bits.direction(),
};
let context = TacticContext {
mapping: SideMapping::of_tactics(
@@ -713,19 +761,8 @@ impl RetainedState {
let declarations = if name.is_empty() {
None
} else {
- Some(self.resolve_position_try_rule(node, &name)?)
+ Some(self.resolve_position_try_rule(node, &name)?.declarations)
};
- let mut table = ComputedLonghandTable::copied_for_partial_drive(base);
- if let Some(declarations) = declarations {
- self.apply_position_try_declarations(node, record, own, &declarations, &mut table)?;
- }
- if context.mapping != SideMapping::IDENTITY {
- let mut transformed = ComputedLonghandTable::copied_for_partial_drive(&table);
- context.execute(&table, &mut transformed);
- table = transformed;
- }
- table.freeze();
-
// NB: The Animation Origin lies above the Position Fallback Origin.
let animated_overlay = self
.computed_group_sets
@@ -733,7 +770,35 @@ impl RetainedState {
.animated_overlay
.cloned();
let mut style = LayoutStyle::from_record(self, record);
- style.replace_groups_from_table(&table, animated_overlay.as_ref(), &POSITION_OPTION_GROUPS);
+ // The option's values are the base styles' values with the option's declarations and
+ // tactics written over them, written over the default groups.
+ crate::css::computed_values::with_default_seed(&self.process_style.default_groups, |seed| {
+ let mut writer = GroupValuesWriter::seeded_for_child(
+ seed,
+ seed,
+ (FIRST_LONGHAND_PROPERTY_ID..=LAST_LONGHAND_PROPERTY_ID)
+ .filter_map(|property| Some((property, base.handle(property)?.clone()))),
+ crate::css::computed_longhand_table::LonghandTableFlags::empty(),
+ 0,
+ );
+ writer.set_effective_zoom(base.effective_zoom());
+ writer.set_effective_color_scheme(base.effective_color_scheme());
+ if let Some(declarations) = declarations {
+ self.apply_position_try_declarations(node, record, own, &declarations, &mut writer)?;
+ }
+ if context.mapping != SideMapping::IDENTITY {
+ let before = writer.clone();
+ context.execute(&before, &mut writer);
+ }
+ for entry in animated_overlay.as_ref().map_or(&[][..], AnimatedOverlay::entries) {
+ if overlay_wins(entry, base.is_important(entry.property)) {
+ writer.set(entry.property, entry.clone_value());
+ }
+ }
+ let (values, ..) = writer.finish(&[]);
+ style.replace_groups_from_values(&values, &POSITION_OPTION_GROUPS, &self.process_style.default_groups);
+ Some(())
+ })?;
// <position-area>: Automatically creates a position option composed solely of a position-area property with
// the given value.
let position_area = if fallback.has_position_area {
@@ -758,19 +823,19 @@ impl RetainedState {
/// https://drafts.csswg.org/css-shadow-1/#tree-scoped-name
/// The declarations of the `@position-try` rule of this name that the element of `node` refers to: the one of the
/// closest tree scope around the element that defines one.
- fn resolve_position_try_rule(&self, node: StyleNodeID, name: &[u16]) -> Option<Arc<DeclarationBlockData>> {
- let mut scope = self.tree.tree_scope(node);
+ fn resolve_position_try_rule(&self, node: StyleNodeID, name: &[u16]) -> Option<PositionTryRule> {
+ let mut scope = self.projection.tree_scope(node);
loop {
- if let Some(declarations) = self.position_try_rules.in_scope(scope, name) {
- return Some(declarations.clone());
+ if let Some(rule) = self.position_try_rules.in_scope(scope, name) {
+ return Some(rule.clone());
}
if scope == TreeScopeID::DOCUMENT {
return None;
}
scope = self
.scope_root(scope)
- .and_then(|root| self.tree.host_of(root))
- .map_or(TreeScopeID::DOCUMENT, |host| self.tree.tree_scope(host));
+ .and_then(|root| self.projection.host_of(root))
+ .map_or(TreeScopeID::DOCUMENT, |host| self.projection.tree_scope(host));
}
}
@@ -784,15 +849,15 @@ impl RetainedState {
node: StyleNodeID,
record: u64,
own: WritingModeSides,
- declarations: &DeclarationBlockData,
- table: &mut ComputedLonghandTable,
+ declarations: &SharedDeclarationBlock,
+ table: &mut GroupValuesWriter<'_>,
) -> Option<()> {
use crate::css::property_metadata::{FIRST_LONGHAND_PROPERTY_ID, LAST_LONGHAND_PROPERTY_ID};
use crate::css::style_compute::{
FfiEffectiveColorSchemeInput, FfiFontMetrics, FfiInputLineHeightMetrics, FfiLengthResolutionContext,
FfiStyleComputationEnvironment, LONGHAND_DRIVE_PHASE_REMAINING, drive_property_computation,
empty_longhand_driver_results, expand_shorthands_with, is_required_driver_input,
- map_logical_alias_to_physical, parent_snapshot_for_style_record,
+ map_logical_alias_to_physical, parent_snapshot_of_view,
};
let mut declared: Vec<(u16, RetainedStyleValueData)> = Vec::new();
@@ -803,8 +868,8 @@ impl RetainedState {
.map_or(std::ptr::null(), |store| Arc::as_ptr(store).cast::<std::ffi::c_void>())
};
let store = custom_property_store(Some(node));
- let inheritance_store = custom_property_store(self.tree.inheritance_parent(node));
- for declaration in &declarations.properties {
+ let inheritance_store = custom_property_store(self.projection.inheritance_parent(node));
+ for declaration in declarations.properties() {
let mut value = RetainedStyleValueData::from_arc(declaration.value.clone());
if matches!(value.optional_data(), Some(StyleValueData::Unresolved { .. })) {
value = self.substitute_keyframe_value(
@@ -832,7 +897,7 @@ impl RetainedState {
StyleValueData::Unresolved { .. }
| StyleValueData::PendingSubstitution { .. }
| StyleValueData::GuaranteedInvalid,
- ) => RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Keyword {
+ ) => RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Keyword {
keyword: keyword::UNSET,
})),
// As with the Animation Origin, revert-layer has no special behavior and acts as specified,
@@ -845,7 +910,7 @@ impl RetainedState {
// NB: No user style sheet sets an accepted @position-try property, so this is unset.
Some(StyleValueData::Keyword {
keyword: keyword::REVERT,
- }) => RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Keyword {
+ }) => RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Keyword {
keyword: keyword::UNSET,
})),
Some(_) => data.clone_retained(),
@@ -854,7 +919,7 @@ impl RetainedState {
declared.push((longhand, data));
});
}
- let base = self.computed_group_sets.style_record_view(record)?.longhand_table?;
+ let base = self.computed_group_sets.style_record_view(record)?.longhands();
declared.retain(|(property, _)| !base.is_important(*property));
if declared.is_empty() {
return Some(());
@@ -862,20 +927,17 @@ impl RetainedState {
let view = self.computed_group_sets.style_record_view(record)?;
let snapshot = self
- .tree
+ .projection
.inheritance_parent(node)
.and_then(|parent| self.computed_group_sets.assigned_style_record(parent))
.and_then(|parent_record| {
let parent_view = self.computed_group_sets.style_record_view(parent_record.raw())?;
- Some(parent_snapshot_for_style_record(
- self,
- parent_record.raw(),
- parent_view.animated_overlay,
- ))
+ Some(parent_snapshot_of_view(parent_view, parent_view.animated_overlay))
});
// SAFETY: A live record's payloads are live payloads of their groups.
let font = unsafe { view.payloads[group_index::FONT].cast::<FontValues>().deref() };
let inputs = &self.document_style_computation_inputs;
+ let first_available = font.first_available_font_metrics();
let font_metric = |value: f32| crate::css::css_pixels::CssPixels::nearest_value_for_f32(value).to_double();
let mut resolved_viewport_relative_length = false;
let mut length = FfiLengthResolutionContext {
@@ -883,11 +945,11 @@ impl RetainedState {
viewport_height: inputs.viewport_height,
font_metrics: FfiFontMetrics {
font_size: font.font_size.to_double(),
- x_height: font_metric(font.font_x_height),
+ x_height: font_metric(first_available.x_height),
// The C++ metrics approximate the cap height with the ascent.
- cap_height: font_metric(font.font_ascent),
- zero_advance: font_metric(font.font_zero_advance),
- line_height: font.line_height_used.to_double(),
+ cap_height: font_metric(first_available.ascent),
+ zero_advance: font_metric(first_available.zero_advance),
+ line_height: font.line_height_used().to_double(),
},
root_font_metrics: FfiFontMetrics {
font_size: inputs.root_font_size,
@@ -912,9 +974,9 @@ impl RetainedState {
self.container_unit_bases(node, false).apply_to(&mut length);
let environment = FfiStyleComputationEnvironment {
box_type_input: self.box_type_transformation_input(
- self.computed_group_sets.adjustment_facts(node),
- crate::css::style_compute::FfiStyleAdjustmentTarget::Element,
- self.tree.inheritance_parent(node),
+ self.projection.adjustment_facts(node),
+ crate::css::style_compute::StyleAdjustmentTarget::Element,
+ self.projection.inheritance_parent(node),
),
color_scheme_input: FfiEffectiveColorSchemeInput {
preferred_color_scheme: 0,
@@ -945,7 +1007,7 @@ impl RetainedState {
if !is_required_driver_input(property) {
continue;
}
- if let Some(value) = base.get(property) {
+ if let Some(value) = base.handle(property) {
store.seed_retained_property(property, value.clone_retained(), false, false);
}
}
@@ -955,34 +1017,49 @@ impl RetainedState {
let index = usize::from(*property - FIRST_LONGHAND_PROPERTY_ID);
selected[index / 64] |= 1 << (index % 64);
}
- let mut driven = view.longhand_table_for_partial_drive();
let mut results = empty_longhand_driver_results();
let mut effective_color_scheme = base.effective_color_scheme();
let input_line_height_metrics = FfiInputLineHeightMetrics {
current_line_height: 0.0,
minimum_line_height: 0.0,
};
- // SAFETY: Every pointer the environment and length context hold stays live across the drive.
- unsafe {
- drive_property_computation(
- &mut driven,
- &store,
- snapshot.as_ref(),
- None,
- &environment,
- Some(&selected),
- LONGHAND_DRIVE_PHASE_REMAINING,
- Some(&length),
- Some(&input_line_height_metrics),
- &mut results,
- &mut effective_color_scheme,
- false,
- );
- }
- for (property, _) in &declared {
- if let Some(value) = driven.get(*property) {
- table.set(*property, value.clone_retained(), -1);
- }
+ // The drive writes over the base values, written over the default groups.
+ let driven: Vec<(u16, RetainedStyleValueData)> =
+ crate::css::computed_values::with_default_seed(&self.process_style.default_groups, |seed| {
+ let mut writer = crate::css::computed_values::GroupValuesWriter::seeded_for_child(
+ seed,
+ seed,
+ (FIRST_LONGHAND_PROPERTY_ID..=LAST_LONGHAND_PROPERTY_ID)
+ .filter_map(|property| Some((property, base.handle(property)?.clone()))),
+ crate::css::computed_longhand_table::LonghandTableFlags::empty(),
+ 0,
+ );
+ writer.set_effective_zoom(base.effective_zoom());
+ writer.set_effective_color_scheme(base.effective_color_scheme());
+ // SAFETY: Every pointer the environment and length context hold stays live across the drive.
+ unsafe {
+ drive_property_computation(
+ &mut writer,
+ &store,
+ snapshot.as_ref(),
+ None,
+ &environment,
+ Some(&selected),
+ LONGHAND_DRIVE_PHASE_REMAINING,
+ Some(&length),
+ Some(&input_line_height_metrics),
+ &mut results,
+ &mut effective_color_scheme,
+ false,
+ );
+ }
+ declared
+ .iter()
+ .filter_map(|(property, _)| Some((*property, writer.get(*property)?.clone())))
+ .collect()
+ });
+ for (property, value) in driven {
+ table.set(property, value);
}
Some(())
}
diff --git a/Libraries/LibWeb/Rust/src/css/style/publication/winner_store.rs b/Libraries/LibWeb/Rust/src/css/style/publication/winner_store.rs
deleted file mode 100644
index f1a96a55317..00000000000
--- a/Libraries/LibWeb/Rust/src/css/style/publication/winner_store.rs
+++ /dev/null
@@ -1,646 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-//! Cached winner locations, with values borrowed from the committed declaration inputs.
-//! Only substituted values need ownership here. A view cannot outlive its input borrow.
-
-use super::*;
-use crate::css::cascaded_properties::{CascadedValues, WinningDeclaration};
-use crate::css::style_compute::{ExternalValueDependencies, external_value_dependencies};
-use crate::css::style_value::{RetainedStyleValueData, StyleValueData};
-use std::sync::atomic::AtomicU32;
-use std::sync::atomic::Ordering;
-
-pub(super) enum WinnerValue {
- Written {
- node: StyleNodeID,
- source: WinnerSource,
- index: usize,
- },
- /// A value substituted from what `source` declared, which keeps the sheet a `url()` in it
- /// resolves against.
- Substituted {
- value: RetainedStyleValueData,
- source: WinnerSource,
- },
-}
-
-pub(super) struct WinnerDeclaration {
- pub(super) property: u16,
- pub(super) important: bool,
- pub(super) value: WinnerValue,
- /// The origin of the winning declaration, or none for a declaration that rolled back past every other one and
- /// leaves the property without a cascaded value.
- pub(super) origin: Option<CascadeOrigin>,
- /// `external_value_dependencies(value)`, memoized, packed into one word with a bit saying
- /// it has been computed. A `Cell` would do on one thread, but a winner store is on the read
- /// side an evaluation step borrows, which has to be `Sync`. The memo is a pure function of
- /// the value, so two workers computing it and storing the same answer is not a race and
- /// relaxed ordering is enough.
- dependencies: AtomicU32,
-}
-
-/// Set on a packed `ExternalValueDependencies` word that has been computed.
-const DEPENDENCIES_COMPUTED: u32 = 1 << 31;
-
-fn pack_dependencies(dependencies: ExternalValueDependencies) -> u32 {
- let ExternalValueDependencies {
- uses_tree_counting_function,
- container_relative_length_unit_mask,
- has_unfixed_random_sharing,
- uses_random_function,
- needs_document_base_url,
- may_need_style_sheet_resource_context,
- inheritance_dependent,
- } = dependencies;
- DEPENDENCIES_COMPUTED
- | u32::from(container_relative_length_unit_mask)
- | (u32::from(uses_tree_counting_function) << 8)
- | (u32::from(has_unfixed_random_sharing) << 9)
- | (u32::from(uses_random_function) << 10)
- | (u32::from(needs_document_base_url) << 11)
- | (u32::from(may_need_style_sheet_resource_context) << 12)
- | (u32::from(inheritance_dependent) << 13)
-}
-
-fn unpack_dependencies(bits: u32) -> ExternalValueDependencies {
- ExternalValueDependencies {
- uses_tree_counting_function: bits & (1 << 8) != 0,
- container_relative_length_unit_mask: (bits & 0xff) as u8,
- has_unfixed_random_sharing: bits & (1 << 9) != 0,
- uses_random_function: bits & (1 << 10) != 0,
- needs_document_base_url: bits & (1 << 11) != 0,
- may_need_style_sheet_resource_context: bits & (1 << 12) != 0,
- inheritance_dependent: bits & (1 << 13) != 0,
- }
-}
-
-impl WinnerDeclaration {
- pub(super) fn new(property: u16, important: bool, value: WinnerValue, origin: Option<CascadeOrigin>) -> Self {
- Self {
- property,
- important,
- value,
- origin,
- dependencies: AtomicU32::new(0),
- }
- }
-}
-
-/// A winner that rolled back below a `revert` or `revert-layer`, as it was declared.
-#[derive(Clone, Copy)]
-pub(super) struct RevertedDeclaration {
- /// The reverting declaration's priority and its index in its block.
- pub(super) position: (CascadePriority, usize),
- pub(super) operator: CascadeOperator,
-}
-
-#[derive(Default)]
-pub(in crate::css::style) struct WinnerStore {
- // NB: Cascade order supplies both source slots and logical/physical tie breaking.
- declarations: Vec<WinnerDeclaration>,
- by_property: Vec<u16>,
- /// Each declaration's priority and index in its block, when known, and the declarations that
- /// reverted, by their index in `declarations`.
- positions: Vec<(CascadePriority, usize)>,
- reverted_declarations: Vec<(usize, RevertedDeclaration)>,
- /// A style query read the sibling position while substituting these declarations.
- pub(super) reads_sibling_position: bool,
-}
-
-impl WinnerStore {
- pub(super) fn new(declarations: Vec<WinnerDeclaration>) -> Self {
- let mut by_property = vec![u16::MAX; crate::css::property_metadata::NUMBER_OF_LONGHAND_PROPERTIES];
- for (index, declaration) in declarations.iter().enumerate() {
- by_property
- [usize::from(declaration.property - crate::css::property_metadata::FIRST_LONGHAND_PROPERTY_ID)] =
- u16::try_from(index).expect("winner count exceeds longhand count");
- }
- Self {
- declarations,
- by_property,
- positions: Vec::new(),
- reverted_declarations: Vec::new(),
- reads_sibling_position: false,
- }
- }
-
- pub(super) fn set_reverted_declarations(
- &mut self,
- positions: Vec<(CascadePriority, usize)>,
- reverted_declarations: Vec<(usize, RevertedDeclaration)>,
- ) {
- debug_assert_eq!(positions.len(), self.declarations.len());
- // NB: The positions only order declarations against a revert, so a store without one keeps none.
- if reverted_declarations.is_empty() {
- return;
- }
- self.positions = positions;
- self.reverted_declarations = reverted_declarations;
- }
-
- fn reverted_declaration(&self, index: usize) -> Option<&RevertedDeclaration> {
- self.reverted_declarations
- .iter()
- .find_map(|(reverted_index, reverted)| (*reverted_index == index).then_some(reverted))
- }
-
- /// https://drafts.csswg.org/css-logical/#box
- /// Whether the declaration at `reverting` reverted past the one at `other`, its counterpart in a
- /// logical property group: declared later than `other`, the revert leaves the group's value as if
- /// `other` were not declared either.
- fn reverts_past_counterpart(&self, reverting: usize, other: usize) -> bool {
- let Some(reverted) = self.reverted_declaration(reverting) else {
- return false;
- };
- if self.reverted_declaration(other).is_some() {
- return false;
- }
- let Some(other_position) = self.positions.get(other) else {
- return false;
- };
- reverted.position > *other_position && reverted.position.0.reverts_past(reverted.operator, &other_position.0)
- }
-
- /// NB: Compare the resolved declarations while retaining context-dependent computation guards.
- pub(super) fn environment_value_delta(&self, other: &Self, engine: &RetainedState) -> Option<SmallVec<[u16; 8]>> {
- if self.reads_sibling_position || other.reads_sibling_position {
- return None;
- }
- if self.declarations.len() != other.declarations.len() {
- return None;
- }
- let mine = self.view(engine);
- let theirs = other.view(engine);
- let mut changed = SmallVec::new();
- for (old, new) in self.declarations.iter().zip(&other.declarations) {
- if old.property != new.property || old.important != new.important {
- return None;
- }
- for dependencies in [mine.dependencies(old), theirs.dependencies(new)] {
- if value_resolves_against_the_element(&dependencies)
- || dependencies.uses_tree_counting_function
- || dependencies.may_need_style_sheet_resource_context
- || dependencies.needs_document_base_url
- {
- return None;
- }
- }
- if mine.value(old) != theirs.value(new) {
- changed.push(old.property);
- }
- }
- Some(changed)
- }
-
- #[cfg(test)]
- fn environment_values_equal(&self, other: &Self, engine: &RetainedState) -> bool {
- self.environment_value_delta(other, engine)
- .is_some_and(|properties| properties.is_empty())
- }
-
- pub(super) fn uses_tree_counting_function(&self, engine: &RetainedState) -> bool {
- let view = self.view(engine);
- self.reads_sibling_position
- || self
- .declarations
- .iter()
- .any(|declaration| view.dependencies(declaration).uses_tree_counting_function)
- }
-
- /// Whether a substitution made a non-inherited longhand `inherit`, which its written value
- /// does not show: the value is then read from the parent's record, not its inherited style.
- pub(super) fn substitutes_inherit_for_non_inherited_property(&self, engine: &RetainedState) -> bool {
- let view = self.view(engine);
- self.declarations.iter().any(|declaration| {
- matches!(declaration.value, WinnerValue::Substituted { .. })
- && declaration.property >= crate::css::property_metadata::FIRST_LONGHAND_PROPERTY_ID
- && !crate::css::property_metadata::property_is_inherited(declaration.property)
- && matches!(view.value(declaration).data(), StyleValueData::Keyword { keyword }
- if *keyword == crate::css::style_compute::keyword::INHERIT)
- })
- }
-
- /// The proof that no value the store holds resolves a `url()`, or `None` when one may.
- pub(super) fn reads_no_resource_contexts(&self, engine: &RetainedState) -> Option<ReadsNoResourceContexts> {
- let view = self.view(engine);
- (!self
- .declarations
- .iter()
- .any(|declaration| view.dependencies(declaration).may_need_style_sheet_resource_context))
- .then_some(ReadsNoResourceContexts(()))
- }
-
- /// What a record computed from the store reads beside its winners.
- pub(super) fn record_reads(&self, engine: &RetainedState) -> StateRecordReads {
- StateRecordReads {
- sibling_position: self.uses_tree_counting_function(engine),
- no_resource_contexts: self.reads_no_resource_contexts(engine),
- }
- }
-
- /// Whether a value the store holds resolves a container-relative length, which the drive
- /// resolves against the element's query containers.
- pub(super) fn reads_container_units(&self, engine: &RetainedState) -> bool {
- let view = self.view(engine);
- self.declarations
- .iter()
- .any(|declaration| view.dependencies(declaration).container_relative_length_unit_mask != 0)
- }
-
- pub(super) fn view<'a>(&'a self, engine: &'a RetainedState) -> WinnerView<'a> {
- WinnerView { store: self, engine }
- }
-
- fn declaration(&self, property: u16) -> Option<(usize, &WinnerDeclaration)> {
- let index = usize::from(*self.by_property.get(usize::from(
- property.checked_sub(crate::css::property_metadata::FIRST_LONGHAND_PROPERTY_ID)?,
- ))?);
- self.declarations.get(index).map(|declaration| (index, declaration))
- }
-}
-
-pub(super) struct WinnerView<'a> {
- store: &'a WinnerStore,
- engine: &'a RetainedState,
-}
-
-pub(super) fn shorthand_longhand_data(property: u16, data: &StyleValueData) -> Option<&RetainedStyleValueData> {
- let StyleValueData::Shorthand {
- sub_properties, values, ..
- } = data
- else {
- return None;
- };
- for (&sub_property, sub_value) in sub_properties.as_slice().iter().zip(values.as_slice()) {
- if sub_property == property {
- return Some(sub_value);
- }
- if let Some(found) = shorthand_longhand_data(property, sub_value.data()) {
- return Some(found);
- }
- }
- None
-}
-
-impl WinnerView<'_> {
- fn value<'a>(&'a self, declaration: &'a WinnerDeclaration) -> &'a RetainedStyleValueData {
- let written = match &declaration.value {
- WinnerValue::Substituted { value, .. } => return value,
- WinnerValue::Written { node, source, index } => match source {
- WinnerSource::Rule(rule) => &self.engine.program.written_values_of(*rule)[*index],
- WinnerSource::Element(kind) => self
- .engine
- .facts
- .element_declarations(*node, *kind)
- .expect("a written winner's declarations are held")
- .written(*index),
- WinnerSource::ExactCascade => unreachable!("a winner recipe requires original spelling"),
- },
- };
- match written.data() {
- data @ StyleValueData::Shorthand { .. } => {
- shorthand_longhand_data(declaration.property, data).expect("validated shorthand winner")
- }
- _ => written,
- }
- }
-}
-
-impl WinnerStore {
- /// The resource context of each declaration, in cascade order, as the drive reads a winner's
- /// source slot. Empty, and no allocation, when no declaration may read one.
- pub(super) fn drive_resource_contexts(
- &self,
- engine: &RetainedState,
- ) -> Vec<crate::css::style_compute::FfiStyleSheetResourceContext> {
- if self.reads_no_resource_contexts(engine).is_some() {
- return Vec::new();
- }
- let view = self.view(engine);
- self.declarations
- .iter()
- .map(|declaration| {
- view.resource_context(declaration).map_or(
- crate::css::style_compute::FfiStyleSheetResourceContext::empty(),
- |context| context.as_drive_context(),
- )
- })
- .collect()
- }
-}
-
-impl WinnerStore {
- /// The random sharings of the declarations' random functions whose random base value is not
- /// fixed, as the drive finds their base values: by pointer.
- fn unfixed_random_sharings(&self, engine: &RetainedState) -> Vec<*const StyleValueData> {
- let view = self.view(engine);
- let mut sharings = Vec::new();
- for declaration in &self.declarations {
- if view.dependencies(declaration).has_unfixed_random_sharing {
- crate::css::style_compute::collect_unfixed_random_sharings_in_value(
- view.value(declaration).data(),
- &mut sharings,
- );
- }
- }
- sharings
- }
-
- /// Draw the random base value of every random function in the declarations that has not got
- /// one yet, for a drive of `node`'s record.
- pub(super) fn draw_random_base_values(&self, engine: &mut RetainedState, node: StyleNodeID) {
- for sharing in self.unfixed_random_sharings(engine) {
- // SAFETY: The declarations retain every value a sharing is part of.
- let (name, element_shared) = crate::css::style_compute::random_caching_key(unsafe { &*sharing });
- engine.ensure_random_base_value(Some(node), name, element_shared);
- }
- }
-
- /// The random base values of the declarations' random functions for a drive of `node`'s
- /// record. Empty, and no allocation, when they hold none; `None` when one was not drawn for
- /// the node.
- pub(super) fn drive_random_base_values(
- &self,
- engine: &RetainedState,
- node: StyleNodeID,
- ) -> Option<Vec<crate::css::style_compute::FfiRandomBaseValue>> {
- self.unfixed_random_sharings(engine)
- .into_iter()
- .map(|sharing| {
- // SAFETY: The declarations retain every value a sharing is part of.
- let (name, element_shared) = crate::css::style_compute::random_caching_key(unsafe { &*sharing });
- Some(crate::css::style_compute::FfiRandomBaseValue {
- source: sharing.cast(),
- value: engine.random_base_values.get(node, name, element_shared)?,
- })
- })
- .collect()
- }
-}
-
-impl<'a> WinnerView<'a> {
- fn dependencies(&self, declaration: &WinnerDeclaration) -> ExternalValueDependencies {
- let memoized = declaration.dependencies.load(Ordering::Relaxed);
- if memoized & DEPENDENCIES_COMPUTED != 0 {
- return unpack_dependencies(memoized);
- }
- let dependencies = external_value_dependencies(self.value(declaration).data());
- declaration
- .dependencies
- .store(pack_dependencies(dependencies), Ordering::Relaxed);
- dependencies
- }
-
- /// The resource context of the sheet a rule declaration came from, written or substituted. An
- /// element's own declarations resolve against the document's base URL, as they do in the
- /// host's cascade.
- fn resource_context(
- &self,
- declaration: &WinnerDeclaration,
- ) -> Option<&'a super::resource_contexts::StyleSheetResourceContext> {
- let (WinnerValue::Written {
- source: WinnerSource::Rule(rule),
- ..
- }
- | WinnerValue::Substituted {
- source: WinnerSource::Rule(rule),
- ..
- }) = declaration.value
- else {
- return None;
- };
- let engine: &'a RetainedState = self.engine;
- engine
- .document_resource_contexts
- .for_source(engine.rule_source_identity(rule)?)
- }
-}
-
-impl CascadedValues for WinnerView<'_> {
- fn winning_declaration(&self, property: u16) -> Option<WinningDeclaration<'_>> {
- let (index, declaration) = self.store.declaration(property)?;
- Some((
- self.value(declaration),
- declaration.important,
- u32::try_from(index).unwrap(),
- self.resource_context(declaration).is_some(),
- self.dependencies(declaration),
- ))
- }
-
- fn winning_origin(&self, property: u16) -> Option<CascadeOrigin> {
- self.store.declaration(property)?.1.origin
- }
-
- fn property_with_higher_priority(&self, first: u16, second: u16) -> u16 {
- match (self.store.declaration(first), self.store.declaration(second)) {
- (Some((first_index, _)), Some((second_index, _)))
- if self.store.reverts_past_counterpart(first_index, second_index) =>
- {
- first
- }
- (Some((first_index, _)), Some((second_index, _)))
- if self.store.reverts_past_counterpart(second_index, first_index) =>
- {
- second
- }
- (Some((first_index, _)), Some((second_index, _))) if first_index >= second_index => first,
- (Some(_), None) => first,
- _ => second,
- }
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::css::property_metadata::property_id;
- use std::sync::Arc;
-
- fn length_store(value: f64, unit: &str) -> WinnerStore {
- let unit = u8::try_from(
- crate::css::style_compute::LENGTH_UNIT_NAMES
- .iter()
- .position(|&name| name == unit)
- .unwrap(),
- )
- .unwrap();
- WinnerStore::new(vec![WinnerDeclaration::new(
- property_id::WIDTH,
- false,
- WinnerValue::Substituted {
- value: RetainedStyleValueData::from_owned(StyleValueData::Length { value, unit }),
- source: WinnerSource::Element(ElementDeclarationKind::InlineStyle),
- },
- Some(CascadeOrigin::Author),
- )])
- }
-
- #[test]
- fn environment_value_comparison_checks_resolved_values() {
- let engine = StyleEngine::new();
- let first = length_store(10.0, "px");
- let equal = length_store(10.0, "px");
- let changed = length_store(20.0, "px");
- assert!(first.environment_values_equal(&equal, &engine.retained));
- assert!(equal.environment_values_equal(&first, &engine.retained));
- assert!(!first.environment_values_equal(&changed, &engine.retained));
- assert_eq!(
- first.environment_value_delta(&changed, &engine.retained).as_deref(),
- Some([property_id::WIDTH].as_slice())
- );
- assert!(!first.environment_values_equal(&WinnerStore::new(Vec::new()), &engine.retained));
- }
-
- #[test]
- fn environment_value_comparison_leaves_font_context_to_driver_checks() {
- let engine = StyleEngine::new();
- assert!(length_store(1.0, "em").environment_values_equal(&length_store(1.0, "em"), &engine.retained));
- }
-
- #[test]
- fn environment_value_comparison_rejects_container_relative_values() {
- let engine = StyleEngine::new();
- assert!(!length_store(1.0, "cqw").environment_values_equal(&length_store(1.0, "cqw"), &engine.retained));
- }
-
- #[test]
- fn environment_value_comparison_only_reuses_urls_without_resource_dependencies() {
- use crate::css::style_value::{ImageResourceContext, RetainedRequestUrlModifierList, RetainedString};
-
- let store = |property, value| {
- WinnerStore::new(vec![WinnerDeclaration::new(
- property,
- false,
- WinnerValue::Substituted {
- value: RetainedStyleValueData::from_owned(value),
- source: WinnerSource::Element(ElementDeclarationKind::InlineStyle),
- },
- Some(CascadeOrigin::Author),
- )])
- };
- let engine = StyleEngine::new();
- for (url, can_reuse) in [
- ("https://example.com/paint.svg#fill", true),
- ("data:image/svg+xml,paint", true),
- ("paint.svg#fill", false),
- ("/paint.svg#fill", false),
- ("//example.com/paint.svg#fill", false),
- ] {
- let url_value = || StyleValueData::Url {
- url: RetainedString::from_ascii(url.to_owned()),
- url_type: 0,
- modifiers: RetainedRequestUrlModifierList::from_retained_modifiers(Vec::new()),
- };
- let first = store(property_id::FILL, url_value());
- let equal = store(property_id::FILL, url_value());
- assert_eq!(
- first.environment_values_equal(&equal, &engine.retained),
- can_reuse,
- "{url}"
- );
- assert_eq!(
- first.reads_no_resource_contexts(&engine.retained).is_some(),
- can_reuse,
- "{url}"
- );
- }
-
- let image_value = |base_url: &str, origin_clean| StyleValueData::Image {
- url: RetainedString::from_ascii("https://example.com/image.png".to_owned()),
- url_type: 0,
- url_modifiers: RetainedRequestUrlModifierList::from_retained_modifiers(Vec::new()),
- resource_context: ImageResourceContext {
- base_url: RetainedString::from_ascii(base_url.to_owned()),
- has_base_url: true,
- has_parent_style_sheet_origin_clean: true,
- parent_style_sheet_origin_clean: origin_clean,
- should_absolutize_url_for_computed_value: true,
- },
- };
- let first = store(
- property_id::BACKGROUND_IMAGE,
- image_value("https://example.com/first.css", true),
- );
- let equal = store(
- property_id::BACKGROUND_IMAGE,
- image_value("https://example.com/second.css", false),
- );
- assert!(!first.environment_values_equal(&equal, &engine.retained));
- assert!(first.reads_no_resource_contexts(&engine.retained).is_none());
- }
-
- #[test]
- fn winner_view_borrows_written_spelling_and_preserves_cascade_order() {
- let mut engine = StyleEngine::new();
- let node = StyleNodeID::element(1);
- let kind = ElementDeclarationKind::InlineStyle;
- let properties = [property_id::MARGIN_LEFT, property_id::MARGIN_INLINE_START];
- let written = [1.25, 2.5].map(|value| RetainedStyleValueData::from_owned(StyleValueData::Number { value }));
- let mut owned = CascadedPropertyStore::new();
- for (&property, value) in properties.iter().zip(&written) {
- owned.seed_retained_property(property, value.clone_retained(), true, false);
- }
- let observer = written[0].clone_retained().into_arc();
- engine.facts.set_element_declared_properties(
- node,
- kind,
- properties
- .iter()
- .map(|&property| DeclaredProperty {
- property,
- important: true,
- operator: CascadeOperator::Declared,
- // NB: The identity does not supply the written value to the drive.
- value: SpecifiedValueID(1),
- })
- .zip(written)
- .collect(),
- );
- let owners = Arc::strong_count(&observer);
- let store = WinnerStore::new(
- properties
- .iter()
- .enumerate()
- .map(|(index, &property)| {
- WinnerDeclaration::new(
- property,
- true,
- WinnerValue::Written {
- node,
- source: WinnerSource::Element(kind),
- index,
- },
- Some(CascadeOrigin::Author),
- )
- })
- .collect(),
- );
- let view = store.view(&engine);
- for property in properties {
- let actual = view.winning_declaration(property).unwrap();
- let expected = owned.winning_declaration(property).unwrap();
- assert_eq!(
- (actual.0.pointer(), actual.1, actual.2, actual.3),
- (expected.0.pointer(), expected.1, expected.2, expected.3)
- );
- assert!(matches!(view.winning_origin(property), Some(CascadeOrigin::Author)));
- }
- assert_eq!(
- view.property_with_higher_priority(properties[0], properties[1]),
- properties[1]
- );
- assert_eq!(
- view.property_with_higher_priority(properties[1], properties[0]),
- properties[1]
- );
- assert!(view.winning_declaration(property_id::OPACITY).is_none());
- assert_eq!(Arc::strong_count(&observer), owners);
- drop(store);
- assert_eq!(Arc::strong_count(&observer), owners);
- }
-}
diff --git a/Libraries/LibWeb/Rust/src/css/style/random_bases.rs b/Libraries/LibWeb/Rust/src/css/style/random_bases.rs
index a65de8acd05..f75fa1c0cb4 100644
--- a/Libraries/LibWeb/Rust/src/css/style/random_bases.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/random_bases.rs
@@ -19,11 +19,11 @@ use std::sync::{Arc, Mutex};
/// sharing.
#[derive(Clone, Default)]
pub(crate) struct RandomBaseValues {
- /// The keys whose element is null, by name.
- document: HashMap<Box<[u16]>, f64>,
+ /// The keys whose element is null, by name, shared with a fork until either side writes it.
+ document: crate::fork::ForkShared<HashMap<Box<[u16]>, f64>>,
/// The keys that name an element. Few elements draw, and those draw few names, so only they
- /// have a row and a row is searched in order.
- elements: HashMap<StyleNodeID, Vec<NamedBaseValue>>,
+ /// have a row and a row is searched in order. Shared with a fork until either side writes it.
+ elements: crate::fork::ForkShared<HashMap<StyleNodeID, Vec<NamedBaseValue>>>,
/// Raised once any element has a row, and never lowered. The host watches it so that an element losing its
/// identity asks for keys only once some element can have any.
element_rows_exist: Arc<AtomicBool>,
@@ -97,6 +97,9 @@ impl RandomBaseValues {
/// Takes the keys that name an element, with their values, as the element loses its identity.
pub(crate) fn take_element_values(&mut self, node: StyleNodeID) -> Vec<NamedBaseValue> {
+ if !self.elements.contains_key(&node) {
+ return Vec::new();
+ }
self.elements.remove(&node).unwrap_or_default()
}
@@ -104,11 +107,33 @@ impl RandomBaseValues {
/// element, which must not see this one's values; the element itself took its own along when
/// it lost the identity.
pub(crate) fn retire(&mut self, node: StyleNodeID) {
- self.elements.remove(&node);
+ if self.elements.contains_key(&node) {
+ self.elements.remove(&node);
+ }
}
}
+/// A random caching key a style computation of `node` needs the base value of, which has not
+/// been drawn. A pass draws none itself: the key is drawn between passes, as a font is resolved,
+/// and the element is styled again.
+pub(crate) struct RandomBaseRequest {
+ pub(crate) node: StyleNodeID,
+ pub(crate) name: Box<[u16]>,
+ pub(crate) element_shared: bool,
+}
+
impl RetainedState {
+ /// Draw the base value of the random caching key `request` names.
+ pub(crate) fn draw_random_base_value(&mut self, request: RandomBaseRequest) {
+ self.random_base_values
+ .ensure(Some(request.node), &request.name, request.element_shared);
+ }
+
+ /// The base value of a random caching key, if it has been drawn.
+ pub(crate) fn drawn_random_base_value(&self, node: StyleNodeID, name: &[u16], element_shared: bool) -> Option<f64> {
+ self.random_base_values.get(node, name, element_shared)
+ }
+
/// Give an element's new style node the keys the element kept while it had none.
pub(crate) fn set_element_random_base_values(&mut self, node: StyleNodeID, row: Vec<NamedBaseValue>) {
if !row.is_empty() {
@@ -122,11 +147,8 @@ impl RetainedState {
let exist = self.random_base_values.element_rows_exist.load(Ordering::Relaxed);
self.random_base_values.element_rows_exist = Arc::new(AtomicBool::new(exist));
self.detach_container_effects_held_for_fork();
- // The prefix caches hold the answers of the engine's own match answer catalog, which the fork copies as either
- // writes it: the fork starts with caches of its own.
- self.prefix_caches = Default::default();
if let Some(font_resolution) = self.font_resolution.as_mut() {
- font_resolution.start_over_for_fork();
+ font_resolution.hold_cascades_for_fork();
}
}
diff --git a/Libraries/LibWeb/Rust/src/css/style/resource_contexts.rs b/Libraries/LibWeb/Rust/src/css/style/resource_contexts.rs
index 85595eb917e..d524fe4a90f 100644
--- a/Libraries/LibWeb/Rust/src/css/style/resource_contexts.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/resource_contexts.rs
@@ -6,7 +6,7 @@
//! What a `url()` resolves against: the document's base URL, and the resource context of the style
//! sheet a rule came from, keyed by the native sheet's identity (an imported sheet's own, not its
-//! importer's). The host lends them at each style transaction boundary; the engine keeps a copy.
+//! importer's). The host lends them at each style update boundary; the engine keeps a copy.
use super::fast_hash::FastMap as HashMap;
@@ -24,6 +24,8 @@ pub(crate) struct StyleSheetResourceContext {
pub(crate) struct DocumentResourceContexts {
pub(crate) document_base_url: Box<[u8]>,
by_source: HashMap<u64, StyleSheetResourceContext>,
+ /// Which collection of the contexts the host last lent, which `by_source` holds.
+ version: u64,
}
impl DocumentResourceContexts {
@@ -68,6 +70,11 @@ impl DocumentResourceContexts {
if *self.document_base_url != *document_base_url {
self.document_base_url = document_base_url.into();
}
+ if std::mem::replace(&mut self.version, inputs.style_sheet_resource_contexts_version)
+ == inputs.style_sheet_resource_contexts_version
+ {
+ return;
+ }
let held = |entry: &FfiStyleSheetResourceContextEntry| {
self.by_source.get(&entry.source_identity).is_some_and(|context| {
*context.base_url == *lent(entry.base_url, entry.base_url_length)
@@ -136,6 +143,7 @@ mod tests {
document_base_url_length: document_base_url.len(),
style_sheet_resource_contexts: FfiHostHandle::from_pointer(entries.as_ptr().cast()),
style_sheet_resource_context_count: entries.len(),
+ style_sheet_resource_contexts_version: contexts.version + 1,
..Default::default()
};
unsafe { contexts.take_in(&mut inputs) };
diff --git a/Libraries/LibWeb/Rust/src/css/style/specified_value.rs b/Libraries/LibWeb/Rust/src/css/style/specified_value.rs
index a2e3a3fe589..121fca2e8fc 100644
--- a/Libraries/LibWeb/Rust/src/css/style/specified_value.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/specified_value.rs
@@ -4,114 +4,139 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! Canonical specified-value identities retained as a dense table.
+//! The canonical values of elements' own declarations, and the entries those declarations take.
+use crate::css::declaration_block;
+use crate::css::declaration_block::DeclarationEntry;
use crate::css::style_value::RetainedStyleValueData;
use crate::css::style_value::StyleValueData;
-use std::sync::Arc;
+use crate::css::style_value_arc::StyleValueArc;
-use super::cascade::SpecifiedValueID;
-use super::fast_hash::FastMap as HashMap;
+use super::RetainedState;
+use super::instrumentation::Counter;
-#[derive(Clone)]
-
-struct SpecifiedValueEntry {
- id: SpecifiedValueID,
- value: RetainedStyleValueData,
-}
+define_id! { struct CanonicalValueIndex(); }
-define_id! { struct SpecifiedValueEntryIndex(); }
-
-impl super::intern_table::InternIdentity for SpecifiedValueEntryIndex {
+impl super::intern_table::InternIdentity for CanonicalValueIndex {
fn index(self) -> usize {
self.0 as usize
}
+
+ fn from_index(index: usize) -> Self {
+ Self(u32::try_from(index).expect("canonical value set exceeds u32 indexing"))
+ }
}
-/// An identity is never reused, so rule and winner rows can compare their opaque identities.
+/// How many values the set holds before its first sweep.
+const MINIMUM_SWEEP_THRESHOLD: usize = 1024;
+
+/// The values elements' own declarations were written with, one per content, so that elements
+/// declaring equal values share one, which the caches over computed values key by. A value the set
+/// alone holds is no element's any more, and a sweep drops it.
#[derive(Clone)]
-pub(super) struct SpecifiedValues {
- entries: super::intern_table::InternTable<SpecifiedValueEntryIndex, SpecifiedValueEntry>,
- entries_by_pointer: HashMap<usize, SpecifiedValueID>,
- entries_by_id: HashMap<SpecifiedValueID, u32>,
- next_id: u64,
+pub(super) struct CanonicalValues {
+ entries: super::intern_table::InternTable<CanonicalValueIndex, RetainedStyleValueData>,
+ /// How many values the set holds before it sweeps the ones only it holds: twice as many as the
+ /// last sweep kept, so sweeping costs a constant per value entered.
+ sweep_threshold: usize,
}
-impl SpecifiedValues {
- pub(super) fn new() -> Self {
+impl Default for CanonicalValues {
+ fn default() -> Self {
Self {
entries: super::intern_table::InternTable::default(),
- entries_by_pointer: HashMap::default(),
- entries_by_id: HashMap::default(),
- next_id: 1,
+ sweep_threshold: MINIMUM_SWEEP_THRESHOLD,
}
}
+}
- #[must_use]
- fn lookup(&self, value: &StyleValueData) -> Option<SpecifiedValueID> {
- if let Some(id) = self.entries_by_pointer.get(&(std::ptr::from_ref(value) as usize)) {
- return Some(*id);
- }
- // Equal URL text can refer to different resources in different declarations. The native
- // image keeps its stylesheet context outside StyleValueData, so only an existing pointer
- // identity can prove equality for values containing resource-dependent images.
- if !crate::css::style_compute::value_may_need_style_sheet_resource_context(value)
- && let Some(index) = self
- .entries
- .find(value.content_hash(), |_index, entry| entry.value.data() == value)
- {
- return Some(self.entries[index].id);
- }
- None
+impl CanonicalValues {
+ /// The bytes of the set and its index, with the values it holds counted aside.
+ pub(super) fn heap_size(&self, sizer: &mut crate::heap_size::HeapSizer) -> usize {
+ use crate::heap_size::HeapSize;
+ self.entries.heap_size(sizer, |value, sizer| value.heap_size(sizer))
}
- /// Return the retained payload behind one maintained declaration identity.
- #[must_use]
- pub(super) fn value(&self, id: SpecifiedValueID) -> Option<&StyleValueData> {
- let index = self.entries_by_id.get(&id)?;
- Some(self.entries[*index as usize].value.data())
+ /// Whether the set grew enough since its last sweep to sweep it again.
+ pub(super) fn should_sweep(&self) -> bool {
+ self.entries.len() >= self.sweep_threshold
}
- /// Return an owned reference to one maintained declaration payload.
- #[must_use]
- #[cfg(test)]
- pub(super) fn retained_value(&self, id: SpecifiedValueID) -> Option<RetainedStyleValueData> {
- let index = self.entries_by_id.get(&id)?;
- Some(self.entries[*index as usize].value.clone_retained())
+ /// Drop the values only the set holds, which no element declares any more.
+ ///
+ /// NB: A fork's copy of the set holds a second reference to each of its values, so a sweep
+ /// while a fork lives keeps them all.
+ pub(super) fn sweep(&mut self) {
+ self.entries.retain(|value| !value.is_unique());
+ self.sweep_threshold = (self.entries.len() * 2).max(MINIMUM_SWEEP_THRESHOLD);
}
- /// The identity of `value`, and whether it already had one.
- pub(super) fn intern(&mut self, value: &Arc<StyleValueData>) -> (SpecifiedValueID, bool) {
- if let Some(id) = self.lookup(value) {
- return (id, true);
+ /// The value equal to `value` elements share, entering `value` as that one where none is, and
+ /// whether one was. A value whose content cannot name it, as an image's resource context is
+ /// not part of its content, is its own.
+ fn canonical(&mut self, value: &StyleValueArc) -> (RetainedStyleValueData, bool) {
+ if crate::css::style_compute::value_may_need_style_sheet_resource_context(value) {
+ return (RetainedStyleValueData::from_arc(value.clone()), false);
+ }
+ let content_hash = value.content_hash();
+ let data: &StyleValueData = value;
+ if let Some(index) = self.entries.find(content_hash, |_index, entry| entry.data() == data) {
+ return (self.entries.get(index).clone(), true);
}
- let id = SpecifiedValueID(self.next_id);
- self.next_id = self
- .next_id
- .checked_add(1)
- .expect("specified value identity space exhausted");
- self.push_entry(id, RetainedStyleValueData::from_arc(Arc::clone(value)));
- (id, false)
+ let index =
+ CanonicalValueIndex(u32::try_from(self.entries.len()).expect("canonical value set exceeds u32 indexing"));
+ let canonical = RetainedStyleValueData::from_arc(value.clone());
+ self.entries.insert(content_hash, index, canonical.clone());
+ (canonical, false)
}
+}
- /// Associate another immutable spelling with an existing canonical identity.
- pub(super) fn alias(&mut self, value: &Arc<StyleValueData>, id: SpecifiedValueID) {
- if let Some(existing) = self.lookup(value) {
- debug_assert_eq!(existing, id);
- return;
+/// The entries of the longhands `declarations` declare, each with the value an element declaring
+/// it is written with, a shorthand's longhands taking its value.
+pub(crate) fn element_declared_properties<'a>(
+ declarations: impl ExactSizeIterator<Item = declaration_block::DeclarationRef<'a>>,
+) -> Vec<(DeclarationEntry, RetainedStyleValueData)> {
+ fn append(
+ property: u16,
+ declaration: declaration_block::DeclarationRef<'_>,
+ declarations: &mut Vec<(DeclarationEntry, RetainedStyleValueData)>,
+ ) {
+ use crate::css::property_metadata::{longhands_for_shorthand, property_is_shorthand};
+ // Element declarations decide longhands. Presentation attributes can name shorthands
+ // whose children are themselves shorthands, so expand the complete property inventory.
+ // The longhands of a shorthand awaiting substitution have declarations of their own, which
+ // a later change to the block may have replaced or removed.
+ if property_is_shorthand(property)
+ && !matches!(
+ &**declaration.value,
+ StyleValueData::Unresolved { .. } | StyleValueData::PendingSubstitution { .. }
+ )
+ {
+ for &longhand in longhands_for_shorthand(property) {
+ append(longhand, declaration, declarations);
+ }
+ } else {
+ declarations.push((
+ DeclarationEntry::new(property, declaration.important, declaration.operator),
+ RetainedStyleValueData::from_arc(declaration.value.clone()),
+ ));
}
- self.push_entry(id, RetainedStyleValueData::from_arc(Arc::clone(value)));
}
+ let mut entries = Vec::with_capacity(declarations.len());
+ for declaration in declarations {
+ append(declaration.property_id, declaration, &mut entries);
+ }
+ entries
+}
- fn push_entry(&mut self, id: SpecifiedValueID, value: RetainedStyleValueData) {
- let pointer = value.pointer() as usize;
- let index = SpecifiedValueEntryIndex(
- u32::try_from(self.entries.len()).expect("specified value table exceeds u32 indexing"),
- );
- self.entries
- .insert(value.data().content_hash(), index, SpecifiedValueEntry { id, value });
- self.entries_by_pointer.insert(pointer, id);
- self.entries_by_id.entry(id).or_insert(index.0);
+impl RetainedState {
+ /// The value equal to `value` the elements of the document share.
+ pub(super) fn canonical_value(&mut self, value: &StyleValueArc) -> RetainedStyleValueData {
+ let (canonical, reused) = self.canonical_values.canonical(value);
+ if reused {
+ self.counters.bump(Counter::SpecifiedValuesReused);
+ }
+ canonical
}
}
@@ -121,36 +146,36 @@ mod tests {
use super::*;
#[test]
- fn equal_content_dedups_across_distinct_spellings() {
- let mut values = SpecifiedValues::new();
+ fn equal_content_shares_one_value() {
+ let mut values = CanonicalValues::default();
let originals: Vec<_> = (0..64)
- .map(|i| std::sync::Arc::new(StyleValueData::Number { value: f64::from(i) }))
+ .map(|i| StyleValueArc::new(StyleValueData::Number { value: f64::from(i) }))
.collect();
- let ids: Vec<_> = originals.iter().map(|value| values.intern(value).0).collect();
- for (left, right) in ids.iter().zip(ids.iter().skip(1)) {
- assert_ne!(left, right);
- }
+ let canonical: Vec<_> = originals.iter().map(|value| values.canonical(value).0).collect();
let respellings: Vec<_> = (0..64)
- .map(|i| std::sync::Arc::new(StyleValueData::Number { value: f64::from(i) }))
+ .map(|i| StyleValueArc::new(StyleValueData::Number { value: f64::from(i) }))
.collect();
- for (respelling, id) in respellings.iter().zip(ids.iter()) {
- let (reused, _) = values.intern(respelling);
- assert_eq!(reused, *id);
+ for (respelling, canonical) in respellings.iter().zip(&canonical) {
+ let (shared, reused) = values.canonical(respelling);
+ assert!(reused);
+ assert_eq!(shared.pointer(), canonical.pointer());
}
}
#[test]
- fn authored_spellings_can_alias_a_canonical_identity() {
- let mut values = SpecifiedValues::new();
- let canonical = std::sync::Arc::new(StyleValueData::Number { value: 42.0 });
- let authored = std::sync::Arc::new(StyleValueData::Number { value: 43.0 });
-
- let (canonical_id, _) = values.intern(&canonical);
- values.alias(&authored, canonical_id);
- assert_eq!(values.entries_by_pointer.len(), 2);
- assert_eq!(values.lookup(&authored), Some(canonical_id));
- let (authored_id, reused) = values.intern(&authored);
- assert_eq!(authored_id, canonical_id);
- assert!(reused);
+ fn a_sweep_drops_the_values_only_the_set_holds() {
+ let mut values = CanonicalValues::default();
+ let kept = values
+ .canonical(&StyleValueArc::new(StyleValueData::Number { value: 1.0 }))
+ .0;
+ drop(values.canonical(&StyleValueArc::new(StyleValueData::Number { value: 2.0 })));
+ values.sweep();
+ assert_eq!(values.entries.len(), 1);
+ assert!(
+ values
+ .canonical(&StyleValueArc::new(StyleValueData::Number { value: 1.0 }))
+ .1
+ );
+ drop(kept);
}
}
diff --git a/Libraries/LibWeb/Rust/src/css/table_group_builder.rs b/Libraries/LibWeb/Rust/src/css/table_group_builder.rs
index 023450efd6d..e701d924bc2 100644
--- a/Libraries/LibWeb/Rust/src/css/table_group_builder.rs
+++ b/Libraries/LibWeb/Rust/src/css/table_group_builder.rs
@@ -269,6 +269,38 @@ pub(crate) fn group_holds_current_color_for_its_reader(property: u16, data: Opti
) && matches!(data, Some(StyleValueData::Keyword { keyword }) if *keyword == keyword::CURRENTCOLOR)
}
+/// The groups an element's color reaches through the colors it inherits, which it holds no record of having
+/// declared: a color reading `currentcolor` that is more than plain `currentcolor` resolves against the color of the
+/// element holding it, not the parent's. The other inherited groups hold the color itself, and rebuild with it.
+pub(crate) fn groups_reading_current_color_through_inherited_values<'a>(
+ value: impl Fn(u16) -> Option<&'a StyleValueData>,
+) -> u32 {
+ let reads_current_color = |property: u16| {
+ value(property).is_some_and(|data| {
+ crate::css::style_value::value_depends_on_current_color(data)
+ && !group_holds_current_color_for_its_reader(property, Some(data))
+ })
+ };
+ let mut groups = 0;
+ if [
+ property_id::CARET_COLOR,
+ property_id::ACCENT_COLOR,
+ property_id::SCROLLBAR_COLOR,
+ ]
+ .into_iter()
+ .any(reads_current_color)
+ {
+ groups |= 1 << group_index::INHERITED_UI;
+ }
+ if [property_id::FILL, property_id::STROKE]
+ .into_iter()
+ .any(reads_current_color)
+ {
+ groups |= 1 << group_index::INHERITED_SVG;
+ }
+ groups
+}
+
/// The computed color `data` is, as a group holds it: `currentcolor` stays for the group's reader
/// to resolve against the element's color.
fn style_color(data: &StyleValueData, input: &ColorResolutionInput) -> Option<StyleColor> {
diff --git a/Tests/LibWeb/Ref/expected/css/fill-inherited-mix-reads-animated-color-ref.html b/Tests/LibWeb/Ref/expected/css/fill-inherited-mix-reads-animated-color-ref.html
new file mode 100644
index 00000000000..b7552c6d287
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/css/fill-inherited-mix-reads-animated-color-ref.html
@@ -0,0 +1,2 @@
+<!DOCTYPE html>
+<svg width="100" height="100"><rect width="100" height="100" style="fill: color-mix(in srgb, rgb(0, 200, 0) 50%, white)"></rect></svg>
diff --git a/Tests/LibWeb/Ref/expected/css/scrollbar-color-inherited-mix-reads-own-color-ref.html b/Tests/LibWeb/Ref/expected/css/scrollbar-color-inherited-mix-reads-own-color-ref.html
new file mode 100644
index 00000000000..4c9925593d7
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/css/scrollbar-color-inherited-mix-reads-own-color-ref.html
@@ -0,0 +1,9 @@
+<!DOCTYPE html>
+<style>
+ .scroller { width: 100px; height: 100px; overflow: scroll; scrollbar-gutter: stable; cursor: pointer; }
+ .scroller > div { width: 300px; height: 300px; }
+ #first { color: rgb(200, 0, 0); scrollbar-color: color-mix(in srgb, rgb(200, 0, 0) 50%, #0000) #0000; }
+ #second { color: rgb(0, 200, 0); scrollbar-color: color-mix(in srgb, rgb(0, 200, 0) 50%, #0000) #0000; }
+</style>
+<div class="scroller" id="first"><div></div></div>
+<div class="scroller" id="second"><div></div></div>
diff --git a/Tests/LibWeb/Ref/input/css/fill-inherited-mix-reads-animated-color.html b/Tests/LibWeb/Ref/input/css/fill-inherited-mix-reads-animated-color.html
new file mode 100644
index 00000000000..acdbe0c2ca6
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/css/fill-inherited-mix-reads-animated-color.html
@@ -0,0 +1,8 @@
+<!DOCTYPE html>
+<link rel="match" href="../../expected/css/fill-inherited-mix-reads-animated-color-ref.html" />
+<style>
+ :root { fill: color-mix(in srgb, currentColor 50%, white); }
+ @keyframes paint { from, to { color: rgb(0, 200, 0); } }
+ rect { color: rgb(200, 0, 0); animation: paint 100s paused; }
+</style>
+<svg width="100" height="100"><rect width="100" height="100"></rect></svg>
diff --git a/Tests/LibWeb/Ref/input/css/scrollbar-color-inherited-mix-reads-own-color.html b/Tests/LibWeb/Ref/input/css/scrollbar-color-inherited-mix-reads-own-color.html
new file mode 100644
index 00000000000..874623e6f72
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/css/scrollbar-color-inherited-mix-reads-own-color.html
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<link rel="match" href="../../expected/css/scrollbar-color-inherited-mix-reads-own-color-ref.html" />
+<style>
+ :root { scrollbar-color: color-mix(in srgb, currentColor 50%, #0000) #0000; }
+ .scroller { width: 100px; height: 100px; overflow: scroll; scrollbar-gutter: stable; cursor: pointer; }
+ .scroller > div { width: 300px; height: 300px; }
+ #first { color: rgb(200, 0, 0); }
+ #second { color: rgb(0, 200, 0); }
+</style>
+<div class="scroller" id="first"><div></div></div>
+<div class="scroller" id="second"><div></div></div>
diff --git a/Tests/LibWeb/Text/expected/css/custom-property-not-inherited-below-pseudo-element-sharing-its-value.txt b/Tests/LibWeb/Text/expected/css/custom-property-not-inherited-below-pseudo-element-sharing-its-value.txt
new file mode 100644
index 00000000000..06ae3ce458b
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/custom-property-not-inherited-below-pseudo-element-sharing-its-value.txt
@@ -0,0 +1 @@
+--not-inherited of the child: start
diff --git a/Tests/LibWeb/Text/expected/css/custom-property-substitution-serialization-retokenizes.txt b/Tests/LibWeb/Text/expected/css/custom-property-substitution-serialization-retokenizes.txt
new file mode 100644
index 00000000000..56decad535a
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/custom-property-substitution-serialization-retokenizes.txt
@@ -0,0 +1,6 @@
+calc(1px +/**/2px)
+3px
+3px
+1.0
+7
+12/**/0
diff --git a/Tests/LibWeb/Text/expected/css/input-line-height-after-a-web-font-loads.txt b/Tests/LibWeb/Text/expected/css/input-line-height-after-a-web-font-loads.txt
new file mode 100644
index 00000000000..2f71e137cc7
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/input-line-height-after-a-web-font-loads.txt
@@ -0,0 +1,2 @@
+Before the load: 20px
+After the load: normal
diff --git a/Tests/LibWeb/Text/expected/css/longhand-substitution-keeps-token-kinds.txt b/Tests/LibWeb/Text/expected/css/longhand-substitution-keeps-token-kinds.txt
new file mode 100644
index 00000000000..2945f094d20
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/longhand-substitution-keeps-token-kinds.txt
@@ -0,0 +1,4 @@
+integer: 1
+decimal: auto
+exponent: auto
+joined: auto
diff --git a/Tests/LibWeb/Text/expected/css/overflow-inherit-coordinated.txt b/Tests/LibWeb/Text/expected/css/overflow-inherit-coordinated.txt
new file mode 100644
index 00000000000..4467671898b
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/overflow-inherit-coordinated.txt
@@ -0,0 +1,5 @@
+visible-parent: visible visible
+visible-child: auto hidden
+clip-parent: clip clip
+clip-child: hidden scroll
+clip-sibling: clip visible
diff --git a/Tests/LibWeb/Text/expected/css/pending-substitution-after-block-changes.txt b/Tests/LibWeb/Text/expected/css/pending-substitution-after-block-changes.txt
new file mode 100644
index 00000000000..d566b44520b
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/pending-substitution-after-block-changes.txt
@@ -0,0 +1,20 @@
+attribute: border then border-top-width: border-top-style: solid; border-top-width: 3px; border-right-style: solid; border-right-width: 1px
+attribute: border then border-top: border-top-style: dashed; border-top-width: 3px; border-right-style: solid; border-right-width: 1px
+attribute: border-block then a width: border-top-style: solid; border-top-width: 3px
+attribute: background then a position: background-color: rgb(0, 128, 0); background-position-x: 9px
+attribute: font then a variant: font-size: 12px; font-variant-caps: small-caps
+attribute: border alone: border-top-style: solid; border-top-width: 1px; border-right-style: solid; border-right-width: 1px
+attribute: an undefined variable:
+attribute: important: border-top-style: solid; border-top-width: 1px; border-right-style: solid; border-right-width: 1px
+inline: background cleared:
+inline: background cleared and written again: background-color: rgb(0, 128, 0); background-position-x: 5px
+inline: background removed and written again: background-color: rgb(0, 128, 0); background-position-x: 5px
+inline: margin replaced and written again: margin-left: 7px
+inline: margin-left replaced and margin written again: margin-left: 7px; margin-top: 7px
+inline: border-top-width removed: border-top-style: solid; border-top-width: 3px; border-right-style: solid; border-right-width: 1px
+inline: border-width removed: border-top-style: solid; border-top-width: 3px; border-right-style: solid; border-right-width: 3px
+inline: border-width replaced: border-top-style: solid; border-top-width: 7px; border-right-style: solid; border-right-width: 7px
+rule: background cleared and written again: background-color: rgb(0, 128, 0); background-position-x: 5px
+rule: margin replaced and written again: margin-left: 7px
+rule: margin-left replaced and margin written again: margin-left: 7px; margin-top: 7px
+rule: border-top-width removed: border-top-style: solid; border-top-width: 3px; border-right-style: solid; border-right-width: 1px
diff --git a/Tests/LibWeb/Text/expected/css/pseudo-elements-generated-after-changes.txt b/Tests/LibWeb/Text/expected/css/pseudo-elements-generated-after-changes.txt
new file mode 100644
index 00000000000..ceeb6c918e6
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/pseudo-elements-generated-after-changes.txt
@@ -0,0 +1,16 @@
+none: 0
++before -undefined: 7
++after -before: 11
++before -undefined: 18
++null -after: 7
++null -before: 0
+below without parent: 0
+below with parent: 13
+below without parent again: 0
+gated in a container: 17
+gated out of a container: 0
+no content: 0
+marker before: rgb(0, 0, 0)
+marker of a list item: rgb(0, 128, 0) true
+marker without its rule: rgb(0, 0, 0)
+no longer a list item: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/absolutized-substituted-values-per-element.txt b/Tests/LibWeb/Text/expected/css/style-engine/absolutized-substituted-values-per-element.txt
new file mode 100644
index 00000000000..6f8365623a6
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/absolutized-substituted-values-per-element.txt
@@ -0,0 +1,3 @@
+attr: 0 of 600 with the width of another
+function: 0 of 600 with the width of another
+condition: 0 of 600 with the width of another
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/ancestor-became-visible-engine-computed.txt b/Tests/LibWeb/Text/expected/css/style-engine/ancestor-became-visible.txt
similarity index 74%
rename from Tests/LibWeb/Text/expected/css/style-engine/ancestor-became-visible-engine-computed.txt
rename to Tests/LibWeb/Text/expected/css/style-engine/ancestor-became-visible.txt
index 28d62d8af77..c7989ec96ce 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/ancestor-became-visible-engine-computed.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/ancestor-became-visible.txt
@@ -1,5 +1,3 @@
-engine records: 3
-C++ recomputations: 0
grandchild color: rgb(0, 128, 0)
hit test finds the child: true
child::before width: 16px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/backing-pseudo-complete-answer.txt b/Tests/LibWeb/Text/expected/css/style-engine/backing-pseudo-complete-style.txt
similarity index 60%
rename from Tests/LibWeb/Text/expected/css/style-engine/backing-pseudo-complete-answer.txt
rename to Tests/LibWeb/Text/expected/css/style-engine/backing-pseudo-complete-style.txt
index 5b863a79063..28dac6a0cd1 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/backing-pseudo-complete-answer.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/backing-pseudo-complete-style.txt
@@ -1,2 +1 @@
-C++ recomputations: 0
placeholder color: rgb(0, 128, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-group-cache.txt b/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-group-cache.txt
new file mode 100644
index 00000000000..28fef11af01
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-group-cache.txt
@@ -0,0 +1,2 @@
+computed every styled element: true
+differences: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-keywords.txt b/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-keywords.txt
new file mode 100644
index 00000000000..28fef11af01
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-keywords.txt
@@ -0,0 +1,2 @@
+computed every styled element: true
+differences: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-pseudo-elements.txt b/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-pseudo-elements.txt
new file mode 100644
index 00000000000..ae8a1540a43
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-pseudo-elements.txt
@@ -0,0 +1,3 @@
+computed every styled element: true
+pseudo-elements: 7
+differences: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-registered-properties.txt b/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-registered-properties.txt
new file mode 100644
index 00000000000..28fef11af01
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-registered-properties.txt
@@ -0,0 +1,2 @@
+computed every styled element: true
+differences: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-reuse.txt b/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-reuse.txt
new file mode 100644
index 00000000000..381acf74c70
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-reuse.txt
@@ -0,0 +1,3 @@
+computed every styled element: true
+reused some elements: true
+differences: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-sharing.txt b/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-sharing.txt
new file mode 100644
index 00000000000..40eff793f6d
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-sharing.txt
@@ -0,0 +1,3 @@
+computed every styled element: true
+shared some elements: true
+differences: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-substitution.txt b/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-substitution.txt
new file mode 100644
index 00000000000..28fef11af01
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-substitution.txt
@@ -0,0 +1,2 @@
+computed every styled element: true
+differences: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-zoom.txt b/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-zoom.txt
new file mode 100644
index 00000000000..28fef11af01
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-zoom.txt
@@ -0,0 +1,2 @@
+computed every styled element: true
+differences: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/computed-cold-subtree-records.txt b/Tests/LibWeb/Text/expected/css/style-engine/computed-cold-subtree-records.txt
new file mode 100644
index 00000000000..490a7c44733
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/computed-cold-subtree-records.txt
@@ -0,0 +1,3 @@
+em color: rgb(255, 0, 0)
+p font size: 20px
+::before content: "x"
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/computed-document-element-records.txt b/Tests/LibWeb/Text/expected/css/style-engine/computed-document-element-records.txt
new file mode 100644
index 00000000000..c097d6656dd
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/computed-document-element-records.txt
@@ -0,0 +1,5 @@
+load: html font-size 16px, padding 0px, margin 0px, 2rem width 32px
+html.big: html font-size 24px, padding 0px, margin 0px, 2rem width 48px
+html.big pad: html font-size 24px, padding 24px, margin 48px, 2rem width 48px
+html.pad: html font-size 16px, padding 16px, margin 32px, 2rem width 32px
+html.none: html font-size 16px, padding 0px, margin 0px, 2rem width 32px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/engine-computed-pseudo-element-records.txt b/Tests/LibWeb/Text/expected/css/style-engine/computed-pseudo-element-records.txt
similarity index 87%
rename from Tests/LibWeb/Text/expected/css/style-engine/engine-computed-pseudo-element-records.txt
rename to Tests/LibWeb/Text/expected/css/style-engine/computed-pseudo-element-records.txt
index 25aca30e6f0..87850238fdf 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/engine-computed-pseudo-element-records.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/computed-pseudo-element-records.txt
@@ -6,5 +6,3 @@ d: before content none
e: before content "e" color rgb(0, 0, 255)
none: before content normal
second b: before content "b"
-engine pseudo records: 13
-C++ recomputations: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/content-and-anchor-name.txt b/Tests/LibWeb/Text/expected/css/style-engine/content-and-anchor-name.txt
new file mode 100644
index 00000000000..c79b1273064
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/content-and-anchor-name.txt
@@ -0,0 +1,14 @@
+image content, first record: value an image
+counter(x, decimal), first record: value counter(x)
+named @counter-style, first record: value counter(x, thumbs)
+content flip, first record: value none
+list-style-type, first record: value thumbs
+anchor-name, first record: value --anchor
+anchor-name on ::before, first record: value --anchor
+image content, warm record: value an image
+counter(x, decimal), warm record: value counter(x)
+named @counter-style, warm record: value counter(x, thumbs)
+content flip, warm record: value none
+list-style-type, warm record: value thumbs
+anchor-name, warm record: value --anchor
+anchor-name on ::before, warm record: value --anchor
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/custom-function-body-change-engine-computed.txt b/Tests/LibWeb/Text/expected/css/style-engine/custom-function-body-change.txt
similarity index 50%
rename from Tests/LibWeb/Text/expected/css/style-engine/custom-function-body-change-engine-computed.txt
rename to Tests/LibWeb/Text/expected/css/style-engine/custom-function-body-change.txt
index 77c69e976c2..4467de4bb02 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/custom-function-body-change-engine-computed.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/custom-function-body-change.txt
@@ -1,4 +1,2 @@
-engine records: 1
-C++ recomputations: 0
element width: 20px
::before width: 20px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/custom-function-conditions-engine-computed.txt b/Tests/LibWeb/Text/expected/css/style-engine/custom-function-conditions.txt
similarity index 100%
rename from Tests/LibWeb/Text/expected/css/style-engine/custom-function-conditions-engine-computed.txt
rename to Tests/LibWeb/Text/expected/css/style-engine/custom-function-conditions.txt
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/font-carried-longhand.txt b/Tests/LibWeb/Text/expected/css/style-engine/font-carried-longhand.txt
new file mode 100644
index 00000000000..6da9ecd34c8
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/font-carried-longhand.txt
@@ -0,0 +1,2 @@
+font-feature-settings: value "liga" 0
+text-rendering: value optimizelegibility
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/font-feature-values-edit.txt b/Tests/LibWeb/Text/expected/css/style-engine/font-feature-values-edit.txt
new file mode 100644
index 00000000000..484e72a8dff
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/font-feature-values-edit.txt
@@ -0,0 +1 @@
+font-variant-alternates: styleset(fancy)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/font-waits-resolve-within-pass.txt b/Tests/LibWeb/Text/expected/css/style-engine/font-waits-resolve-within-pass.txt
new file mode 100644
index 00000000000..b1cf196e7ac
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/font-waits-resolve-within-pass.txt
@@ -0,0 +1,3 @@
+passes: 1
+elements styled: 6
+deepest font size: 18.75px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/identical-style-reuses-cascade-input.txt b/Tests/LibWeb/Text/expected/css/style-engine/identical-style-reuses-cascade-input.txt
new file mode 100644
index 00000000000..12b2014a6bb
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/identical-style-reuses-cascade-input.txt
@@ -0,0 +1,2 @@
+first color: rgb(255, 0, 0)
+second color: rgb(255, 0, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/inherited-color-mix-resolves-against-own-color.txt b/Tests/LibWeb/Text/expected/css/style-engine/inherited-color-mix-resolves-against-own-color.txt
new file mode 100644
index 00000000000..1419425604b
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/inherited-color-mix-resolves-against-own-color.txt
@@ -0,0 +1,4 @@
+start: differences from a cold pass: 0
+third moved: differences from a cold pass: 0
+first moved: differences from a cold pass: 0
+third back: differences from a cold pass: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/install-same-custom-property-values.txt b/Tests/LibWeb/Text/expected/css/style-engine/install-same-custom-property-values.txt
new file mode 100644
index 00000000000..c1235caac85
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/install-same-custom-property-values.txt
@@ -0,0 +1,4 @@
+inserted: 600 children, 0 with the style of another
+inserted: 0 installed differently from a cold pass
+restyled: 600 children, 0 with the style of another
+restyled: 0 installed differently from a cold pass
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/losing-context-winners.txt b/Tests/LibWeb/Text/expected/css/style-engine/losing-context-winners.txt
new file mode 100644
index 00000000000..dc7d5b070da
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/losing-context-winners.txt
@@ -0,0 +1,2 @@
+ordinary item: rgb(0, 0, 0)
+sentinel: rgb(0, 128, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/mathml-hint-change-engine-computed.txt b/Tests/LibWeb/Text/expected/css/style-engine/mathml-hint-change.txt
similarity index 53%
rename from Tests/LibWeb/Text/expected/css/style-engine/mathml-hint-change-engine-computed.txt
rename to Tests/LibWeb/Text/expected/css/style-engine/mathml-hint-change.txt
index a2fdc10b663..cb70d21661c 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/mathml-hint-change-engine-computed.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/mathml-hint-change.txt
@@ -1,3 +1,2 @@
color: rgb(0, 128, 0)
-hint change stays in the engine: true
color: rgb(255, 0, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/monospace-font-size-quirk-engine-computed.txt b/Tests/LibWeb/Text/expected/css/style-engine/monospace-font-size-quirk.txt
similarity index 86%
rename from Tests/LibWeb/Text/expected/css/style-engine/monospace-font-size-quirk-engine-computed.txt
rename to Tests/LibWeb/Text/expected/css/style-engine/monospace-font-size-quirk.txt
index 79624d4d4ae..618cbd94442 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/monospace-font-size-quirk-engine-computed.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/monospace-font-size-quirk.txt
@@ -5,4 +5,3 @@ inherits-mono: 26px
keyword: 18px
mono-under-keyword: 16px
recoloured mono-under-keyword: 16px
-C++ recomputations: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/named-timeline.txt b/Tests/LibWeb/Text/expected/css/style-engine/named-timeline.txt
new file mode 100644
index 00000000000..9bab209ad84
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/named-timeline.txt
@@ -0,0 +1,4 @@
+scroll timeline named: --scroller inline
+view timeline named: --viewed 10px
+scroll timeline unnamed: none block
+view timeline unnamed: none auto
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/position-anchor-differs-with-shared-insets.txt b/Tests/LibWeb/Text/expected/css/style-engine/position-anchor-differs-with-shared-insets.txt
new file mode 100644
index 00000000000..35b9958a83d
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/position-anchor-differs-with-shared-insets.txt
@@ -0,0 +1,2 @@
+t1: top: 0 left: 0
+t2: top: 250 left: 300
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/presentational-hint-change-engine-computed.txt b/Tests/LibWeb/Text/expected/css/style-engine/presentational-hint-change.txt
similarity index 64%
rename from Tests/LibWeb/Text/expected/css/style-engine/presentational-hint-change-engine-computed.txt
rename to Tests/LibWeb/Text/expected/css/style-engine/presentational-hint-change.txt
index 41e70f3bbeb..594730ec730 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/presentational-hint-change-engine-computed.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/presentational-hint-change.txt
@@ -1,3 +1,2 @@
-no C++ recomputation: true
text-align: -libweb-right
color: rgb(0, 128, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/retained-priority-change.txt b/Tests/LibWeb/Text/expected/css/style-engine/priority-change.txt
similarity index 86%
rename from Tests/LibWeb/Text/expected/css/style-engine/retained-priority-change.txt
rename to Tests/LibWeb/Text/expected/css/style-engine/priority-change.txt
index 4f00172839f..3a4f5291403 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/retained-priority-change.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/priority-change.txt
@@ -1,11 +1,9 @@
-reverse stays selective: true
reverse color: rgb(255, 0, 0)
reverse background: rgb(255, 0, 0)
reverse child color: rgb(255, 0, 0)
reverse pseudo content: "first"
reverse pseudo color: rgb(255, 0, 0)
reverse opacity: 0.5
-restore stays selective: true
restore color: rgb(0, 0, 255)
restore background: rgb(255, 0, 0)
restore child color: rgb(0, 0, 255)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/pseudo-element-custom-properties-over-another-parent.txt b/Tests/LibWeb/Text/expected/css/style-engine/pseudo-element-custom-properties-over-another-parent.txt
new file mode 100644
index 00000000000..8a3b8673cdd
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/pseudo-element-custom-properties-over-another-parent.txt
@@ -0,0 +1,2 @@
+animations: 2
+heights: 14/14
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/registered-custom-property.txt b/Tests/LibWeb/Text/expected/css/style-engine/registered-custom-property.txt
new file mode 100644
index 00000000000..ff83ce6553f
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/registered-custom-property.txt
@@ -0,0 +1,3 @@
+parents switched on: small --len 20px children 20px 20px, large --len 40px children 40px 40px
+::before switched on: --len 60px, width 60px
+first records: --len 40px, child 40px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/root-font-face-load-engine-computed.txt b/Tests/LibWeb/Text/expected/css/style-engine/root-font-face-load.txt
similarity index 63%
rename from Tests/LibWeb/Text/expected/css/style-engine/root-font-face-load-engine-computed.txt
rename to Tests/LibWeb/Text/expected/css/style-engine/root-font-face-load.txt
index aae0bf34c6f..b18e08b9207 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/root-font-face-load-engine-computed.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/root-font-face-load.txt
@@ -1,5 +1,3 @@
-engine computed records: true
-C++ recomputations: 0
rem child matches a fresh one: true
rlh child matches a fresh one: true
face loaded: loaded
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/sampled-custom-property-own-var-engine-computed.txt b/Tests/LibWeb/Text/expected/css/style-engine/sampled-custom-property-own-var.txt
similarity index 66%
rename from Tests/LibWeb/Text/expected/css/style-engine/sampled-custom-property-own-var-engine-computed.txt
rename to Tests/LibWeb/Text/expected/css/style-engine/sampled-custom-property-own-var.txt
index f631d35b66e..3d99b51d1e4 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/sampled-custom-property-own-var-engine-computed.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/sampled-custom-property-own-var.txt
@@ -1,2 +1 @@
-C++ recomputations: 0
width 30px, z-index 2, color rgb(0, 128, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/selection-observability-engine-computed.txt b/Tests/LibWeb/Text/expected/css/style-engine/selection-observability.txt
similarity index 72%
rename from Tests/LibWeb/Text/expected/css/style-engine/selection-observability-engine-computed.txt
rename to Tests/LibWeb/Text/expected/css/style-engine/selection-observability.txt
index af0d778afe7..38b37339754 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/selection-observability-engine-computed.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/selection-observability.txt
@@ -1,5 +1,3 @@
-engine computed records: true
-C++ recomputations: 0
styled ::selection: rgb(1, 2, 3) on rgb(4, 5, 6)
inner ::selection inherits: rgb(1, 2, 3) on rgb(4, 5, 6)
plain color: rgb(0, 128, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/sibling-pseudo-elements-keep-their-own-animated-custom-properties.txt b/Tests/LibWeb/Text/expected/css/style-engine/sibling-pseudo-elements-keep-their-own-animated-custom-properties.txt
new file mode 100644
index 00000000000..0f61e43daea
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/sibling-pseudo-elements-keep-their-own-animated-custom-properties.txt
@@ -0,0 +1,2 @@
+sampled: 0deg, 360deg
+restyled: 0deg, 360deg
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/style-change-gap.txt b/Tests/LibWeb/Text/expected/css/style-engine/style-change-gap.txt
new file mode 100644
index 00000000000..45ec1750ddb
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/style-change-gap.txt
@@ -0,0 +1 @@
+color: rgb(0, 0, 255)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/style-change-inherited-gap.txt b/Tests/LibWeb/Text/expected/css/style-engine/style-change-inherited-gap.txt
new file mode 100644
index 00000000000..256ed5701a9
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/style-change-inherited-gap.txt
@@ -0,0 +1 @@
+child list position: inside
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/style-counters-report-work.txt b/Tests/LibWeb/Text/expected/css/style-engine/style-counters-report-work.txt
new file mode 100644
index 00000000000..68b462e69d0
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/style-counters-report-work.txt
@@ -0,0 +1,17 @@
+keys: passes, fullPasses, styledElements, changedElements, hintedElements, hintedSubtrees, invalidationVisits, invalidationTests, coldPasses, sharedElements, reusedElements, indexBuilds, indexedEntries, compiledSelectors, userAgentIndexBuilds, matchedElements, relativeWalks
+reset zeroes every counter: true
+one pass: true
+no full pass: true
+styled <= 1: true
+changed <= styled: true
+hinted <= 1: true
+no cold pass or index build: true
+last pass full: false
+last pass styled: [target]
+last pass changed: [target]
+reset zeroes every counter again: true
+reset forgets the last pass: true
+animation sample composed: true
+stylesheet change: no full pass true, no index build true, entries true
+stylesheet change last pass targeted: true
+stylesheet change changed sibling: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/substituted-url-image-engine-computed.txt b/Tests/LibWeb/Text/expected/css/style-engine/substituted-url-image.txt
similarity index 59%
rename from Tests/LibWeb/Text/expected/css/style-engine/substituted-url-image-engine-computed.txt
rename to Tests/LibWeb/Text/expected/css/style-engine/substituted-url-image.txt
index ed09f98859c..2e3485841bd 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/substituted-url-image-engine-computed.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/substituted-url-image.txt
@@ -1,3 +1,2 @@
-engine computed the image records: true
local: url("image.svg")
imported: url("support/image.svg")
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/substitution-sources.txt b/Tests/LibWeb/Text/expected/css/style-engine/substitution-sources.txt
new file mode 100644
index 00000000000..a0578321214
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/substitution-sources.txt
@@ -0,0 +1,15 @@
+inherit() in a custom property: value 3px
+inherit() in a longhand: value 3px
+if(media()): value 10px
+if(supports()): value 10px
+if(style()): value 10px
+if(style()) range: value 10px
+if(style()) registered: value 10px
+env(): value 10px
+custom function: value 10px
+custom function with @media: value 10px
+custom function with @container: value 10px
+registered <length> in em: value 30px
+random() shared: value a length
+random() per element: value a length
+mixed: value 3px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/published-substitution-usage.txt b/Tests/LibWeb/Text/expected/css/style-engine/substitution-usage.txt
similarity index 55%
rename from Tests/LibWeb/Text/expected/css/style-engine/published-substitution-usage.txt
rename to Tests/LibWeb/Text/expected/css/style-engine/substitution-usage.txt
index 716039f3d43..26831d5ceae 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/published-substitution-usage.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/substitution-usage.txt
@@ -1,3 +1,2 @@
-child uses an engine record: true
retried width: 10px
registered width: 20px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/url-image-winners-engine-computed.txt b/Tests/LibWeb/Text/expected/css/style-engine/url-image-winners.txt
similarity index 75%
rename from Tests/LibWeb/Text/expected/css/style-engine/url-image-winners-engine-computed.txt
rename to Tests/LibWeb/Text/expected/css/style-engine/url-image-winners.txt
index 1d58c03c7b5..39cbc6e23c3 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/url-image-winners-engine-computed.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/url-image-winners.txt
@@ -1,4 +1,3 @@
-engine computed the image records: true
local: url("image.svg")
imported: url("support/image.svg")
attribute: url("support/image.svg")
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/value-function-inputs.txt b/Tests/LibWeb/Text/expected/css/style-engine/value-function-inputs.txt
new file mode 100644
index 00000000000..f32f35d4c80
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/value-function-inputs.txt
@@ -0,0 +1,26 @@
+attr initial: width 10px, --copied "first", ::before "one", ::after width 10px
+attr width changed: width 20px, --copied "first", ::before "one", ::after width 20px
+attr word changed: width 20px, --copied "second", ::before "one", ::after width 20px
+attr label changed: width 20px, --copied "second", ::before "two", ::after width 20px
+attr width removed: width 1px, --copied "second", ::before "two", ::after width 2px
+attr width added: width 30px, --copied "second", ::before "two", ::after width 30px
+siblings initial: first(1px 3px 1 1000px 11px 10px 100px) second(2px 3px 2 2000px 22px 10px 200px) third(3px 3px 3 3000px 11px 10px 300px)
+sibling inserted first: inserted(1px 4px 1 1000px 11px 10px 100px) first(2px 4px 2 2000px 22px 10px 200px) second(3px 4px 3 3000px 11px 10px 300px) third(4px 4px 4 4000px 11px 10px 400px)
+sibling removed: inserted(1px 3px 1 1000px 11px 10px 100px) first(2px 3px 2 2000px 22px 10px 200px) third(3px 3px 3 3000px 11px 10px 300px)
+sibling moved last: inserted(1px 3px 1 1000px 11px 10px 100px) third(2px 3px 2 2000px 22px 10px 200px) first(3px 3px 3 3000px 11px 10px 300px)
+text node inserted: inserted(1px 3px 1 1000px 11px 10px 100px) third(2px 3px 2 2000px 22px 10px 200px) first(3px 3px 3 3000px 11px 10px 300px)
+sibling appended last: inserted(1px 4px 1 1000px 11px 10px 100px) third(2px 4px 2 2000px 22px 10px 200px) first(3px 4px 3 3000px 11px 10px 300px) appended(4px 4px 4 4000px 11px 10px 400px)
+last sibling removed: inserted(1px 3px 1 1000px 11px 10px 100px) third(2px 3px 2 2000px 22px 10px 200px) first(3px 3px 3 3000px 11px 10px 300px)
+if initial: 5px 0px
+if own property set: 50px 0px
+if own property removed: 5px 0px
+if inherited property set: 50px 0px
+if inherited property changed: 5px 0px
+inherit initial: 7px 14px
+inherit parent changed: 9px 18px
+inherit parent removed: 3px 6px
+inherit own property set: 3px 6px
+function initial: 8px 4px
+function inherited input changed: 12px 6px
+function own input set: 12px 18px
+function definition changed: 30px 18px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/viewport-relative-value-shared-by-elements.txt b/Tests/LibWeb/Text/expected/css/style-engine/viewport-relative-value-shared-by-elements.txt
new file mode 100644
index 00000000000..e8a18b13213
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/viewport-relative-value-shared-by-elements.txt
@@ -0,0 +1,3 @@
+first: 50px
+second: 50px
+third: 50px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/retained-winner-priority-pseudo-target.txt b/Tests/LibWeb/Text/expected/css/style-engine/winner-priority-pseudo-target.txt
similarity index 100%
rename from Tests/LibWeb/Text/expected/css/style-engine/retained-winner-priority-pseudo-target.txt
rename to Tests/LibWeb/Text/expected/css/style-engine/winner-priority-pseudo-target.txt
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/winner-prune-retained-answer.txt b/Tests/LibWeb/Text/expected/css/style-engine/winner-prune.txt
similarity index 100%
rename from Tests/LibWeb/Text/expected/css/style-engine/winner-prune-retained-answer.txt
rename to Tests/LibWeb/Text/expected/css/style-engine/winner-prune.txt
diff --git a/Tests/LibWeb/Text/expected/css/user-agent-declarations-intern-once-per-process.txt b/Tests/LibWeb/Text/expected/css/user-agent-declarations-intern-once-per-process.txt
new file mode 100644
index 00000000000..90a5528fddf
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/user-agent-declarations-intern-once-per-process.txt
@@ -0,0 +1,2 @@
+margin-top from the user-agent sheet: 16px
+declarations the frame published: 0
diff --git a/Tests/LibWeb/Text/expected/css/webkit-text-fill-color-inherited-below-own-color.txt b/Tests/LibWeb/Text/expected/css/webkit-text-fill-color-inherited-below-own-color.txt
new file mode 100644
index 00000000000..c7b5c079384
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/webkit-text-fill-color-inherited-below-own-color.txt
@@ -0,0 +1,5 @@
+dynamic: rgb(16, 30, 30), rgb(111, 119, 134), rgb(111, 119, 134)
+svg: rgb(16, 30, 30), rgb(111, 119, 134), rgb(111, 119, 134)
+static: rgba(0, 0, 0, 0), rgba(0, 0, 0, 0), rgba(0, 0, 0, 0)
+dynamic: rgba(0, 0, 0, 0), rgba(0, 0, 0, 0), rgba(0, 0, 0, 0)
+svg: rgba(0, 0, 0, 0), rgba(0, 0, 0, 0), rgba(0, 0, 0, 0)
diff --git a/Tests/LibWeb/Text/input/css/custom-property-not-inherited-below-pseudo-element-sharing-its-value.html b/Tests/LibWeb/Text/input/css/custom-property-not-inherited-below-pseudo-element-sharing-its-value.html
new file mode 100644
index 00000000000..801e46e5a50
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/custom-property-not-inherited-below-pseudo-element-sharing-its-value.html
@@ -0,0 +1,33 @@
+<!DOCTYPE html>
+<style>
+@property --not-inherited {
+ syntax: "*";
+ inherits: false;
+ initial-value: start;
+}
+.pseudo-element-declares::before, .element-declares {
+ --not-inherited: declared;
+}
+.pseudo-element-declares::before {
+ content: "";
+}
+</style>
+<div id="first"></div>
+<div id="second"><div id="child"></div></div>
+<script src="../include.js"></script>
+<script>
+ asyncTest(done => {
+ const child = document.getElementById("child");
+ requestAnimationFrame(() => {
+ // NB: A ::before and an element holding the same custom properties, with a child of the element restyled
+ // along with them.
+ document.getElementById("first").classList.add("pseudo-element-declares");
+ document.getElementById("second").classList.add("element-declares");
+ child.style.color = "green";
+ requestAnimationFrame(() => {
+ println(`--not-inherited of the child: ${getComputedStyle(child).getPropertyValue("--not-inherited")}`);
+ done();
+ });
+ });
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/custom-property-substitution-serialization-retokenizes.html b/Tests/LibWeb/Text/input/css/custom-property-substitution-serialization-retokenizes.html
new file mode 100644
index 00000000000..1b85e538cac
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/custom-property-substitution-serialization-retokenizes.html
@@ -0,0 +1,33 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<style>
+@property --length {
+ syntax: "<length>";
+ inherits: false;
+ initial-value: 0px;
+}
+@property --integer {
+ syntax: "<integer>";
+ inherits: false;
+ initial-value: 7;
+}
+#a { --plus: +; --sum: calc(1px var(--plus)2px); --alias: var(--sum); --length: var(--alias); }
+#d { --plus: +; --length: calc(1px var(--plus)2px); }
+#b { --number: 1.0; --alias: var(--number); --integer: var(--alias); }
+#c { --number: 12; --joined: var(--number)0; --alias: var(--joined); }
+</style>
+<div id="a"></div>
+<div id="b"></div>
+<div id="c"></div>
+<div id="d"></div>
+<script>
+ test(() => {
+ const computedValue = (id, property) => getComputedStyle(document.getElementById(id)).getPropertyValue(property);
+ println(computedValue("a", "--alias"));
+ println(computedValue("a", "--length"));
+ println(computedValue("d", "--length"));
+ println(computedValue("b", "--alias"));
+ println(computedValue("b", "--integer"));
+ println(computedValue("c", "--alias"));
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/input-line-height-after-a-web-font-loads.html b/Tests/LibWeb/Text/input/css/input-line-height-after-a-web-font-loads.html
new file mode 100644
index 00000000000..24a46d6e041
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/input-line-height-after-a-web-font-loads.html
@@ -0,0 +1,28 @@
+<!DOCTYPE html>
+<!-- The used line-height of a single-line input is never smaller than a line-height of normal, which reads the metrics
+ of its first available font: a web font arriving moves them. -->
+<style>
+ @font-face {
+ font-family: "Tall";
+ src: url("../../../Assets/NotoSansEthiopic.woff2");
+ }
+ input {
+ font-family: "Tall", sans-serif;
+ font-size: 16px;
+ line-height: 1.25;
+ }
+</style>
+<input id="input">
+<script src="../include.js"></script>
+<script>
+ asyncTest(async done => {
+ const input = document.getElementById("input");
+ const face = [...document.fonts][0];
+ println(`Before the load: ${getComputedStyle(input).lineHeight}`);
+ await face.load();
+ await document.fonts.ready;
+ await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
+ println(`After the load: ${getComputedStyle(input).lineHeight}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/longhand-substitution-keeps-token-kinds.html b/Tests/LibWeb/Text/input/css/longhand-substitution-keeps-token-kinds.html
new file mode 100644
index 00000000000..d8acdba29d3
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/longhand-substitution-keeps-token-kinds.html
@@ -0,0 +1,18 @@
+<!doctype html>
+<style>
+ #integer { --n: 1; --alias: var(--n); z-index: var(--alias); }
+ #decimal { --n: 1.0; --alias: var(--n); z-index: var(--alias); }
+ #exponent { --n: 1e0; z-index: var(--n); }
+ #joined { --n: 1; z-index: var(--n)0; }
+</style>
+<div id="integer"></div>
+<div id="decimal"></div>
+<div id="exponent"></div>
+<div id="joined"></div>
+<script src="../include.js"></script>
+<script>
+ test(() => {
+ for (const id of ["integer", "decimal", "exponent", "joined"])
+ println(`${id}: ${getComputedStyle(document.getElementById(id)).zIndex}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/overflow-inherit-coordinated.html b/Tests/LibWeb/Text/input/css/overflow-inherit-coordinated.html
new file mode 100644
index 00000000000..0da149b7e57
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/overflow-inherit-coordinated.html
@@ -0,0 +1,17 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<div id="visible-parent">
+ <div id="visible-child" style="overflow-x: inherit; overflow-y: hidden"></div>
+</div>
+<div id="clip-parent" style="overflow: clip">
+ <div id="clip-child" style="overflow-x: inherit; overflow-y: scroll"></div>
+ <div id="clip-sibling" style="overflow-x: inherit"></div>
+</div>
+<script>
+ test(() => {
+ for (const id of ["visible-parent", "visible-child", "clip-parent", "clip-child", "clip-sibling"]) {
+ const style = getComputedStyle(document.getElementById(id));
+ println(`${id}: ${style.overflowX} ${style.overflowY}`);
+ }
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/pending-substitution-after-block-changes.html b/Tests/LibWeb/Text/input/css/pending-substitution-after-block-changes.html
new file mode 100644
index 00000000000..dcbeca395d3
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/pending-substitution-after-block-changes.html
@@ -0,0 +1,141 @@
+<!DOCTYPE html>
+<style>
+ #rule-target {
+ }
+</style>
+<div id="rule-target"></div>
+<script src="../include.js"></script>
+<script>
+ test(() => {
+ const properties = [
+ "background-color",
+ "background-position-x",
+ "border-top-style",
+ "border-top-width",
+ "border-right-style",
+ "border-right-width",
+ "font-size",
+ "font-variant-caps",
+ "margin-left",
+ "margin-top",
+ ];
+
+ function report(name, element, setup) {
+ setup();
+ const style = getComputedStyle(element);
+ const values = properties
+ .filter(property => style.getPropertyValue(property) !== initial.getPropertyValue(property))
+ .map(property => `${property}: ${style.getPropertyValue(property)}`);
+ println(`${name}: ${values.join("; ")}`);
+ }
+
+ const reference = document.createElement("div");
+ document.body.append(reference);
+ const initial = getComputedStyle(reference);
+
+ function inlineCase(name, variables, writes) {
+ const element = document.createElement("div");
+ element.style.cssText = variables;
+ document.body.append(element);
+ report(name, element, () => {
+ for (const write of writes) {
+ write(element.style);
+ getComputedStyle(element).color;
+ }
+ });
+ element.remove();
+ }
+
+ function attributeCase(name, text) {
+ const element = document.createElement("div");
+ element.setAttribute("style", text);
+ document.body.append(element);
+ report(name, element, () => {});
+ element.remove();
+ }
+
+ const ruleElement = document.getElementById("rule-target");
+ const ruleStyle = document.styleSheets[0].cssRules[0].style;
+ function ruleCase(name, writes) {
+ ruleStyle.cssText = "--x: 1px solid red; --y: 7px; --z: rgb(0, 128, 0) 5px 6px";
+ report(name, ruleElement, () => {
+ for (const write of writes) {
+ write(ruleStyle);
+ getComputedStyle(ruleElement).color;
+ }
+ });
+ }
+
+ // A later declaration replaces a longhand of a nested shorthand, so its siblings alone pend it.
+ attributeCase("attribute: border then border-top-width", "--x: 1px solid red; border: var(--x); border-top-width: 3px");
+ attributeCase("attribute: border then border-top", "--x: 1px solid red; border: var(--x); border-top: 3px dashed blue");
+ attributeCase("attribute: border-block then a width", "--x: 1px solid red; border-block: var(--x); border-block-start-width: 3px");
+ attributeCase("attribute: background then a position", "--x: rgb(0, 128, 0) 5px 6px; background: var(--x); background-position-x: 9px");
+ attributeCase("attribute: font then a variant", "--x: 12px serif; font: var(--x); font-variant-caps: small-caps");
+ attributeCase("attribute: border alone", "--x: 1px solid red; border: var(--x)");
+ attributeCase("attribute: an undefined variable", "border: var(--missing); border-top-width: 3px");
+ attributeCase("attribute: important", "--x: 1px solid red; border: var(--x) !important; border-top-width: 3px");
+
+ // Clearing a shorthand and writing it again gives its longhands a value equal to the one the
+ // shorthand's own declaration still holds, but not that value.
+ const inlineVariables = "--x: 1px solid red; --y: 7px; --z: rgb(0, 128, 0) 5px 6px";
+ inlineCase("inline: background cleared", inlineVariables, [
+ s => (s.background = "var(--z)"),
+ s => (s.background = ""),
+ ]);
+ inlineCase("inline: background cleared and written again", inlineVariables, [
+ s => (s.background = "var(--z)"),
+ s => (s.background = ""),
+ s => (s.background = "var(--z)"),
+ ]);
+ inlineCase("inline: background removed and written again", inlineVariables, [
+ s => (s.background = "var(--z)"),
+ s => s.removeProperty("background"),
+ s => (s.background = "var(--z)"),
+ ]);
+ inlineCase("inline: margin replaced and written again", inlineVariables, [
+ s => (s.margin = "var(--y)"),
+ s => (s.margin = "1px"),
+ s => (s.margin = "var(--y)"),
+ s => s.removeProperty("margin-top"),
+ ]);
+ inlineCase("inline: margin-left replaced and margin written again", inlineVariables, [
+ s => (s.margin = "var(--y)"),
+ s => (s.marginLeft = "1px"),
+ s => (s.margin = "var(--y)"),
+ ]);
+ inlineCase("inline: border-top-width removed", inlineVariables, [
+ s => (s.border = "var(--x)"),
+ s => s.removeProperty("border-top-width"),
+ ]);
+ inlineCase("inline: border-width removed", inlineVariables, [
+ s => (s.border = "var(--x)"),
+ s => s.removeProperty("border-width"),
+ ]);
+ inlineCase("inline: border-width replaced", inlineVariables, [
+ s => (s.border = "var(--x)"),
+ s => (s.borderWidth = "var(--y)"),
+ ]);
+
+ ruleCase("rule: background cleared and written again", [
+ s => (s.background = "var(--z)"),
+ s => (s.background = ""),
+ s => (s.background = "var(--z)"),
+ ]);
+ ruleCase("rule: margin replaced and written again", [
+ s => (s.margin = "var(--y)"),
+ s => (s.margin = "1px"),
+ s => (s.margin = "var(--y)"),
+ s => s.removeProperty("margin-top"),
+ ]);
+ ruleCase("rule: margin-left replaced and margin written again", [
+ s => (s.margin = "var(--y)"),
+ s => (s.marginLeft = "1px"),
+ s => (s.margin = "var(--y)"),
+ ]);
+ ruleCase("rule: border-top-width removed", [
+ s => (s.border = "var(--x)"),
+ s => s.removeProperty("border-top-width"),
+ ]);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/pseudo-elements-generated-after-changes.html b/Tests/LibWeb/Text/input/css/pseudo-elements-generated-after-changes.html
new file mode 100644
index 00000000000..cf7127f5128
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/pseudo-elements-generated-after-changes.html
@@ -0,0 +1,62 @@
+<!doctype html>
+<script src="../include.js"></script>
+<style>
+ #root * { display: block; }
+ .before::before { content: ""; display: block; height: 7px; }
+ .after::after { content: ""; display: block; height: 11px; }
+ .below .before-below::before { content: ""; display: block; height: 13px; }
+ @container box (min-width: 1px) { .gated::before { content: ""; display: block; height: 17px; } }
+ .box { container: box / inline-size; }
+ li.item { list-style-position: inside; }
+ .item-style::marker { color: rgb(0, 128, 0); }
+ .no-content::before { height: 19px; display: block; }
+</style>
+<div id="root">
+ <div class="target"></div>
+ <div class="parent"><div class="child"></div></div>
+ <div class="box"><div class="in-box"></div></div>
+ <div class="no-content"></div>
+ <div id="list-item" style="display: block; list-style-position: inside">x</div>
+</div>
+<script>
+ // Whether an element generates its pseudo-elements is told by the height they give it: it has to follow the rules
+ // that style them coming and going, with the element holding no rule for any of them in between.
+ test(() => {
+ const height = selector => document.querySelector(selector).offsetHeight;
+ const target = document.querySelector(".target");
+ println(`none: ${height(".target")}`);
+ for (const [add, remove] of [["before"], ["after", "before"], ["before"], [null, "after"], [null, "before"]]) {
+ if (add) target.classList.add(add);
+ if (remove) target.classList.remove(remove);
+ println(`+${add} -${remove}: ${height(".target")}`);
+ }
+
+ const parent = document.querySelector(".parent");
+ const child = document.querySelector(".child");
+ child.classList.add("before-below");
+ println(`below without parent: ${height(".child")}`);
+ parent.classList.add("below");
+ println(`below with parent: ${height(".child")}`);
+ parent.classList.remove("below");
+ println(`below without parent again: ${height(".child")}`);
+
+ const inBox = document.querySelector(".in-box");
+ inBox.classList.add("gated");
+ println(`gated in a container: ${height(".in-box")}`);
+ document.querySelector(".box").classList.remove("box");
+ println(`gated out of a container: ${height(".in-box")}`);
+
+ println(`no content: ${height(".no-content")}`);
+
+ const item = document.getElementById("list-item");
+ const empty = item.offsetWidth;
+ println(`marker before: ${getComputedStyle(item, "::marker").color}`);
+ item.style.display = "list-item";
+ item.classList.add("item-style");
+ println(`marker of a list item: ${getComputedStyle(item, "::marker").color} ${item.offsetHeight > 0}`);
+ item.classList.remove("item-style");
+ println(`marker without its rule: ${getComputedStyle(item, "::marker").color}`);
+ item.style.display = "block";
+ println(`no longer a list item: ${item.offsetHeight > 0 && empty > 0}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/resources/shared-link-component.css b/Tests/LibWeb/Text/input/css/resources/shared-link-component.css
new file mode 100644
index 00000000000..46d5ce6e7ce
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/resources/shared-link-component.css
@@ -0,0 +1,3 @@
+.target { color: rgb(0, 128, 0); }
+.target.wide { width: 10px; }
+.other { color: rgb(255, 0, 0); }
diff --git a/Tests/LibWeb/Text/input/css/style-engine/absolutized-substituted-values-per-element.html b/Tests/LibWeb/Text/input/css/style-engine/absolutized-substituted-values-per-element.html
new file mode 100644
index 00000000000..b40aec8e33a
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/style-engine/absolutized-substituted-values-per-element.html
@@ -0,0 +1,33 @@
+<!DOCTYPE html>
+<style>
+ @function --passed(--value <length>) returns <length> { result: var(--value); }
+ .attr { width: attr(data-w type(<length>)); }
+ .function { width: --passed(attr(data-w type(<length>))); }
+ .condition { width: if(media(width > 1px): attr(data-w type(<length>)); else: 0px); }
+</style>
+<div id="holder"></div>
+<script src="../../include.js"></script>
+<script>
+ // Each element here substitutes a value of its own, freed once it is computed, which the next element's can land on
+ // the address of. What the first absolutized to must not then answer for the second.
+ test(() => {
+ const holder = document.getElementById("holder");
+ for (const name of ["attr", "function", "condition"]) {
+ const expected = [];
+ const children = [];
+ for (let i = 0; i < 600; ++i) {
+ const inches = (i * i + i) % 5 + 1;
+ const child = document.createElement("div");
+ child.className = name;
+ child.setAttribute("data-w", `${inches}in`);
+ holder.append(child);
+ children.push(child);
+ expected.push(`${inches * 96}px`);
+ }
+ internals.updateStyle();
+ const wrong = children.filter((child, index) => getComputedStyle(child).width !== expected[index]).length;
+ println(`${name}: ${wrong} of ${children.length} with the width of another`);
+ holder.textContent = "";
+ }
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/ancestor-became-visible-engine-computed.html b/Tests/LibWeb/Text/input/css/style-engine/ancestor-became-visible.html
similarity index 73%
rename from Tests/LibWeb/Text/input/css/style-engine/ancestor-became-visible-engine-computed.html
rename to Tests/LibWeb/Text/input/css/style-engine/ancestor-became-visible.html
index ea6994859cb..62b304d4df8 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/ancestor-became-visible-engine-computed.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/ancestor-became-visible.html
@@ -9,20 +9,16 @@
</style>
<div id="hidden-ancestor" class="hidden"><div id="child"><span id="grandchild">text</span></div></div>
<script>
- // An element whose ancestor leaves display:none had its style cleared on the way in. Count who
- // computes its record again, and check the element takes it: its box is there for a hit test.
+ // An element whose ancestor leaves display:none had its style cleared on the way in. Check the
+ // element computes its record again and takes it: its box is there for a hit test.
// Its pseudo-element comes back with it, and a change made inside the subtree while it was
// hidden shows once it is revealed.
test(() => {
internals.updateStyle();
grandchild.classList.add("toggled");
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
document.getElementById("hidden-ancestor").classList.remove("hidden");
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`engine records: ${after.engineComputedStyleRecords - before.engineComputedStyleRecords}`);
- println(`C++ recomputations: ${after.elementStyleRecomputations - before.elementStyleRecomputations}`);
println(`grandchild color: ${getComputedStyle(grandchild).color}`);
const rect = child.getBoundingClientRect();
const hit = document.elementFromPoint(rect.left + 1, rect.top + 1);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/backing-pseudo-complete-answer.html b/Tests/LibWeb/Text/input/css/style-engine/backing-pseudo-complete-style.html
similarity index 71%
rename from Tests/LibWeb/Text/input/css/style-engine/backing-pseudo-complete-answer.html
rename to Tests/LibWeb/Text/input/css/style-engine/backing-pseudo-complete-style.html
index 703932be3e3..c54c888bda4 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/backing-pseudo-complete-answer.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/backing-pseudo-complete-style.html
@@ -9,11 +9,8 @@
test(() => {
// The element standing for the input's ::placeholder is cascaded from the input's rules.
internals.updateStyle();
- const recomputations = () => internals.getStyleInvalidationCounters().elementStyleRecomputations;
- const before = recomputations();
input.classList.add("changed");
internals.updateStyle();
- println(`C++ recomputations: ${recomputations() - before}`);
println(`placeholder color: ${getComputedStyle(input, "::placeholder").color}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/cold-pass-group-cache.html b/Tests/LibWeb/Text/input/css/style-engine/cold-pass-group-cache.html
new file mode 100644
index 00000000000..1226eb26d27
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/style-engine/cold-pass-group-cache.html
@@ -0,0 +1,24 @@
+<!DOCTYPE html>
+<style>
+ .framed { border: 2px solid currentcolor; outline: 1px solid currentcolor; padding: 1em; display: block; }
+ .red { color: rgb(200, 0, 0); }
+ .blue { color: rgb(0, 0, 200); }
+ .small { font-size: 10px; }
+ .large { font-size: 30px; }
+ .zoomed { zoom: 2; }
+</style>
+<div class="red"><span class="framed">a</span><span class="framed">b</span></div>
+<div class="blue"><span class="framed">a</span><span class="framed">b</span></div>
+<div class="small"><span class="framed">a</span></div>
+<div class="large"><span class="framed">a</span></div>
+<div class="zoomed"><span class="framed">a</span></div>
+<div><span class="framed">a</span></div>
+<script src="../../include.js"></script>
+<script>
+ test(() => {
+ internals.updateStyle();
+ const report = internals.styleColdPass();
+ println(`computed every styled element: ${report.computedElements == report.elements}`);
+ println(`differences: ${report.differences}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/cold-pass-keywords.html b/Tests/LibWeb/Text/input/css/style-engine/cold-pass-keywords.html
new file mode 100644
index 00000000000..86d871ec997
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/style-engine/cold-pass-keywords.html
@@ -0,0 +1,19 @@
+<!DOCTYPE html>
+<style>
+ .parent { color: rgb(10, 20, 30); padding: 3px; scrollbar-width: thin; text-transform: uppercase; }
+ .initial { color: initial; padding: initial; scrollbar-width: initial; text-transform: initial; }
+ .inherit { color: inherit; padding: inherit; scrollbar-width: inherit; margin-inline-start: inherit; }
+ .unset { color: unset; padding: unset; text-transform: unset; border-top-style: unset; }
+</style>
+<div class="parent" style="margin-inline-start: 7px">
+ <span class="initial">initial</span><span class="inherit">inherit</span><span class="unset">unset</span>
+</div>
+<script src="../../include.js"></script>
+<script>
+ test(() => {
+ internals.updateStyle();
+ const report = internals.styleColdPass();
+ println(`computed every styled element: ${report.computedElements == report.elements}`);
+ println(`differences: ${report.differences}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/cold-pass-pseudo-elements.html b/Tests/LibWeb/Text/input/css/style-engine/cold-pass-pseudo-elements.html
new file mode 100644
index 00000000000..41308ef161f
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/style-engine/cold-pass-pseudo-elements.html
@@ -0,0 +1,28 @@
+<!DOCTYPE html>
+<style>
+ .quoted::before { content: "\201C"; color: rgb(100, 0, 0); margin-right: 2px; }
+ .quoted::after { content: "\201D"; font-weight: bold; }
+ .empty::before { content: none; color: red; }
+ .normal::after { content: normal; color: red; }
+ .themed { --accent: rgb(0, 90, 0); }
+ .themed::before { --gap: 3px; content: "*"; color: var(--accent); padding-left: var(--gap); }
+ li::marker { color: rgb(0, 0, 120); width: 100px; padding-left: 7px; }
+ .not-a-list-item::marker { color: red; }
+ .no-marker::marker { content: none; color: red; }
+</style>
+<p class="quoted">quoted</p>
+<p class="quoted">quoted again</p>
+<p class="empty normal">no generated content</p>
+<p class="themed">themed</p>
+<ul><li>one</li><li>two</li><li class="no-marker">three</li></ul>
+<div class="not-a-list-item">not a list item</div>
+<script src="../../include.js"></script>
+<script>
+ test(() => {
+ internals.updateStyle();
+ const report = internals.styleColdPass();
+ println(`computed every styled element: ${report.computedElements == report.elements}`);
+ println(`pseudo-elements: ${report.pseudoElements}`);
+ println(`differences: ${report.differences}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/cold-pass-registered-properties.html b/Tests/LibWeb/Text/input/css/style-engine/cold-pass-registered-properties.html
new file mode 100644
index 00000000000..da25c947c4b
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/style-engine/cold-pass-registered-properties.html
@@ -0,0 +1,19 @@
+<!DOCTYPE html>
+<style>
+ @property --kept { syntax: "*"; inherits: false; initial-value: 3px; }
+ @property --passed { syntax: "*"; inherits: true; initial-value: 5px; }
+ .outer { --kept: 11px; --passed: 13px; padding-left: var(--kept); padding-right: var(--passed); }
+ .inner { margin-left: var(--kept); margin-right: var(--passed); }
+ .declares { --kept: 17px; border-left: var(--kept) solid; }
+</style>
+<div class="outer"><div class="inner">inner</div><div class="inner declares">declares</div></div>
+<div class="inner">top level</div>
+<script src="../../include.js"></script>
+<script>
+ test(() => {
+ internals.updateStyle();
+ const report = internals.styleColdPass();
+ println(`computed every styled element: ${report.computedElements == report.elements}`);
+ println(`differences: ${report.differences}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/cold-pass-reuse.html b/Tests/LibWeb/Text/input/css/style-engine/cold-pass-reuse.html
new file mode 100644
index 00000000000..4998706836c
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/style-engine/cold-pass-reuse.html
@@ -0,0 +1,29 @@
+<!DOCTYPE html>
+<style>
+ .box { padding: 1px; }
+ .a .label { color: rgb(1, 2, 3); }
+ .b .label { color: rgb(4, 5, 6); }
+ .framed { border: 2px solid rgb(200, 0, 0); }
+ .inherits { border: inherit; margin: 3px; }
+ .contents { display: contents; }
+ .grid { display: grid; }
+</style>
+<div class="box a"><span class="label">a</span><span class="label">a</span></div>
+<div class="box b"><span class="label">b</span><span class="label">b</span></div>
+<div class="framed"><p class="inherits">framed</p></div>
+<div><p class="inherits">plain</p></div>
+<div class="grid"><span class="box">grid item</span></div>
+<div class="contents"><span class="box">contents child</span></div>
+<div style="margin: 1px"><div style="margin: 1px"><div style="margin: 1px"><div style="margin: 1px">
+ <div style="margin: 1px"><div style="margin: 1px">deep</div></div>
+</div></div></div></div>
+<script src="../../include.js"></script>
+<script>
+ test(() => {
+ internals.updateStyle();
+ const report = internals.styleColdPass();
+ println(`computed every styled element: ${report.computedElements == report.elements}`);
+ println(`reused some elements: ${report.reusedElements > 0}`);
+ println(`differences: ${report.differences}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/cold-pass-sharing.html b/Tests/LibWeb/Text/input/css/style-engine/cold-pass-sharing.html
new file mode 100644
index 00000000000..58e57d4491c
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/style-engine/cold-pass-sharing.html
@@ -0,0 +1,39 @@
+<!DOCTYPE html>
+<style>
+ .item { color: rgb(1, 2, 3); padding: 2px; }
+ .item[data-on] { color: rgb(200, 0, 0); }
+ .item:nth-child(3n) { margin-left: 5px; }
+ .item + .item { border-top: 1px solid black; }
+ .item:first-child { font-weight: bold; }
+ #named { background-color: rgb(0, 100, 0); }
+ .group[data-wide] .item { width: 50px; }
+ .group:has(.marker) .item { height: 7px; }
+ .item:empty { display: inline-block; }
+ li { list-style-type: square; }
+ li:nth-child(2n + 1 of .odd) { text-indent: 3px; }
+ li:hover { outline: 1px solid red; }
+</style>
+<div class="group">
+ <span class="item">a</span><span class="item">b</span><span class="item" data-on>c</span>
+ <span class="item">d</span><span class="item" id="named">e</span><span class="item" id="untested">f</span>
+ <span class="item" style="padding: 9px">g</span><span class="item"></span><span class="item">h</span>
+</div>
+<div class="group" data-wide>
+ <span class="item">a</span><span class="item">b</span><span class="item">c</span>
+</div>
+<div class="group">
+ <span class="item">a</span><span class="item">b</span><span class="marker"></span>
+</div>
+<ul>
+ <li class="odd">1</li><li>2</li><li class="odd">3</li><li class="odd">4</li><li>5</li><li class="odd">6</li>
+</ul>
+<script src="../../include.js"></script>
+<script>
+ test(() => {
+ internals.updateStyle();
+ const report = internals.styleColdPass();
+ println(`computed every styled element: ${report.computedElements == report.elements}`);
+ println(`shared some elements: ${report.sharedElements > 0}`);
+ println(`differences: ${report.differences}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/cold-pass-substitution.html b/Tests/LibWeb/Text/input/css/style-engine/cold-pass-substitution.html
new file mode 100644
index 00000000000..0673aa9cd43
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/style-engine/cold-pass-substitution.html
@@ -0,0 +1,20 @@
+<!DOCTYPE html>
+<style>
+ :root { --main: rgb(10, 20, 30); --gap: 4px; --border: 1px solid var(--main); --unset-me: 1px; }
+ body { color: var(--main); font-family: var(--family, sans-serif); }
+ .card { border: var(--border); margin: var(--gap) calc(var(--gap) * 2); --unset-me: initial; }
+ .inner { padding: var(--unset-me, 3px); --main: inherit; background-color: var(--main); }
+ .invalid { width: var(--missing); height: var(--gap); }
+ details > p { border-radius: var(--gap); }
+</style>
+<div class="card"><div class="inner">inner</div><span class="invalid">invalid</span></div>
+<details open><summary>summary</summary><p>slotted</p></details>
+<script src="../../include.js"></script>
+<script>
+ test(() => {
+ internals.updateStyle();
+ const report = internals.styleColdPass();
+ println(`computed every styled element: ${report.computedElements == report.elements}`);
+ println(`differences: ${report.differences}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/cold-pass-zoom.html b/Tests/LibWeb/Text/input/css/style-engine/cold-pass-zoom.html
new file mode 100644
index 00000000000..d0e32c63035
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/style-engine/cold-pass-zoom.html
@@ -0,0 +1,16 @@
+<!DOCTYPE html>
+<style>
+ .zoomed { zoom: 2; }
+ .boxed { padding: 1em; border: 2px solid; }
+</style>
+<div class="zoomed"><span class="boxed">zoomed</span><span>plain</span></div>
+<div class="boxed">unzoomed</div>
+<script src="../../include.js"></script>
+<script>
+ test(() => {
+ internals.updateStyle();
+ const report = internals.styleColdPass();
+ println(`computed every styled element: ${report.computedElements == report.elements}`);
+ println(`differences: ${report.differences}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/engine-computed-cold-subtree-records.html b/Tests/LibWeb/Text/input/css/style-engine/computed-cold-subtree-records.html
similarity index 65%
rename from Tests/LibWeb/Text/input/css/style-engine/engine-computed-cold-subtree-records.html
rename to Tests/LibWeb/Text/input/css/style-engine/computed-cold-subtree-records.html
index f8bc4a7d1a1..69b6023cd60 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/engine-computed-cold-subtree-records.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/computed-cold-subtree-records.html
@@ -13,19 +13,10 @@
test(() => {
internals.updateStyle();
const host = document.getElementById("host");
- const counters = () => Object.assign({}, internals.styleEngineCounters(), internals.getStyleInvalidationCounters());
- let before = counters();
- const report = (label) => {
- internals.updateStyle();
- const after = counters();
- const delta = (key) => (after[key] ?? 0) - (before[key] ?? 0);
- println(`${label}: engine records ${delta("engineComputedStyleRecords")}, C++ recomputations ${delta("elementStyleRecomputations")}`);
- before = after;
- };
host.innerHTML = `<div class="a"><div class="b"><p>one <span class="c">two</span> <em>three</em></p></div><section class="k"><h1>t</h1><p>p</p><p class="b">q</p></section></div>`;
- report("append subtree");
+ internals.updateStyle();
host.innerHTML = `<div class="b"><div class="a"><p>one <span>two</span> <em class="c">three</em></p></div></div>`;
- report("replace subtree");
+ internals.updateStyle();
println(`em color: ${getComputedStyle(document.querySelector("em")).color}`);
println(`p font size: ${getComputedStyle(document.querySelector("p")).fontSize}`);
println(`::before content: ${getComputedStyle(document.querySelector("em"), "::before").content}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/engine-computed-document-element-records.html b/Tests/LibWeb/Text/input/css/style-engine/computed-document-element-records.html
similarity index 59%
rename from Tests/LibWeb/Text/input/css/style-engine/engine-computed-document-element-records.html
rename to Tests/LibWeb/Text/input/css/style-engine/computed-document-element-records.html
index 9bf2a55fb98..11f1a9da6e3 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/engine-computed-document-element-records.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/computed-document-element-records.html
@@ -12,16 +12,10 @@
// `rem` resolves against: the engine computes its records, first and later, and the
// records under it in the same flush.
test(() => {
- const counters = () => Object.assign({}, internals.styleEngineCounters(), internals.getStyleInvalidationCounters());
- let before = {};
const report = (label) => {
internals.updateStyle();
- const after = counters();
- const delta = (key) => (after[key] ?? 0) - (before[key] ?? 0);
const html = getComputedStyle(document.documentElement);
- println(`${label}: engine records ${delta("engineComputedStyleRecords")}, C++ recomputations ${delta("elementStyleRecomputations")}`);
- println(` html font-size ${html.fontSize}, padding ${html.paddingTop}, margin ${html.marginTop}, 2rem width ${getComputedStyle(document.querySelector("p.r")).width}`);
- before = after;
+ println(`${label}: html font-size ${html.fontSize}, padding ${html.paddingTop}, margin ${html.marginTop}, 2rem width ${getComputedStyle(document.querySelector("p.r")).width}`);
};
report("load");
for (const className of ["big", "big pad", "pad", ""]) {
diff --git a/Tests/LibWeb/Text/input/css/style-engine/engine-computed-pseudo-element-records.html b/Tests/LibWeb/Text/input/css/style-engine/computed-pseudo-element-records.html
similarity index 82%
rename from Tests/LibWeb/Text/input/css/style-engine/engine-computed-pseudo-element-records.html
rename to Tests/LibWeb/Text/input/css/style-engine/computed-pseudo-element-records.html
index 68f0bf9fd83..c9638f83417 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/engine-computed-pseudo-element-records.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/computed-pseudo-element-records.html
@@ -19,9 +19,6 @@
const after = () => getComputedStyle(target, "::after");
const marker = () => getComputedStyle(target, "::marker");
internals.updateStyle();
- const start = internals.styleEngineCounters();
- const recomputes = () => internals.getStyleInvalidationCounters().elementStyleRecomputations;
- const startRecomputes = recomputes();
target.className = "a";
internals.updateStyle();
@@ -54,9 +51,5 @@
second.className = "b";
internals.updateStyle();
println(`second b: before content ${getComputedStyle(second, "::before").content}`);
-
- const end = internals.styleEngineCounters();
- println(`engine pseudo records: ${end.engineComputedPseudoRecords - start.engineComputedPseudoRecords}`);
- println(`C++ recomputations: ${recomputes() - startRecomputes}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/content-and-anchor-name-engine-computed.html b/Tests/LibWeb/Text/input/css/style-engine/content-and-anchor-name.html
similarity index 80%
rename from Tests/LibWeb/Text/input/css/style-engine/content-and-anchor-name-engine-computed.html
rename to Tests/LibWeb/Text/input/css/style-engine/content-and-anchor-name.html
index e8824586e34..45b2143345e 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/content-and-anchor-name-engine-computed.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/content-and-anchor-name.html
@@ -14,8 +14,7 @@
</style>
<script>
// Each case is switched on once in a new element, whose first record computes it, and once
- // in an element that already has a record. Each line prints how often the style engine
- // refused a property or a value and how many elements C++ computed instead.
+ // in an element that already has a record. Each line prints the value it computes to.
const cases = [
["image content", "image-content", null, "content"],
["counter(x, decimal)", "decimal-counter", "::before", "content"],
@@ -34,16 +33,12 @@
}
function measure(name, target, pseudo, property, change) {
- const before = Object.assign({}, internals.styleEngineCounters());
- internals.resetStyleInvalidationCounters();
change();
internals.updateStyle();
- const after = internals.styleEngineCounters();
- const recomputations = internals.getStyleInvalidationCounters().elementStyleRecomputations;
let value = getComputedStyle(target, pseudo).getPropertyValue(property);
if (value.startsWith("url("))
value = "an image";
- println(`${name}: property refusals ${after.engineComputedRecordBailProperty - before.engineComputedRecordBailProperty}, value refusals ${after.engineComputedRecordBailValue - before.engineComputedRecordBailValue}, C++ recomputations ${recomputations}, value ${value}`);
+ println(`${name}: value ${value}`);
}
test(() => {
diff --git a/Tests/LibWeb/Text/input/css/style-engine/custom-function-body-change-engine-computed.html b/Tests/LibWeb/Text/input/css/style-engine/custom-function-body-change.html
similarity index 63%
rename from Tests/LibWeb/Text/input/css/style-engine/custom-function-body-change-engine-computed.html
rename to Tests/LibWeb/Text/input/css/style-engine/custom-function-body-change.html
index 72a36930cd7..2aeea406b11 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/custom-function-body-change-engine-computed.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/custom-function-body-change.html
@@ -7,18 +7,14 @@
</style>
<div id="target"></div>
<script>
- // An element and its ::before call a custom function whose body changes. Count who computes the
- // element's record again, and check both take the new result.
+ // An element and its ::before call a custom function whose body changes. Check both take the
+ // new result.
test(() => {
internals.updateStyle();
const sheet = document.getElementById("definitions").sheet;
- const before = internals.getStyleInvalidationCounters();
sheet.deleteRule(0);
sheet.insertRule("@function --size() { result: 20px; }");
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`engine records: ${after.engineComputedStyleRecords - before.engineComputedStyleRecords}`);
- println(`C++ recomputations: ${after.elementStyleRecomputations - before.elementStyleRecomputations}`);
println(`element width: ${getComputedStyle(target).width}`);
println(`::before width: ${getComputedStyle(target, "::before").width}`);
});
diff --git a/Tests/LibWeb/Text/input/css/style-engine/custom-function-conditions-engine-computed.html b/Tests/LibWeb/Text/input/css/style-engine/custom-function-conditions.html
similarity index 100%
rename from Tests/LibWeb/Text/input/css/style-engine/custom-function-conditions-engine-computed.html
rename to Tests/LibWeb/Text/input/css/style-engine/custom-function-conditions.html
diff --git a/Tests/LibWeb/Text/input/css/style-engine/font-carried-longhand-engine-computed.html b/Tests/LibWeb/Text/input/css/style-engine/font-carried-longhand.html
similarity index 65%
rename from Tests/LibWeb/Text/input/css/style-engine/font-carried-longhand-engine-computed.html
rename to Tests/LibWeb/Text/input/css/style-engine/font-carried-longhand.html
index a9083351ee1..1669c8e6001 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/font-carried-longhand-engine-computed.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/font-carried-longhand.html
@@ -8,8 +8,7 @@
<div class="text-rendering" id="text-rendering">text</div>
<script>
// A longhand the font group carries, switched on in an element that already has a record. Each
- // line prints how many records the style engine computed, how many elements C++ computed, and
- // the value.
+ // line prints the value.
const cases = [
["font-feature-settings", "feature-settings", "font-feature-settings"],
["text-rendering", "text-rendering", "text-rendering"],
@@ -19,11 +18,9 @@
for (const [name, id, property] of cases) {
const target = document.getElementById(id);
internals.updateStyle();
- internals.resetStyleInvalidationCounters();
target.classList.add("on");
internals.updateStyle();
- const counters = internals.getStyleInvalidationCounters();
- println(`${name}: engine records ${counters.engineComputedStyleRecords}, C++ recomputations ${counters.elementStyleRecomputations}, value ${getComputedStyle(target).getPropertyValue(property)}`);
+ println(`${name}: value ${getComputedStyle(target).getPropertyValue(property)}`);
}
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/font-feature-values-edit-engine-computed.html b/Tests/LibWeb/Text/input/css/style-engine/font-feature-values-edit.html
similarity index 60%
rename from Tests/LibWeb/Text/input/css/style-engine/font-feature-values-edit-engine-computed.html
rename to Tests/LibWeb/Text/input/css/style-engine/font-feature-values-edit.html
index 7f463e01a1a..b5de749197a 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/font-feature-values-edit-engine-computed.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/font-feature-values-edit.html
@@ -8,15 +8,11 @@
<div id="plain">plain</div>
<script>
// An edit to a @font-feature-values rule moves the feature values every font resolution reads.
- // Count who computes the records it reaches, and check the alternates still name the feature.
+ // Check the alternates still name the feature.
test(() => {
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
document.styleSheets[0].cssRules[0].styleset.set("fancy", 2);
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`engine computed records: ${after.engineComputedStyleRecords - before.engineComputedStyleRecords > 0}`);
- println(`C++ recomputations: ${after.elementStyleRecomputations - before.elementStyleRecomputations}`);
println(`font-variant-alternates: ${getComputedStyle(document.getElementById("alternates")).fontVariantAlternates}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/font-waits-resolve-within-pass.html b/Tests/LibWeb/Text/input/css/style-engine/font-waits-resolve-within-pass.html
new file mode 100644
index 00000000000..c17139e0a84
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/style-engine/font-waits-resolve-within-pass.html
@@ -0,0 +1,38 @@
+<!DOCTYPE html>
+<script src="../../include.js"></script>
+<style>
+ .level {
+ font-family: monospace;
+ }
+
+ .level::before {
+ content: "b";
+ font-family: serif;
+ }
+</style>
+<div id="host"></div>
+<script>
+ test(() => {
+ internals.updateStyle();
+
+ // Each level asks for a font size no element asked for before, which the style engine
+ // resolves once an element waits on it.
+ const host = document.getElementById("host");
+ let parent = host;
+ for (let level = 0; level < 6; ++level) {
+ const element = document.createElement("div");
+ element.className = "level";
+ element.style.fontSize = `${11.25 + level * 1.5}px`;
+ element.textContent = "x";
+ parent.appendChild(element);
+ parent = element;
+ }
+
+ internals.resetStyleCounters();
+ internals.updateStyle();
+ const counters = internals.styleCounters();
+ println(`passes: ${counters.passes}`);
+ println(`elements styled: ${counters.styledElements}`);
+ println(`deepest font size: ${getComputedStyle(parent).fontSize}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/published-answer-identity-reuses-cascade-input.html b/Tests/LibWeb/Text/input/css/style-engine/identical-style-reuses-cascade-input.html
similarity index 59%
rename from Tests/LibWeb/Text/input/css/style-engine/published-answer-identity-reuses-cascade-input.html
rename to Tests/LibWeb/Text/input/css/style-engine/identical-style-reuses-cascade-input.html
index f2672e2f612..e6a32b6234a 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/published-answer-identity-reuses-cascade-input.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/identical-style-reuses-cascade-input.html
@@ -11,16 +11,11 @@
const second = document.getElementById("second");
internals.updateStyle();
- const before = internals.styleEngineCounters();
first.classList.add("active");
second.classList.add("active");
internals.updateStyle();
- const after = internals.styleEngineCounters();
println(`first color: ${getComputedStyle(first).color}`);
println(`second color: ${getComputedStyle(second).color}`);
- println(`published answers: ${after.publishedMatchAnswerRecords - before.publishedMatchAnswerRecords}`);
- println(`engine records: ${after.engineComputedRecordDeltas - before.engineComputedRecordDeltas}`);
- println(`shared payloads: ${after.publishedMatchAnswerSharedPayloads - before.publishedMatchAnswerSharedPayloads}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/inherited-color-mix-resolves-against-own-color.html b/Tests/LibWeb/Text/input/css/style-engine/inherited-color-mix-resolves-against-own-color.html
new file mode 100644
index 00000000000..0feb1b490a3
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/style-engine/inherited-color-mix-resolves-against-own-color.html
@@ -0,0 +1,40 @@
+<!DOCTYPE html>
+<style>
+ :root {
+ color: rgb(10, 10, 10);
+ scrollbar-color: color-mix(in srgb, currentColor 50%, #0000) #0000;
+ caret-color: color-mix(in srgb, currentColor 50%, #0000);
+ accent-color: color-mix(in srgb, currentColor 50%, #0000);
+ fill: color-mix(in srgb, currentColor 50%, #0000);
+ stroke: color-mix(in srgb, currentColor 50%, #0000);
+ }
+ .same { cursor: pointer; stroke-width: 2px; }
+ #first { color: rgb(200, 0, 0); }
+ #second { color: rgb(0, 200, 0); }
+ #third { color: rgb(0, 0, 200); }
+ .moved { cursor: help; stroke-width: 3px; }
+</style>
+<div class="same" id="first">first</div>
+<div class="same" id="second">second</div>
+<div id="third">third</div>
+<script src="../../include.js"></script>
+<script>
+ // Each elements scrollbar, caret, accent, fill and stroke colors read that elements own color, although none of
+ // them declares those colors. The elements hold groups no other element of a different color may share.
+ asyncTest(async done => {
+ const frames = () => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
+ const report = label => println(`${label}: differences from a cold pass: ${internals.styleColdPass().differences}`);
+ await frames();
+ report("start");
+ third.classList.add("moved");
+ await frames();
+ report("third moved");
+ first.classList.add("moved");
+ await frames();
+ report("first moved");
+ third.classList.remove("moved");
+ await frames();
+ report("third back");
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/install-same-custom-property-values.html b/Tests/LibWeb/Text/input/css/style-engine/install-same-custom-property-values.html
new file mode 100644
index 00000000000..47866255e2e
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/style-engine/install-same-custom-property-values.html
@@ -0,0 +1,55 @@
+<!DOCTYPE html>
+<style>
+ @property --local {
+ syntax: "*";
+ inherits: false;
+ }
+ .root { --shared: 2px; }
+ .holder { --local: 1; }
+ .first { color: rgb(1, 0, 0); width: 11px; }
+ .second { color: rgb(2, 0, 0); width: 12px; }
+ .third { color: rgb(3, 0, 0); width: 13px; }
+ .fourth { color: rgb(4, 0, 0); width: 14px; }
+ .fifth { color: rgb(5, 0, 0); width: 15px; }
+</style>
+<div class="root"><div class="holder" id="holder"></div></div>
+<script src="../../include.js"></script>
+<script>
+ test(() => {
+ const holder = document.getElementById("holder");
+ const styles = {
+ first: "rgb(1, 0, 0) 11px",
+ second: "rgb(2, 0, 0) 12px",
+ third: "rgb(3, 0, 0) 13px",
+ fourth: "rgb(4, 0, 0) 14px",
+ fifth: "rgb(5, 0, 0) 15px",
+ };
+ const names = Object.keys(styles);
+ const read = (label) => {
+ let wrong = 0;
+ for (const child of holder.children) {
+ const style = getComputedStyle(child);
+ if (`${style.color} ${style.width}` !== styles[child.classList[0]]) wrong++;
+ }
+ const cold = internals.styleColdPass(true);
+ println(`${label}: ${holder.children.length} children, ${wrong} with the style of another`);
+ println(`${label}: ${cold.differences} installed differently from a cold pass`);
+ };
+ internals.updateStyle();
+
+ // The holder hands down nothing its parent does not, so its children inherit their parent's environment, each
+ // in a record of its own that gives way to an installed one holding the same style. Their styles must stay
+ // their own, as many records come and go through one installation.
+ for (let i = 0; i < 600; ++i) {
+ const child = document.createElement("div");
+ child.className = names[(i * i + i) % names.length];
+ holder.appendChild(child);
+ }
+ internals.updateStyle();
+ read("inserted");
+
+ for (const child of holder.children) child.classList.add("again");
+ internals.updateStyle();
+ read("restyled");
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/losing-context-uses-retained-winners.html b/Tests/LibWeb/Text/input/css/style-engine/losing-context-winners.html
similarity index 61%
rename from Tests/LibWeb/Text/input/css/style-engine/losing-context-uses-retained-winners.html
rename to Tests/LibWeb/Text/input/css/style-engine/losing-context-winners.html
index 4a8d3117bda..6a8e1124b2f 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/losing-context-uses-retained-winners.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/losing-context-winners.html
@@ -17,15 +17,9 @@
root.lastElementChild.id = "sentinel";
internals.updateStyle();
- const before = internals.styleEngineCounters();
root.classList.add("boost");
internals.updateStyle();
- const after = internals.styleEngineCounters();
- const losingSelectorsRejected = after.selectorRoutesRejectedByCascade - before.selectorRoutesRejectedByCascade
- + after.prefixRelationCascadeStops - before.prefixRelationCascadeStops;
- println(`losing selector rejected: ${losingSelectorsRejected > 0}`);
- println(`only sentinel invalidated: ${after.invalidatedStyleNodes - before.invalidatedStyleNodes === 1}`);
println(`ordinary item: ${getComputedStyle(root.firstElementChild).color}`);
println(`sentinel: ${getComputedStyle(root.lastElementChild).outlineColor}`);
});
diff --git a/Tests/LibWeb/Text/input/css/style-engine/mathml-hint-change-engine-computed.html b/Tests/LibWeb/Text/input/css/style-engine/mathml-hint-change.html
similarity index 55%
rename from Tests/LibWeb/Text/input/css/style-engine/mathml-hint-change-engine-computed.html
rename to Tests/LibWeb/Text/input/css/style-engine/mathml-hint-change.html
index 4f7b31ec746..2fbbc9f3d43 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/mathml-hint-change-engine-computed.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/mathml-hint-change.html
@@ -2,16 +2,13 @@
<script src="../../include.js"></script>
<math><mi id="identifier" mathcolor="green">x</mi></math>
<script>
- // A MathML element's hints are mapped from its own attributes, so they are published where the
- // attributes move and the engine computes the element's record against them.
+ // A MathML element's hints are mapped from its own attributes, so moving the attributes moves the
+ // element's computed values.
test(() => {
internals.updateStyle();
println(`color: ${getComputedStyle(identifier).color}`);
- const before = internals.getStyleInvalidationCounters();
identifier.setAttribute("mathcolor", "red");
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`hint change stays in the engine: ${after.elementStyleRecomputations - before.elementStyleRecomputations === 0}`);
println(`color: ${getComputedStyle(identifier).color}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/monospace-font-size-quirk-engine-computed.html b/Tests/LibWeb/Text/input/css/style-engine/monospace-font-size-quirk.html
similarity index 86%
rename from Tests/LibWeb/Text/input/css/style-engine/monospace-font-size-quirk-engine-computed.html
rename to Tests/LibWeb/Text/input/css/style-engine/monospace-font-size-quirk.html
index 2632a953f54..bce906b3dbc 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/monospace-font-size-quirk-engine-computed.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/monospace-font-size-quirk.html
@@ -18,12 +18,10 @@
// The element's own font-size declaration still wins over the recascaded value, so only an
// element that declares none takes it.
internals.updateStyle();
- const start = internals.getStyleInvalidationCounters().elementStyleRecomputations;
for (const id of ["outer", "own-size", "mono-parent", "inherits-mono", "keyword", "mono-under-keyword"])
println(`${id}: ${getComputedStyle(document.getElementById(id)).fontSize}`);
document.getElementById("keyword").style.color = "rgb(0, 0, 255)";
internals.updateStyle();
println(`recoloured mono-under-keyword: ${getComputedStyle(document.getElementById("mono-under-keyword")).fontSize}`);
- println(`C++ recomputations: ${internals.getStyleInvalidationCounters().elementStyleRecomputations - start}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/named-timeline-engine-computed.html b/Tests/LibWeb/Text/input/css/style-engine/named-timeline.html
similarity index 71%
rename from Tests/LibWeb/Text/input/css/style-engine/named-timeline-engine-computed.html
rename to Tests/LibWeb/Text/input/css/style-engine/named-timeline.html
index b2c5a3975ea..78490850d29 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/named-timeline-engine-computed.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/named-timeline.html
@@ -8,18 +8,14 @@
</style>
<div id="scroller"><div id="subject"></div></div>
<script>
- // A named timeline is a plain computed value: it starts nothing itself. Count who computes the
- // record of an element whose timeline names move.
+ // A named timeline is a plain computed value: it starts nothing itself. Move an element's timeline
+ // names and read them back.
test(() => {
function toggle(label, element, className, read) {
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
element.classList.toggle(className);
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
println(`${label}: ${read(getComputedStyle(element))}`);
- println(` engine records: ${after.engineComputedStyleRecords - before.engineComputedStyleRecords}`);
- println(` C++ recomputations: ${after.elementStyleRecomputations - before.elementStyleRecomputations}`);
}
const scroll = style => `${style.scrollTimelineName} ${style.scrollTimelineAxis}`;
const view = style => `${style.viewTimelineName} ${style.viewTimelineInset}`;
diff --git a/Tests/LibWeb/Text/input/css/style-engine/position-anchor-differs-with-shared-insets.html b/Tests/LibWeb/Text/input/css/style-engine/position-anchor-differs-with-shared-insets.html
new file mode 100644
index 00000000000..6dde0af84e0
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/style-engine/position-anchor-differs-with-shared-insets.html
@@ -0,0 +1,23 @@
+<!DOCTYPE html>
+<script src="../../include.js"></script>
+<style>
+ .cb { position: fixed; inset: 0; }
+ #a1 { anchor-name: --a1; position: absolute; top: 0; left: 0; width: 100px; height: 50px; }
+ #a2 { anchor-name: --a2; position: absolute; top: 200px; left: 300px; width: 100px; height: 50px; }
+ .target { position: absolute; width: 20px; height: 20px; top: anchor(bottom); left: anchor(left); }
+ #t2 { position-anchor: --a2; }
+</style>
+<div class="cb">
+ <div id="a1"></div>
+ <div id="a2"></div>
+ <div id="t1" class="target"></div>
+ <div id="t2" class="target"></div>
+</div>
+<script>
+ test(() => {
+ for (const id of ["t1", "t2"]) {
+ const t = document.getElementById(id).getBoundingClientRect();
+ println(`${id}: top: ${t.top} left: ${t.left}`);
+ }
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/presentational-hint-change-engine-computed.html b/Tests/LibWeb/Text/input/css/style-engine/presentational-hint-change.html
similarity index 60%
rename from Tests/LibWeb/Text/input/css/style-engine/presentational-hint-change-engine-computed.html
rename to Tests/LibWeb/Text/input/css/style-engine/presentational-hint-change.html
index 755b380767a..5528a1cf864 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/presentational-hint-change-engine-computed.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/presentational-hint-change.html
@@ -3,16 +3,12 @@
<div id="target" align="left">text</div>
<font id="font" color="red">text</font>
<script>
- // A presentational hint is published where its attribute moves, so the engine computes the
- // element's new style itself.
+ // A presentational hint follows its attribute when it moves.
test(() => {
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
document.getElementById("target").setAttribute("align", "right");
document.getElementById("font").setAttribute("color", "green");
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`no C++ recomputation: ${after.elementStyleRecomputations - before.elementStyleRecomputations === 0}`);
println(`text-align: ${getComputedStyle(document.getElementById("target")).textAlign}`);
println(`color: ${getComputedStyle(document.getElementById("font")).color}`);
});
diff --git a/Tests/LibWeb/Text/input/css/style-engine/retained-priority-change.html b/Tests/LibWeb/Text/input/css/style-engine/priority-change.html
similarity index 87%
rename from Tests/LibWeb/Text/input/css/style-engine/retained-priority-change.html
rename to Tests/LibWeb/Text/input/css/style-engine/priority-change.html
index 67ba847c14c..5d25b6fd2a8 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/retained-priority-change.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/priority-change.html
@@ -27,12 +27,9 @@
internals.updateStyle();
function reorder(label, sheets, opacity) {
- const before = internals.getStyleInvalidationCounters();
document.adoptedStyleSheets = sheets;
target.style.opacity = opacity;
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`${label} stays selective: ${after.elementStyleRecomputations - before.elementStyleRecomputations < 16}`);
println(`${label} color: ${getComputedStyle(target).color}`);
println(`${label} background: ${getComputedStyle(target).backgroundColor}`);
println(`${label} child color: ${getComputedStyle(child).color}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/pseudo-element-custom-properties-over-another-parent.html b/Tests/LibWeb/Text/input/css/style-engine/pseudo-element-custom-properties-over-another-parent.html
new file mode 100644
index 00000000000..0e616b5d0c6
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/style-engine/pseudo-element-custom-properties-over-another-parent.html
@@ -0,0 +1,50 @@
+<!DOCTYPE html>
+<script src="../../include.js"></script>
+<style>
+ @keyframes angle {
+ 0% { content: var(--text); --angle: 0deg; }
+ to { content: var(--text); --angle: 360deg; }
+ }
+ *, :before, :after { --text: ""; --stops: red, blue; }
+ .item { display: block; position: relative; background: white; border: 2px solid; --own: 1; }
+ .item.moved { border-color: transparent; color: red; --own: 2; }
+ .item:after {
+ content: var(--text);
+ display: block;
+ height: 10px;
+ background-image: linear-gradient(var(--angle, 90deg), var(--stops));
+ animation: angle 1000s infinite paused;
+ }
+ .item.moved:after { opacity: 1; }
+</style>
+<div id="list"><a class="item" id="first"></a><a class="item" id="second"></a></div>
+<script>
+ asyncTest(async done => {
+ // The two ::after share a store of custom properties, which the engine names as resolved over the environment it
+ // saw last. A pseudo-element whose inherited environment is another one still holds its declarations, or its
+ // animation samples over nothing and its content goes with --text.
+ const nextFrame = () => new Promise(resolve => requestAnimationFrame(resolve));
+ for (let i = 0; i < 5; ++i)
+ await nextFrame();
+ const animations = list.getAnimations({ subtree: true });
+ const heights = new Set();
+ for (let i = 0; i < 120; ++i) {
+ await nextFrame();
+ if (i % 5 === 0)
+ first.classList.toggle("moved");
+ if (i % 11 === 0)
+ document.documentElement.style.setProperty("--root", i);
+ if (i % 23 === 0)
+ first.style.color = i % 2 ? "blue" : "";
+ if (i % 4 === 0) {
+ for (const animation of animations)
+ animation.currentTime = i % 8 === 0 ? 100000 : 900000;
+ }
+ await nextFrame();
+ heights.add(`${first.offsetHeight}/${second.offsetHeight}`);
+ }
+ println(`animations: ${animations.length}`);
+ println(`heights: ${[...heights].join(", ")}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/registered-custom-property-engine-computed.html b/Tests/LibWeb/Text/input/css/style-engine/registered-custom-property.html
similarity index 82%
rename from Tests/LibWeb/Text/input/css/style-engine/registered-custom-property-engine-computed.html
rename to Tests/LibWeb/Text/input/css/style-engine/registered-custom-property.html
index d00d6407ee9..1051ed8d583 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/registered-custom-property-engine-computed.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/registered-custom-property.html
@@ -17,16 +17,11 @@
// A registered <length> declared in em computes against each declaring element's own font:
// two parents declaring the same value under different fonts hand their children different
// lengths, and a pseudo-element declaring one computes it against the pseudo-element's font.
- // Each line prints how many elements C++ computed for the change. The parents' change moves a
- // winner beside the custom property, which the engine drives; a rule declaring custom
- // properties for a pseudo-element alone still sends the element to C++.
function measure(name, change, values) {
internals.updateStyle();
- internals.resetStyleInvalidationCounters();
change();
internals.updateStyle();
- const recomputations = internals.getStyleInvalidationCounters().elementStyleRecomputations;
- println(`${name}: C++ recomputations ${recomputations}, ${values()}`);
+ println(`${name}: ${values()}`);
}
const widths = id => [...document.getElementById(id).querySelectorAll(".child")].map(child => getComputedStyle(child).width).join(" ");
diff --git a/Tests/LibWeb/Text/input/css/style-engine/root-font-face-load-engine-computed.html b/Tests/LibWeb/Text/input/css/style-engine/root-font-face-load.html
similarity index 68%
rename from Tests/LibWeb/Text/input/css/style-engine/root-font-face-load-engine-computed.html
rename to Tests/LibWeb/Text/input/css/style-engine/root-font-face-load.html
index 186047e40a6..e23dfeec45a 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/root-font-face-load-engine-computed.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/root-font-face-load.html
@@ -9,18 +9,13 @@
<div class="rlh" id="rlh"></div>
<script>
// The document element names a face that loads, and its children are sized in units that
- // resolve against the root's font inputs. Count who computes the records, and check each child
- // agrees with one computed from scratch against the loaded face.
+ // resolve against the root's font inputs. Check each child agrees with one computed from scratch against the loaded face.
promiseTest(async () => {
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
const face = new FontFace("RootFace", 'url("../../../../Assets/HashSans.woff")');
document.fonts.add(face);
await face.load();
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`engine computed records: ${after.engineComputedStyleRecords - before.engineComputedStyleRecords > 0}`);
- println(`C++ recomputations: ${after.elementStyleRecomputations - before.elementStyleRecomputations}`);
const fresh = className => {
const element = document.body.appendChild(document.createElement("div"));
element.className = className;
diff --git a/Tests/LibWeb/Text/input/css/style-engine/sampled-custom-property-own-var-engine-computed.html b/Tests/LibWeb/Text/input/css/style-engine/sampled-custom-property-own-var.html
similarity index 82%
rename from Tests/LibWeb/Text/input/css/style-engine/sampled-custom-property-own-var-engine-computed.html
rename to Tests/LibWeb/Text/input/css/style-engine/sampled-custom-property-own-var.html
index ad4220172f7..9dee49228f0 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/sampled-custom-property-own-var-engine-computed.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/sampled-custom-property-own-var.html
@@ -21,11 +21,8 @@
};
seek(500000);
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
target.classList.add("tinted");
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`C++ recomputations: ${after.elementStyleRecomputations - before.elementStyleRecomputations}`);
const style = getComputedStyle(target);
println(`width ${style.width}, z-index ${style.zIndex}, color ${style.color}`);
});
diff --git a/Tests/LibWeb/Text/input/css/style-engine/selection-observability-engine-computed.html b/Tests/LibWeb/Text/input/css/style-engine/selection-observability.html
similarity index 69%
rename from Tests/LibWeb/Text/input/css/style-engine/selection-observability-engine-computed.html
rename to Tests/LibWeb/Text/input/css/style-engine/selection-observability.html
index 887b7459d07..b0e8d250907 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/selection-observability-engine-computed.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/selection-observability.html
@@ -9,17 +9,12 @@
<script>
// Once a selection makes ::selection styles observable, every element in the selection is
// told its pseudo-element inputs may have changed. An unrelated change rides in the same
- // update. Count who computes the elements' records, and check the highlight pseudo-elements
- // are recomputed as each record installs.
+ // update. Check the highlight pseudo-elements are recomputed as each record installs.
test(() => {
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
getSelection().selectAllChildren(document.body);
document.getElementById("plain").classList.add("moved");
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`engine computed records: ${after.engineComputedStyleRecords - before.engineComputedStyleRecords > 0}`);
- println(`C++ recomputations: ${after.elementStyleRecomputations - before.elementStyleRecomputations}`);
const styled = getComputedStyle(document.getElementById("styled"), "::selection");
println(`styled ::selection: ${styled.color} on ${styled.backgroundColor}`);
const inner = getComputedStyle(document.getElementById("inner"), "::selection");
diff --git a/Tests/LibWeb/Text/input/css/style-engine/sibling-pseudo-elements-keep-their-own-animated-custom-properties.html b/Tests/LibWeb/Text/input/css/style-engine/sibling-pseudo-elements-keep-their-own-animated-custom-properties.html
new file mode 100644
index 00000000000..fd540ea4dc4
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/style-engine/sibling-pseudo-elements-keep-their-own-animated-custom-properties.html
@@ -0,0 +1,40 @@
+<!DOCTYPE html>
+<script src="../../include.js"></script>
+<style>
+ @keyframes angle {
+ from { --angle: 0deg; }
+ to { --angle: 360deg; }
+ }
+ .item { display: block; }
+ .moved .item { margin-left: 1px; }
+ .item::after {
+ content: "";
+ display: block;
+ height: 10px;
+ background-image: linear-gradient(var(--angle, 90deg), red, blue);
+ animation: angle 1000s infinite paused;
+ }
+</style>
+<div id="list"><a class="item" id="first"></a><a class="item" id="second"></a></div>
+<script>
+ asyncTest(async done => {
+ // The two elements match the same rules, so a restyle of both could share a style, but their ::after hold what
+ // their own animations sampled, which stand at different times.
+ const nextFrame = () => new Promise(resolve => requestAnimationFrame(resolve));
+ const angle = element => getComputedStyle(element, "::after").backgroundImage.slice("linear-gradient(".length).split(",")[0];
+ const report = label => println(`${label}: ${angle(first)}, ${angle(second)}`);
+ await nextFrame();
+ await nextFrame();
+ const [firstAnimation, secondAnimation] = list.getAnimations({ subtree: true });
+ firstAnimation.currentTime = 100000;
+ secondAnimation.currentTime = 900000;
+ await nextFrame();
+ await nextFrame();
+ report("sampled");
+ list.className = "moved";
+ await nextFrame();
+ await nextFrame();
+ report("restyled");
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/published-style-delta-gap.html b/Tests/LibWeb/Text/input/css/style-engine/style-change-gap.html
similarity index 50%
rename from Tests/LibWeb/Text/input/css/style-engine/published-style-delta-gap.html
rename to Tests/LibWeb/Text/input/css/style-engine/style-change-gap.html
index fe64c9e498a..cdcc910457b 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/published-style-delta-gap.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/style-change-gap.html
@@ -8,14 +8,10 @@
<script>
test(() => {
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
target.className = "after";
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`materialized gaps: ${after.styleEngineMaterializedGaps - before.styleEngineMaterializedGaps}`);
- println(`record deltas applied: ${after.styleEngineRecordDeltasApplied - before.styleEngineRecordDeltasApplied}`);
println(`color: ${getComputedStyle(target).color}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/published-style-delta-inherited-gap.html b/Tests/LibWeb/Text/input/css/style-engine/style-change-inherited-gap.html
similarity index 62%
rename from Tests/LibWeb/Text/input/css/style-engine/published-style-delta-inherited-gap.html
rename to Tests/LibWeb/Text/input/css/style-engine/style-change-inherited-gap.html
index 47ca84f3ad2..a7c518531eb 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/published-style-delta-inherited-gap.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/style-change-inherited-gap.html
@@ -10,15 +10,9 @@
const parentElement = document.getElementById("parent");
const childElement = document.getElementById("child");
internals.updateStyle();
- internals.resetStyleInvalidationCounters();
parentElement.className = "after";
internals.updateStyle();
-
- const counters = internals.getStyleInvalidationCounters();
println(`child list position: ${getComputedStyle(childElement).listStylePosition}`);
- println(`materialized gaps: ${counters.styleEngineMaterializedGaps}`);
- println(`record deltas applied: ${counters.styleEngineRecordDeltasApplied}`);
- println(`longhand evaluations: ${counters.computedLonghandEvaluations}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/style-counters-report-work.html b/Tests/LibWeb/Text/input/css/style-engine/style-counters-report-work.html
new file mode 100644
index 00000000000..f8f5a1eb1bb
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/style-engine/style-counters-report-work.html
@@ -0,0 +1,71 @@
+<!DOCTYPE html>
+<script src="../../include.js"></script>
+<style>
+ @keyframes grow {
+ from { width: 10px; }
+ to { width: 110px; }
+ }
+ #animated {
+ height: 10px;
+ animation: grow 10s linear infinite;
+ }
+ .on {
+ color: green;
+ }
+</style>
+<div id="list">
+ <span id="target"></span>
+ <span id="sibling"></span>
+ <span></span>
+</div>
+<div id="animated"></div>
+<script>
+ asyncTest(async done => {
+ internals.updateStyle();
+
+ internals.resetStyleCounters();
+ let counters = internals.styleCounters();
+ println(`keys: ${Object.keys(counters).join(", ")}`);
+ println(`reset zeroes every counter: ${Object.values(counters).every(value => value === 0)}`);
+
+ // A class change restyles the element it is on, and nothing beside it.
+ target.classList.add("on");
+ internals.updateStyle();
+ counters = internals.styleCounters();
+ println(`one pass: ${counters.passes === 1}`);
+ println(`no full pass: ${counters.fullPasses === 0}`);
+ println(`styled <= 1: ${counters.styledElements >= 1 && counters.styledElements <= 1}`);
+ println(`changed <= styled: ${counters.changedElements <= counters.styledElements}`);
+ println(`hinted <= 1: ${counters.hintedElements >= 1 && counters.hintedElements <= 1}`);
+ println(`no cold pass or index build: ${counters.coldPasses === 0 && counters.indexBuilds === 0}`);
+
+ const lastPass = internals.styleLastPass();
+ println(`last pass full: ${lastPass.fullPass}`);
+ println(`last pass styled: [${lastPass.styled.join(", ")}]`);
+ println(`last pass changed: [${lastPass.changed.join(", ")}]`);
+
+ internals.resetStyleCounters();
+ counters = internals.styleCounters();
+ println(`reset zeroes every counter again: ${Object.values(counters).every(value => value === 0)}`);
+ println(`reset forgets the last pass: ${internals.styleLastPass().styled.length === 0}`);
+
+ // Sampling the running animation composes it over the record of its element.
+ await new Promise(requestAnimationFrame);
+ internals.resetStyleInvalidationCounters();
+ await new Promise(requestAnimationFrame);
+ animated.getBoundingClientRect();
+ println(`animation sample composed: ${internals.getStyleInvalidationCounters().animatedStyleOverlayBuilds > 0}`);
+
+ // A stylesheet change restyles the elements its rules match, from a rule index updated in place.
+ const style = document.createElement("style");
+ style.textContent = "#sibling { color: blue; }";
+ document.head.appendChild(style);
+ internals.updateStyle();
+ counters = internals.styleCounters();
+ println(`stylesheet change: no full pass ${counters.fullPasses === 0}, no index build ${counters.indexBuilds === 0}, entries ${counters.indexedEntries >= 1}`);
+ println(`stylesheet change last pass targeted: ${!internals.styleLastPass().fullPass}`);
+ println(`stylesheet change changed sibling: ${internals.styleLastPass().changed.includes("sibling")}`);
+
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/substituted-url-image-engine-computed.html b/Tests/LibWeb/Text/input/css/style-engine/substituted-url-image.html
similarity index 77%
rename from Tests/LibWeb/Text/input/css/style-engine/substituted-url-image-engine-computed.html
rename to Tests/LibWeb/Text/input/css/style-engine/substituted-url-image.html
index 557fa3df1fa..ea491aa9ad2 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/substituted-url-image-engine-computed.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/substituted-url-image.html
@@ -9,7 +9,7 @@
<div id="container"></div>
<script>
// A url() a var() substitutes resolves against the sheet of the declaration that used the
- // var(), as a written one does. The engine knows that sheet, so it computes these records.
+ // var(), as a written one does.
test(() => {
const nodes = [];
for (const kind of ["local", "imported"]) {
@@ -21,12 +21,9 @@
}
}
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
for (const node of nodes)
node.classList.add("moved");
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`engine computed the image records: ${after.engineComputedStyleRecords - before.engineComputedStyleRecords >= nodes.length}`);
const directory = new URL(".", location.href).href;
for (const kind of ["local", "imported"]) {
const values = new Set(nodes.filter(node => node.classList.contains(kind)).map(node => getComputedStyle(node).backgroundImage.replace(directory, "")));
diff --git a/Tests/LibWeb/Text/input/css/style-engine/substitution-sources-engine-computed.html b/Tests/LibWeb/Text/input/css/style-engine/substitution-sources.html
similarity index 82%
rename from Tests/LibWeb/Text/input/css/style-engine/substitution-sources-engine-computed.html
rename to Tests/LibWeb/Text/input/css/style-engine/substitution-sources.html
index e3ef7bb1d15..ebda1b26133 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/substitution-sources-engine-computed.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/substitution-sources.html
@@ -24,8 +24,7 @@
</style>
<script>
// One reader of each substitution source, switched on in an element that already has a record.
- // Each line prints how often the style engine refused the reader's record and how many elements
- // C++ computed instead.
+ // Each line prints the value the reader computed to.
const cases = [
["inherit() in a custom property", "inherit-custom-property", "--b"],
["inherit() in a longhand", "inherit-longhand", "width"],
@@ -58,16 +57,12 @@
cases.forEach(([name, , property], index) => {
const target = targets[index];
- const before = Object.assign({}, internals.styleEngineCounters());
- internals.resetStyleInvalidationCounters();
target.classList.add("on");
internals.updateStyle();
- const after = internals.styleEngineCounters();
- const recomputations = internals.getStyleInvalidationCounters().elementStyleRecomputations;
let value = getComputedStyle(target).getPropertyValue(property);
if (name.startsWith("random()"))
value = /^\d+(\.\d+)?px$/.test(value) ? "a length" : value;
- println(`${name}: substitution refusals ${after.engineComputedRecordBailSubstitution - before.engineComputedRecordBailSubstitution}, environment refusals ${after.engineCustomPropertyEnvironmentBails - before.engineCustomPropertyEnvironmentBails}, C++ recomputations ${recomputations}, value ${value}`);
+ println(`${name}: value ${value}`);
});
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/published-substitution-usage.html b/Tests/LibWeb/Text/input/css/style-engine/substitution-usage.html
similarity index 75%
rename from Tests/LibWeb/Text/input/css/style-engine/published-substitution-usage.html
rename to Tests/LibWeb/Text/input/css/style-engine/substitution-usage.html
index daa7f7dea86..43f397478c3 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/published-substitution-usage.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/substitution-usage.html
@@ -8,13 +8,10 @@
<script>
test(() => {
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
// The parent needs C++ computation before its child can get an engine record.
host.innerHTML = '<div class="unsupported"><div class="variable"></div></div>';
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
const child = host.querySelector(".variable");
- println(`child uses an engine record: ${after.engineComputedStyleRecords > before.engineComputedStyleRecords}`);
println(`retried width: ${getComputedStyle(child).width}`);
CSS.registerProperty({ name: "--retried", syntax: "<length>", inherits: false, initialValue: "20px" });
println(`registered width: ${getComputedStyle(child).width}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/url-image-winners-engine-computed.html b/Tests/LibWeb/Text/input/css/style-engine/url-image-winners.html
similarity index 80%
rename from Tests/LibWeb/Text/input/css/style-engine/url-image-winners-engine-computed.html
rename to Tests/LibWeb/Text/input/css/style-engine/url-image-winners.html
index e174932492d..a3836666112 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/url-image-winners-engine-computed.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/url-image-winners.html
@@ -8,7 +8,7 @@
<div id="container"></div>
<script>
// An image written in a sheet resolves against that sheet's base URL, and one in a style
- // attribute against the document's. The engine knows both, so it computes these records.
+ // attribute against the document's.
test(() => {
const nodes = [];
for (const kind of ["local", "imported", "attribute"]) {
@@ -24,12 +24,9 @@
}
}
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
for (const node of nodes)
node.classList.add("moved");
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`engine computed the image records: ${after.engineComputedStyleRecords - before.engineComputedStyleRecords >= nodes.length}`);
const directory = new URL(".", location.href).href;
for (const kind of ["local", "imported", "attribute"]) {
const values = new Set(nodes.filter(node => node.dataset.kind === kind).map(node => getComputedStyle(node).backgroundImage.replace(directory, "")));
diff --git a/Tests/LibWeb/Text/input/css/style-engine/value-function-inputs.html b/Tests/LibWeb/Text/input/css/style-engine/value-function-inputs.html
new file mode 100644
index 00000000000..f73939413be
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/style-engine/value-function-inputs.html
@@ -0,0 +1,167 @@
+<!DOCTYPE html>
+<style>
+ @property --registered-index {
+ syntax: "<integer>";
+ inherits: false;
+ initial-value: 0;
+ }
+ @function --doubled() {
+ result: calc(var(--base) * 2);
+ }
+ @property --second {
+ syntax: "<length>";
+ inherits: false;
+ initial-value: 0px;
+ }
+ @function --indexed() {
+ result: calc(sibling-index() * 1000px);
+ }
+ @function --scaled() {
+ result: calc(var(--base) * var(--scale, 1));
+ }
+ #attributes {
+ width: attr(data-width type(<length>), 1px);
+ --copied: attr(data-word);
+ }
+ #attributes::before {
+ content: attr(data-label);
+ }
+ #attributes::after {
+ content: "after";
+ display: block;
+ width: attr(data-width type(<length>), 2px);
+ }
+ #siblings > div {
+ width: calc(sibling-index() * 1px);
+ height: calc(sibling-count() * 1px);
+ --registered-index: sibling-index();
+ --second: 2px;
+ margin-left: --indexed();
+ max-width: if(style(--second: calc(sibling-index() * 1px)): 22px; else: 11px);
+ }
+ #siblings > div > span {
+ display: block;
+ width: calc(sibling-index() * 10px);
+ }
+ #siblings > div::before {
+ content: "x";
+ display: block;
+ width: calc(sibling-index() * 100px);
+ }
+ #conditional {
+ width: if(style(--mode: wide): 50px; else: 5px);
+ }
+ #inheriting {
+ width: inherit(--size, 3px);
+ height: calc(inherit(--size, 3px) * 2);
+ }
+ #functions {
+ width: --doubled();
+ height: --scaled();
+ }
+</style>
+<div id="attributes" data-width="10px" data-word="first" data-label="one"></div>
+<div id="siblings"><div id="first"><span></span></div><div id="second"><span></span></div><div id="third"><span></span></div></div>
+<div id="conditional-parent"><div id="conditional"></div></div>
+<div id="inheriting-parent" style="--size: 7px"><div id="inheriting"></div></div>
+<div id="functions-parent" style="--base: 4px"><div id="functions"></div></div>
+<script src="../../include.js"></script>
+<script>
+ test(() => {
+ const attributes = document.getElementById("attributes");
+ const siblings = document.getElementById("siblings");
+
+ function dumpAttributes(label) {
+ const style = getComputedStyle(attributes);
+ const before = getComputedStyle(attributes, "::before");
+ const after = getComputedStyle(attributes, "::after");
+ println(`${label}: width ${style.width}, --copied ${style.getPropertyValue("--copied").trim()}, ::before ${before.content}, ::after width ${after.width}`);
+ }
+
+ function dumpSiblings(label) {
+ const parts = [];
+ for (const child of siblings.children) {
+ const style = getComputedStyle(child);
+ const span = getComputedStyle(child.firstElementChild);
+ const before = getComputedStyle(child, "::before");
+ parts.push(`${child.id}(${style.width} ${style.height} ${style.getPropertyValue("--registered-index").trim()} ${style.marginLeft} ${style.maxWidth} ${span.width} ${before.width})`);
+ }
+ println(`${label}: ${parts.join(" ")}`);
+ }
+
+ function dumpWidthAndHeight(id, label) {
+ const style = getComputedStyle(document.getElementById(id));
+ println(`${label}: ${style.width} ${style.height}`);
+ }
+
+ dumpAttributes("attr initial");
+ attributes.setAttribute("data-width", "20px");
+ dumpAttributes("attr width changed");
+ attributes.setAttribute("data-word", "second");
+ dumpAttributes("attr word changed");
+ attributes.setAttribute("data-label", "two");
+ dumpAttributes("attr label changed");
+ attributes.removeAttribute("data-width");
+ dumpAttributes("attr width removed");
+ attributes.setAttribute("data-width", "30px");
+ dumpAttributes("attr width added");
+
+ dumpSiblings("siblings initial");
+ const inserted = document.createElement("div");
+ inserted.id = "inserted";
+ inserted.appendChild(document.createElement("span"));
+ siblings.insertBefore(inserted, siblings.firstElementChild);
+ dumpSiblings("sibling inserted first");
+ document.getElementById("second").remove();
+ dumpSiblings("sibling removed");
+ siblings.appendChild(document.getElementById("first"));
+ dumpSiblings("sibling moved last");
+ siblings.insertBefore(document.createTextNode("text"), siblings.firstChild);
+ dumpSiblings("text node inserted");
+ const appended = document.createElement("div");
+ appended.id = "appended";
+ appended.appendChild(document.createElement("span"));
+ siblings.appendChild(appended);
+ dumpSiblings("sibling appended last");
+ appended.remove();
+ dumpSiblings("last sibling removed");
+
+ const conditionalParent = document.getElementById("conditional-parent");
+ const conditional = document.getElementById("conditional");
+ dumpWidthAndHeight("conditional", "if initial");
+ conditional.style.setProperty("--mode", "wide");
+ dumpWidthAndHeight("conditional", "if own property set");
+ conditional.style.removeProperty("--mode");
+ dumpWidthAndHeight("conditional", "if own property removed");
+ conditionalParent.style.setProperty("--mode", "wide");
+ dumpWidthAndHeight("conditional", "if inherited property set");
+ conditionalParent.style.setProperty("--mode", "narrow");
+ dumpWidthAndHeight("conditional", "if inherited property changed");
+
+ const inheritingParent = document.getElementById("inheriting-parent");
+ dumpWidthAndHeight("inheriting", "inherit initial");
+ inheritingParent.style.setProperty("--size", "9px");
+ dumpWidthAndHeight("inheriting", "inherit parent changed");
+ inheritingParent.style.removeProperty("--size");
+ dumpWidthAndHeight("inheriting", "inherit parent removed");
+ document.getElementById("inheriting").style.setProperty("--size", "100px");
+ dumpWidthAndHeight("inheriting", "inherit own property set");
+
+ const functionsParent = document.getElementById("functions-parent");
+ const functions = document.getElementById("functions");
+ dumpWidthAndHeight("functions", "function initial");
+ functionsParent.style.setProperty("--base", "6px");
+ dumpWidthAndHeight("functions", "function inherited input changed");
+ functions.style.setProperty("--scale", "3");
+ dumpWidthAndHeight("functions", "function own input set");
+ const sheet = document.styleSheets[0];
+ for (let index = 0; index < sheet.cssRules.length; ++index) {
+ if (sheet.cssRules[index].cssText.startsWith("@function --doubled")) {
+ sheet.deleteRule(index);
+ sheet.insertRule("@function --doubled() { result: calc(var(--base) * 5); }", index);
+ break;
+ }
+ }
+ dumpWidthAndHeight("functions", "function definition changed");
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/viewport-relative-value-shared-by-elements.html b/Tests/LibWeb/Text/input/css/style-engine/viewport-relative-value-shared-by-elements.html
new file mode 100644
index 00000000000..61cb31eb544
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/style-engine/viewport-relative-value-shared-by-elements.html
@@ -0,0 +1,50 @@
+<!DOCTYPE html>
+<script src="../../include.js"></script>
+<script>
+ function animationFrame() {
+ return new Promise(resolve => requestAnimationFrame(resolve));
+ }
+
+ promiseTest(async () => {
+ const iframe = document.createElement("iframe");
+ iframe.style.border = "0";
+ iframe.style.width = "300px";
+ iframe.style.height = "200px";
+
+ const loaded = new Promise(resolve => iframe.addEventListener("load", resolve, { once: true }));
+ iframe.srcdoc = `
+ <!DOCTYPE html>
+ <style>
+ .sized {
+ width: 10vw;
+ height: 1px;
+ }
+
+ #second {
+ color: rgb(0, 128, 0);
+ }
+
+ #third {
+ color: rgb(0, 0, 255);
+ }
+ </style>
+ <div class="sized" id="first"></div>
+ <div class="sized" id="second"></div>
+ <div class="sized" id="third"></div>
+ `;
+ document.body.appendChild(iframe);
+ await loaded;
+
+ const child = iframe.contentWindow;
+ child.internals.updateStyle();
+ child.document.body.offsetWidth;
+
+ iframe.style.width = "500px";
+ document.body.offsetWidth;
+ await animationFrame();
+ child.document.body.offsetWidth;
+
+ for (const id of ["first", "second", "third"])
+ println(`${id}: ${child.getComputedStyle(child.document.getElementById(id)).width}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/retained-winner-priority-pseudo-target.html b/Tests/LibWeb/Text/input/css/style-engine/winner-priority-pseudo-target.html
similarity index 100%
rename from Tests/LibWeb/Text/input/css/style-engine/retained-winner-priority-pseudo-target.html
rename to Tests/LibWeb/Text/input/css/style-engine/winner-priority-pseudo-target.html
diff --git a/Tests/LibWeb/Text/input/css/style-engine/winner-prune-retained-answer.html b/Tests/LibWeb/Text/input/css/style-engine/winner-prune.html
similarity index 100%
rename from Tests/LibWeb/Text/input/css/style-engine/winner-prune-retained-answer.html
rename to Tests/LibWeb/Text/input/css/style-engine/winner-prune.html
diff --git a/Tests/LibWeb/Text/input/css/user-agent-declarations-intern-once-per-process.html b/Tests/LibWeb/Text/input/css/user-agent-declarations-intern-once-per-process.html
new file mode 100644
index 00000000000..dfc01f38233
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/user-agent-declarations-intern-once-per-process.html
@@ -0,0 +1,18 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<iframe srcdoc="<p>x</p>"></iframe>
+<script>
+ // Have this document attach the user agent sheets, which has the process keep their rules.
+ internals.updateStyle();
+ asyncTest(done => {
+ const iframe = document.querySelector("iframe");
+ iframe.onload = () => {
+ // The frame reads the rules the process keeps, without recording or interning any of them itself.
+ const p = iframe.contentDocument.querySelector("p");
+ println(`margin-top from the user-agent sheet: ${iframe.contentWindow.getComputedStyle(p).marginTop}`);
+ const counters = iframe.contentWindow.internals.styleEngineCounters();
+ println(`declarations the frame published: ${counters.sheetDeclarationsInterned + counters.sheetDeclarationsShared}`);
+ done();
+ };
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/webkit-text-fill-color-inherited-below-own-color.html b/Tests/LibWeb/Text/input/css/webkit-text-fill-color-inherited-below-own-color.html
new file mode 100644
index 00000000000..f3e08851717
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/webkit-text-fill-color-inherited-below-own-color.html
@@ -0,0 +1,27 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<style>
+ .parent { color: rgb(16, 30, 30); }
+ .on .parent { -webkit-text-fill-color: transparent; }
+ .own { color: rgb(111, 119, 134); }
+</style>
+<div id="static" class="on"><span class="parent"><b class="own"><i>x</i></b></span></div>
+<div id="dynamic"><span class="parent"><b class="own"><i>x</i></b></span></div>
+<div id="svg"><span class="parent"><svg class="own"><path d="M0 0"/></svg></span></div>
+<script>
+ test(() => {
+ const fill = element => getComputedStyle(element).webkitTextFillColor;
+ const report = id => {
+ const parent = document.querySelector(`#${id} .parent`);
+ const own = parent.firstElementChild;
+ println(`${id}: ${fill(parent)}, ${fill(own)}, ${fill(own.firstElementChild)}`);
+ };
+ report("dynamic");
+ report("svg");
+ for (const id of ["dynamic", "svg"])
+ document.getElementById(id).className = "on";
+ report("static");
+ report("dynamic");
+ report("svg");
+ });
+</script>