Skip to content

Truly independent web browser

LibWeb: Keep parsed style data compact and shared

Andreas Klingefb0a1ddf0c6
diff --git a/Libraries/LibWeb/CSS/CSSGroupingRule.cpp b/Libraries/LibWeb/CSS/CSSGroupingRule.cpp
index 860720d3c38..d89eef69df4 100644
--- a/Libraries/LibWeb/CSS/CSSGroupingRule.cpp
+++ b/Libraries/LibWeb/CSS/CSSGroupingRule.cpp
@@ -13,14 +13,28 @@
namespace Web::CSS {
-CSSGroupingRule::CSSGroupingRule(CSSRuleList& rules, RustRule rule)
+CSSGroupingRule::CSSGroupingRule(GC::Ptr<CSSRuleList> rules, RustRule rule)
: CSSRule(move(rule))
, m_rules(rules)
{
- VERIFY(Parser::ValueParserFFI::rust_rule_children(native_rule().handle()) == rules.native_rules().handle());
+ if (!m_rules)
+ return;
+ VERIFY(Parser::ValueParserFFI::rust_rule_children(native_rule().handle()) == m_rules->native_rules().handle());
m_rules->set_owner_rule(*this);
}
+CSSRuleList& CSSGroupingRule::ensure_rules() const
+{
+ if (!m_rules) {
+ auto& rule = const_cast<CSSGroupingRule&>(*this);
+ auto* sheet = rule.parent_style_sheet();
+ m_rules = CSSRuleList::create(RustRuleList { Parser::ValueParserFFI::rust_rule_list_retain(Parser::ValueParserFFI::rust_rule_children(native_rule().handle())) }, sheet ? sheet->parsing_document() : nullptr);
+ m_rules->set_owner_rule(rule);
+ m_rules->set_parent_style_sheet(sheet);
+ }
+ return *m_rules;
+}
+
void CSSGroupingRule::visit_edges(GC::Cell::Visitor& visitor)
{
Base::visit_edges(visitor);
@@ -30,6 +44,8 @@ void CSSGroupingRule::visit_edges(GC::Cell::Visitor& visitor)
void CSSGroupingRule::clear_caches()
{
Base::clear_caches();
+ if (!m_rules)
+ return;
m_rules->for_each_existing_rule([](CSSRule& rule) { rule.clear_caches(); });
}
@@ -41,14 +57,15 @@ WebIDL::ExceptionOr<u32> CSSGroupingRule::insert_rule(Utf16View rule, u32 index)
RustNamespaceContext declared_namespaces;
if (auto* sheet = parent_style_sheet())
declared_namespaces = sheet->declared_namespaces();
- TRY(m_rules->insert_a_css_rule(rule, index, CSSRuleList::Nested::Yes, declared_namespaces));
+ auto& rules = css_rules();
+ TRY(rules.insert_a_css_rule(rule, index, CSSRuleList::Nested::Yes, declared_namespaces));
if (auto* sheet = parent_style_sheet()) {
sheet->invalidate_image_resource_registration();
if (auto* function = Parser::ValueParserFFI::rust_rule_containing_function(native_rule().handle()))
record_style_rule_declarations_changed(RustRule { function }, *sheet);
else
- record_style_rule_inserted(m_rules->native_rules().at(index), *sheet);
+ record_style_rule_inserted(rules.native_rules().at(index), *sheet);
sheet->invalidate_owners();
sheet->synchronize_fonts_after_rule_change();
}
@@ -57,7 +74,7 @@ WebIDL::ExceptionOr<u32> CSSGroupingRule::insert_rule(Utf16View rule, u32 index)
WebIDL::ExceptionOr<void> CSSGroupingRule::delete_rule(u32 index)
{
- auto removed_rule = TRY(m_rules->remove_a_css_rule(index));
+ auto removed_rule = TRY(css_rules().remove_a_css_rule(index));
if (auto* sheet = parent_style_sheet()) {
if (auto* function = Parser::ValueParserFFI::rust_rule_containing_function(native_rule().handle()))
record_style_rule_declarations_changed(RustRule { function }, *sheet);
@@ -72,7 +89,8 @@ WebIDL::ExceptionOr<void> CSSGroupingRule::delete_rule(u32 index)
void CSSGroupingRule::set_parent_style_sheet(StyleSheetState* parent_style_sheet)
{
CSSRule::set_parent_style_sheet(parent_style_sheet);
- m_rules->set_parent_style_sheet(parent_style_sheet);
+ if (m_rules)
+ m_rules->set_parent_style_sheet(parent_style_sheet);
}
}
diff --git a/Libraries/LibWeb/CSS/CSSGroupingRule.h b/Libraries/LibWeb/CSS/CSSGroupingRule.h
index e0ab1a3c98b..4e713068e20 100644
--- a/Libraries/LibWeb/CSS/CSSGroupingRule.h
+++ b/Libraries/LibWeb/CSS/CSSGroupingRule.h
@@ -18,24 +18,26 @@ class CSSGroupingRule : public CSSRule {
WEB_WRAPPABLE(CSSGroupingRule, CSSRule);
public:
- static constexpr size_t rules_offset() { return offsetof(CSSGroupingRule, m_rules); }
virtual ~CSSGroupingRule() = default;
- CSSRuleList const& css_rules() const { return m_rules; }
- CSSRuleList& css_rules() { return m_rules; }
- CSSRuleList* css_rules_for_bindings() { return m_rules.ptr(); }
+ CSSRuleList const& css_rules() const { return ensure_rules(); }
+ CSSRuleList& css_rules() { return ensure_rules(); }
+ CSSRuleList* css_rules_for_bindings() { return &ensure_rules(); }
WebIDL::ExceptionOr<u32> insert_rule(Utf16View rule, u32 index = 0);
WebIDL::ExceptionOr<void> delete_rule(u32 index);
virtual void set_parent_style_sheet(StyleSheetState*) override;
protected:
- CSSGroupingRule(CSSRuleList&, RustRule);
+ // NB: A rule given no list, as a style rule is, makes its list when it is first read.
+ CSSGroupingRule(GC::Ptr<CSSRuleList>, RustRule);
virtual void visit_edges(GC::Cell::Visitor&) override;
virtual void clear_caches() override;
private:
- GC::Ref<CSSRuleList> m_rules;
+ CSSRuleList& ensure_rules() const;
+
+ mutable GC::Ptr<CSSRuleList> m_rules;
};
}
diff --git a/Libraries/LibWeb/CSS/CSSGroupingRule.idl b/Libraries/LibWeb/CSS/CSSGroupingRule.idl
index 6e1370c6bd5..bdfef838184 100644
--- a/Libraries/LibWeb/CSS/CSSGroupingRule.idl
+++ b/Libraries/LibWeb/CSS/CSSGroupingRule.idl
@@ -1,7 +1,7 @@
// https://drafts.csswg.org/cssom/#the-cssgroupingrule-interface
[Exposed=Window]
interface CSSGroupingRule : CSSRule {
- [DirectGetter=rules, SameObject, ImplementedAs=css_rules_for_bindings] readonly attribute CSSRuleList cssRules;
+ [SameObject, ImplementedAs=css_rules_for_bindings] readonly attribute CSSRuleList cssRules;
unsigned long insertRule(CSSOMString rule, optional unsigned long index = 0);
undefined deleteRule(unsigned long index);
};
diff --git a/Libraries/LibWeb/CSS/CSSRule.cpp b/Libraries/LibWeb/CSS/CSSRule.cpp
index 8df3755c45e..b09f4ee3c8b 100644
--- a/Libraries/LibWeb/CSS/CSSRule.cpp
+++ b/Libraries/LibWeb/CSS/CSSRule.cpp
@@ -47,23 +47,31 @@ CSSStyleSheet* CSSRule::parent_style_sheet_for_bindings() const
CSSRule::CSSRule(RustRule rule)
: m_type(rule.type())
, m_native_rule(move(rule))
+{
+}
+
+// NB: Read from the native rule when asked, as only DevTools asks.
+Optional<SourcePosition> CSSRule::source_location() const
{
auto payload = m_native_rule.payload();
- if (payload.has_source_position) {
- VERIFY(payload.start_line <= NumericLimits<u32>::max());
- VERIFY(payload.start_column <= NumericLimits<u32>::max());
- m_source_position = SourcePosition { static_cast<u32>(payload.start_line), static_cast<u32>(payload.start_column) };
- }
+ if (!payload.has_source_position)
+ return {};
+ VERIFY(payload.start_line <= NumericLimits<u32>::max());
+ VERIFY(payload.start_column <= NumericLimits<u32>::max());
+ return SourcePosition { static_cast<u32>(payload.start_line), static_cast<u32>(payload.start_column) };
}
GC::Ref<CSSRule> CSSRule::create(RustRule rule, GC::Ptr<DOM::Document> document)
{
+ // NB: A style rule makes its list of nested rules when it is first read, as most style rules nest none.
+ if (rule.type() == Type::Style)
+ return CSSStyleRule::create(move(rule));
GC::Ptr<CSSRuleList> children;
if (auto* native_children = Parser::ValueParserFFI::rust_rule_children(rule.handle()); native_children && rule.type() != Type::Keyframes)
children = CSSRuleList::create(RustRuleList { Parser::ValueParserFFI::rust_rule_list_retain(native_children) }, document);
switch (rule.type()) {
case Type::Style:
- return CSSStyleRule::create(move(rule), *children);
+ VERIFY_NOT_REACHED();
case Type::Media:
return CSSMediaRule::create(move(rule), *children);
case Type::Supports:
diff --git a/Libraries/LibWeb/CSS/CSSRule.h b/Libraries/LibWeb/CSS/CSSRule.h
index 96c0c81508f..68109d7926b 100644
--- a/Libraries/LibWeb/CSS/CSSRule.h
+++ b/Libraries/LibWeb/CSS/CSSRule.h
@@ -46,7 +46,7 @@ public:
MUST_UPCALL virtual void set_parent_style_sheet(StyleSheetState*);
CSSStyleSheet* parent_style_sheet_for_bindings() const;
- Optional<SourcePosition> const& source_location() const { return m_source_position; }
+ Optional<SourcePosition> source_location() const;
template<typename T>
bool fast_is() const = delete;
@@ -69,8 +69,6 @@ protected:
GC::Ptr<CSSRule> m_parent_rule;
RefPtr<StyleSheetState> m_parent_style_sheet;
GC::Ptr<CSSStyleSheet> m_parent_cssom_sheet;
-
- Optional<SourcePosition> m_source_position;
};
}
diff --git a/Libraries/LibWeb/CSS/CSSStyleRule.cpp b/Libraries/LibWeb/CSS/CSSStyleRule.cpp
index 4c11280a8c5..769fb6ea20d 100644
--- a/Libraries/LibWeb/CSS/CSSStyleRule.cpp
+++ b/Libraries/LibWeb/CSS/CSSStyleRule.cpp
@@ -20,22 +20,36 @@ namespace Web::CSS {
GC_DEFINE_ALLOCATOR(CSSStyleRule);
-GC::Ref<CSSStyleRule> CSSStyleRule::create(RustRule rule, CSSRuleList& nested_rules)
+// NB: The CSSOM wraps every style rule a script reads, so its wrapper stays small.
+#if ARCH(X86_64) && !defined(AK_OS_WINDOWS)
+static_assert(sizeof(CSSRule) <= 64);
+static_assert(sizeof(CSSStyleRule) <= 112);
+#endif
+
+GC::Ref<CSSStyleRule> CSSStyleRule::create(RustRule rule)
{
- return GC::Heap::the().allocate<CSSStyleRule>(move(rule), nested_rules);
+ return GC::Heap::the().allocate<CSSStyleRule>(move(rule));
}
-CSSStyleRule::CSSStyleRule(RustRule rule, CSSRuleList& nested_rules)
- : CSSGroupingRule(nested_rules, move(rule))
+CSSStyleRule::CSSStyleRule(RustRule rule)
+ : CSSGroupingRule(nullptr, move(rule))
, m_declarations(Parser::ValueParserFFI::rust_rule_declarations(native_rule().handle()))
{
}
+CSSStyleRule::SelectorCaches& CSSStyleRule::selector_caches() const
+{
+ if (!m_selector_caches)
+ m_selector_caches = make<SelectorCaches>();
+ return *m_selector_caches;
+}
+
SelectorList const& CSSStyleRule::selectors() const
{
- if (!m_selectors.has_value())
- m_selectors = selector_list_from_rust(static_cast<SelectorFFI::RustParsedSelectorList const*>(Parser::ValueParserFFI::rust_rule_selectors(native_rule().handle())));
- return *m_selectors;
+ auto& caches = selector_caches();
+ if (!caches.selectors.has_value())
+ caches.selectors = selector_list_from_rust(static_cast<SelectorFFI::RustParsedSelectorList const*>(Parser::ValueParserFFI::rust_rule_selectors(native_rule().handle())));
+ return *caches.selectors;
}
size_t CSSStyleRule::external_memory_size() const
@@ -153,7 +167,8 @@ void CSSStyleRule::set_selector_text(Utf16View selector_text)
// 2. If the algorithm returns a non-null value replace the associated group of selectors with the returned value.
if (Parser::ValueParserFFI::rust_rule_set_selector_text(native_rule().handle(), Parser::ffi_utf16_view(selector_text), sheet ? sheet->native_rules().handle() : nullptr)) {
- m_selectors.clear();
+ if (m_selector_caches)
+ m_selector_caches->selectors.clear();
clear_caches();
if (sheet) {
record_style_rule_selector_changed(*this);
@@ -166,17 +181,17 @@ void CSSStyleRule::set_selector_text(Utf16View selector_text)
SelectorList const& CSSStyleRule::absolutized_selectors() const
{
- if (m_cached_absolutized_selectors.has_value())
- return m_cached_absolutized_selectors.value();
-
- m_cached_absolutized_selectors = matching_selectors_for_rule(native_rule());
- return m_cached_absolutized_selectors.value();
+ auto& caches = selector_caches();
+ if (!caches.absolutized_selectors.has_value())
+ caches.absolutized_selectors = matching_selectors_for_rule(native_rule());
+ return *caches.absolutized_selectors;
}
void CSSStyleRule::clear_caches()
{
Base::clear_caches();
- m_cached_absolutized_selectors.clear();
+ if (m_selector_caches)
+ m_selector_caches->absolutized_selectors.clear();
}
void CSSStyleRule::dump(StringBuilder& builder, int indent_levels) const
diff --git a/Libraries/LibWeb/CSS/CSSStyleRule.h b/Libraries/LibWeb/CSS/CSSStyleRule.h
index 1c64f4b3bf4..ee8ee77acb7 100644
--- a/Libraries/LibWeb/CSS/CSSStyleRule.h
+++ b/Libraries/LibWeb/CSS/CSSStyleRule.h
@@ -8,6 +8,7 @@
#pragma once
#include <AK/NonnullRefPtr.h>
+#include <AK/OwnPtr.h>
#include <AK/Utf16String.h>
#include <AK/Utf16View.h>
#include <LibWeb/CSS/CSSGroupingRule.h>
@@ -21,7 +22,7 @@ class CSSStyleRule final : public CSSGroupingRule {
GC_DECLARE_ALLOCATOR(CSSStyleRule);
public:
- [[nodiscard]] static GC::Ref<CSSStyleRule> create(RustRule, CSSRuleList&);
+ [[nodiscard]] static GC::Ref<CSSStyleRule> create(RustRule);
virtual ~CSSStyleRule() override = default;
@@ -36,7 +37,7 @@ public:
GC::Ref<StylePropertyMap> style_map();
private:
- CSSStyleRule(RustRule, CSSRuleList&);
+ explicit CSSStyleRule(RustRule);
GC::Ref<CSSStyleProperties> ensure_style_properties() const;
virtual size_t external_memory_size() const override;
virtual void visit_edges(GC::Cell::Visitor&) override;
@@ -44,8 +45,15 @@ private:
virtual Utf16String serialized() const override;
virtual void dump(StringBuilder&, int indent_levels) const override;
- mutable Optional<SelectorList> m_selectors;
- mutable Optional<SelectorList> m_cached_absolutized_selectors;
+ // What the rule makes of its selectors when they are first read; boxed, as most rules never make it.
+ struct SelectorCaches {
+ AK_ALLOC_WITH_KMALLOC;
+ Optional<SelectorList> selectors;
+ Optional<SelectorList> absolutized_selectors;
+ };
+ SelectorCaches& selector_caches() const;
+
+ mutable OwnPtr<SelectorCaches> m_selector_caches;
RustDeclarationBlock m_declarations;
mutable GC::Ptr<CSSStyleProperties> m_declaration;
GC::Ptr<StylePropertyMap> m_style_map;
diff --git a/Libraries/LibWeb/CSS/ComputedValues.cpp b/Libraries/LibWeb/CSS/ComputedValues.cpp
index 05da4e2c969..3b884153230 100644
--- a/Libraries/LibWeb/CSS/ComputedValues.cpp
+++ b/Libraries/LibWeb/CSS/ComputedValues.cpp
@@ -45,10 +45,8 @@ namespace Web::CSS {
// Groups whose layout is defined in Rust must not change size or alignment when the C++
// side layers initial values and accessors on top of the mirrored layout.
-static_assert(sizeof(ComputedValues::InheritedBoxValues) == sizeof(ComputedValuesFFI::InheritedBoxValues));
-static_assert(alignof(ComputedValues::InheritedBoxValues) == alignof(ComputedValuesFFI::InheritedBoxValues));
-static_assert(sizeof(ComputedValues::InheritedTableValues) == sizeof(ComputedValuesFFI::InheritedTableValues));
-static_assert(alignof(ComputedValues::InheritedTableValues) == alignof(ComputedValuesFFI::InheritedTableValues));
+static_assert(sizeof(ComputedValues::InheritedListTableValues) == sizeof(ComputedValuesFFI::InheritedListTableValues));
+static_assert(alignof(ComputedValues::InheritedListTableValues) == alignof(ComputedValuesFFI::InheritedListTableValues));
static_assert(sizeof(ComputedValues::SizingValues) == sizeof(ComputedValuesFFI::SizingValues));
static_assert(alignof(ComputedValues::SizingValues) == alignof(ComputedValuesFFI::SizingValues));
static_assert(sizeof(ComputedValues::AlignmentValues) == sizeof(ComputedValuesFFI::AlignmentValues));
@@ -100,10 +98,6 @@ static_assert(to_underlying(ShadowPlacement::Inner) == 1);
static_assert(to_underlying(MixBlendMode::Normal) == 0);
static_assert(to_underlying(Isolation::Auto) == 0);
static_assert(sizeof(LineStyle) == sizeof(u8));
-static_assert(sizeof(BorderData) == sizeof(ComputedValuesFFI::ComputedBorderSide));
-static_assert(offsetof(BorderData, color) == offsetof(ComputedValuesFFI::ComputedBorderSide, color));
-static_assert(offsetof(BorderData, line_style) == offsetof(ComputedValuesFFI::ComputedBorderSide, line_style));
-static_assert(offsetof(BorderData, width) == offsetof(ComputedValuesFFI::ComputedBorderSide, width));
static_assert(offsetof(ComputedValues::BorderValues, border_left) == offsetof(ComputedValuesFFI::BorderLayoutFacts, border_left));
static_assert(offsetof(ComputedValues::BorderValues, border_top) == offsetof(ComputedValuesFFI::BorderLayoutFacts, border_top));
static_assert(offsetof(ComputedValues::BorderValues, border_right) == offsetof(ComputedValuesFFI::BorderLayoutFacts, border_right));
@@ -113,10 +107,10 @@ static_assert(sizeof(ComputedValues::BorderValues) == sizeof(ComputedValuesFFI::
static_assert(alignof(ComputedValues::BorderValues) == alignof(ComputedValuesFFI::BorderValues));
static_assert(sizeof(ComputedValues::ContentValues) == sizeof(ComputedValuesFFI::ContentValues));
static_assert(alignof(ComputedValues::ContentValues) == alignof(ComputedValuesFFI::ContentValues));
-static_assert(sizeof(ComputedValues::InheritedListValues) == sizeof(ComputedValuesFFI::InheritedListValues));
-static_assert(alignof(ComputedValues::InheritedListValues) == alignof(ComputedValuesFFI::InheritedListValues));
-static_assert(sizeof(ComputedValues::MiscResetValues) == sizeof(ComputedValuesFFI::MiscResetValues));
-static_assert(alignof(ComputedValues::MiscResetValues) == alignof(ComputedValuesFFI::MiscResetValues));
+static_assert(sizeof(ComputedValues::MiscLayoutValues) == sizeof(ComputedValuesFFI::MiscLayoutValues));
+static_assert(alignof(ComputedValues::MiscLayoutValues) == alignof(ComputedValuesFFI::MiscLayoutValues));
+static_assert(sizeof(ComputedValues::MiscInteractionValues) == sizeof(ComputedValuesFFI::MiscInteractionValues));
+static_assert(alignof(ComputedValues::MiscInteractionValues) == alignof(ComputedValuesFFI::MiscInteractionValues));
static_assert(to_underlying(ListStylePosition::Outside) == 1);
static_assert(sizeof(TextIndentData) == sizeof(ComputedValuesFFI::ComputedTextIndent));
@@ -153,126 +147,86 @@ void const* ComputedValues::style_group_payload(StyleGroupIndex group) const
VERIFY_NOT_REACHED();
}
-void ComputedValues::borrow_style_record_payloads(ReadonlySpan<void const*> payloads)
+void ComputedValues::borrow_style_record_groups(void const* groups)
{
- VERIFY(payloads.size() == to_underlying(StyleGroupIndex::Count));
- size_t index = 0;
-#define LIBWEB_BORROW_STYLE_GROUP(path) path.borrow(payloads[index++]);
- LIBWEB_BORROW_STYLE_GROUP(m_inherited.table)
- LIBWEB_BORROW_STYLE_GROUP(m_inherited.list)
- LIBWEB_BORROW_STYLE_GROUP(m_inherited.ui)
- LIBWEB_BORROW_STYLE_GROUP(m_inherited.svg)
- LIBWEB_BORROW_STYLE_GROUP(m_inherited.text)
- LIBWEB_BORROW_STYLE_GROUP(m_inherited.box)
- LIBWEB_BORROW_STYLE_GROUP(m_inherited.font)
- LIBWEB_BORROW_STYLE_GROUP(m_noninherited.animation)
- LIBWEB_BORROW_STYLE_GROUP(m_noninherited.svg_reset)
- LIBWEB_BORROW_STYLE_GROUP(m_noninherited.grid)
- LIBWEB_BORROW_STYLE_GROUP(m_noninherited.anchor)
- LIBWEB_BORROW_STYLE_GROUP(m_noninherited.effects)
- LIBWEB_BORROW_STYLE_GROUP(m_noninherited.mask_data)
- LIBWEB_BORROW_STYLE_GROUP(m_noninherited.text_reset)
- LIBWEB_BORROW_STYLE_GROUP(m_noninherited.content_data)
- LIBWEB_BORROW_STYLE_GROUP(m_noninherited.transform)
- LIBWEB_BORROW_STYLE_GROUP(m_noninherited.background)
- LIBWEB_BORROW_STYLE_GROUP(m_noninherited.border)
- LIBWEB_BORROW_STYLE_GROUP(m_noninherited.alignment)
- LIBWEB_BORROW_STYLE_GROUP(m_noninherited.misc)
- LIBWEB_BORROW_STYLE_GROUP(m_noninherited.sizing)
- LIBWEB_BORROW_STYLE_GROUP(m_noninherited.surround)
- LIBWEB_BORROW_STYLE_GROUP(m_noninherited.box)
+ VERIFY(groups);
+#define LIBWEB_BORROW_STYLE_GROUP(name, path, sharing_name) \
+ path.borrow(style_record_group_payload<to_underlying(StyleGroupIndex::name)>(groups));
+ LIBWEB_ENUMERATE_COMPUTED_VALUE_STYLE_GROUPS(LIBWEB_BORROW_STYLE_GROUP)
#undef LIBWEB_BORROW_STYLE_GROUP
- VERIFY(index == payloads.size());
+ m_inherited.values = style_record_inherited_values(groups);
+ m_noninherited.reset_bits = style_record_reset_bits(groups);
}
bool InstalledStyle::display_is_none() const
{
- if (!m_view.present)
+ if (!m_record)
return false;
// The record's base payloads are the ones an animation overlay was layered on top of, matching
// what ComputedValues::base_values() exposes.
- auto const* payloads = m_view.base_payloads ? m_view.base_payloads : m_view.payloads;
- if (!payloads)
+ auto view = this->view();
+ auto const* groups = StyleEngineFFI::style_engine_view_base_groups(&view);
+ if (!groups)
return false;
- auto const* box = static_cast<ComputedValuesFFI::BoxValues const*>(payloads[to_underlying(StyleGroupIndex::BoxValues)]);
- if (!box)
- return false;
- return display_from_ffi_display(box->display).is_none();
+ return display_from_ffi_display(style_record_group<ComputedValues::BoxValues>(groups).display).is_none();
}
-ComputedStyleRecordView::ComputedStyleRecordView(StyleEngineFFI::FfiStyleRecordView const& view, StyleComputer const& style_computer, StyleRecordID style_record_identity, bool owns_style_record_pin)
- : m_style_computer(&style_computer)
- , m_style_record_identity(style_record_identity)
- , m_owns_style_record_pin(owns_style_record_pin)
+// NB: Out of line, as what other libraries link against does not include the engine's calls the destructor makes.
+ComputedStyleRecordView::~ComputedStyleRecordView() = default;
+
+ComputedStyleRecordView::ComputedStyleRecordView(InstalledStyle style)
+ : m_style(move(style))
{
- VERIFY(view.present);
- VERIFY(style_record_identity);
- VERIFY(view.payload_count == to_underlying(StyleGroupIndex::Count));
- VERIFY(view.payloads);
- VERIFY(view.base_payloads);
- auto payloads = ReadonlySpan<void const*> { view.payloads, view.payload_count };
- auto base_payloads = ReadonlySpan<void const*> { view.base_payloads, view.payload_count };
+ VERIFY(m_style);
+ auto view = m_style.view();
+ VERIFY(view.groups);
m_values.emplace(ComputedValues::BorrowedStyleRecord::Yes);
- m_values->borrow_style_record_payloads(payloads);
- if (view.animation_overlay_identity != 0) {
+ m_values->borrow_style_record_groups(view.groups);
+ if (view.animated_overlay) {
+ auto const* base_groups = StyleEngineFFI::style_engine_view_base_groups(&view);
+ VERIFY(base_groups);
m_base_values.emplace(ComputedValues::BorrowedStyleRecord::Yes);
- m_base_values->borrow_style_record_payloads(base_payloads);
+ m_base_values->borrow_style_record_groups(base_groups);
m_values->m_borrowed_base_values = &*m_base_values;
}
- m_values->m_pseudo_element_styles = view.pseudo_element_styles;
auto dependency_flags = static_cast<StyleRecordDependencyFlag>(view.dependency_flags);
m_values->m_depends_on_viewport_metrics = has_flag(dependency_flags, StyleRecordDependencyFlag::DependsOnViewportMetrics);
m_values->m_font_metrics_depend_on_viewport_metrics = has_flag(dependency_flags, StyleRecordDependencyFlag::FontMetricsDependOnViewportMetrics);
m_values->m_in_display_none_subtree = has_flag(dependency_flags, StyleRecordDependencyFlag::InDisplayNoneSubtree);
- m_values->m_computed_longhand_table = view.longhand_table;
- if (m_values->m_computed_longhand_table)
- m_values->refresh_computed_longhand_table_views();
+ m_values->m_record = StyleRecordRef { view.longhand_table_record };
if (view.animated_overlay)
m_values->m_animated_properties = adopt_ref(*new AnimatedProperties(static_cast<ComputedValuesFFI::AnimatedOverlay const*>(view.animated_overlay)));
- if (view.animation_overlay_identity != 0) {
- m_base_values->m_property_important = m_values->m_property_important;
- m_base_values->m_property_inherited = m_values->m_property_inherited;
- m_base_values->m_pseudo_element_styles = m_values->m_pseudo_element_styles;
+ if (view.animated_overlay) {
m_base_values->m_depends_on_viewport_metrics = m_values->m_depends_on_viewport_metrics;
m_base_values->m_font_metrics_depend_on_viewport_metrics = m_values->m_font_metrics_depend_on_viewport_metrics;
m_base_values->m_in_display_none_subtree = m_values->m_in_display_none_subtree;
- m_base_values->m_inheritance_dependent_specified_values = m_values->m_inheritance_dependent_specified_values;
- m_base_values->m_computed_longhand_table = m_values->m_computed_longhand_table;
- if (m_base_values->m_computed_longhand_table)
- m_base_values->refresh_computed_longhand_table_views();
+ m_base_values->m_record = m_values->m_record;
}
}
-ComputedStyleRecordView::~ComputedStyleRecordView()
-{
- if (m_style_computer && m_owns_style_record_pin)
- m_style_computer->unpin_style_record(m_style_record_identity);
-}
-
// The table-driven build and the marshalled build must stay on one numbering with the Rust
// mirror in table_group_builder.rs.
-static_assert(to_underlying(StyleGroupIndex::InheritedTableValues) == 0);
-static_assert(to_underlying(StyleGroupIndex::InheritedListValues) == 1);
-static_assert(to_underlying(StyleGroupIndex::InheritedUIValues) == 2);
-static_assert(to_underlying(StyleGroupIndex::InheritedSVGValues) == 3);
-static_assert(to_underlying(StyleGroupIndex::InheritedTextValues) == 4);
-static_assert(to_underlying(StyleGroupIndex::InheritedBoxValues) == 5);
-static_assert(to_underlying(StyleGroupIndex::FontValues) == 6);
-static_assert(to_underlying(StyleGroupIndex::SVGResetValues) == 8);
-static_assert(to_underlying(StyleGroupIndex::GridValues) == 9);
-static_assert(to_underlying(StyleGroupIndex::EffectsValues) == 11);
-static_assert(to_underlying(StyleGroupIndex::MaskValues) == 12);
-static_assert(to_underlying(StyleGroupIndex::ContentValues) == 14);
-static_assert(to_underlying(StyleGroupIndex::TransformValues) == 15);
-static_assert(to_underlying(StyleGroupIndex::MiscResetValues) == 19);
-static_assert(to_underlying(StyleGroupIndex::BackgroundValues) == 16);
-static_assert(to_underlying(StyleGroupIndex::BorderValues) == 17);
-static_assert(to_underlying(StyleGroupIndex::AlignmentValues) == 18);
-static_assert(to_underlying(StyleGroupIndex::SizingValues) == 20);
-static_assert(to_underlying(StyleGroupIndex::SurroundValues) == 21);
-static_assert(to_underlying(StyleGroupIndex::BoxValues) == 22);
-static_assert(to_underlying(StyleGroupIndex::Count) == 23);
+static_assert(to_underlying(StyleGroupIndex::InheritedListTableValues) == 0);
+static_assert(to_underlying(StyleGroupIndex::InheritedUIValues) == 1);
+static_assert(to_underlying(StyleGroupIndex::InheritedSVGValues) == 2);
+static_assert(to_underlying(StyleGroupIndex::InheritedTextValues) == 3);
+static_assert(to_underlying(StyleGroupIndex::FontValues) == 4);
+static_assert(to_underlying(StyleGroupIndex::SVGResetValues) == 6);
+static_assert(to_underlying(StyleGroupIndex::GridValues) == 7);
+static_assert(to_underlying(StyleGroupIndex::EffectsValues) == 13);
+static_assert(to_underlying(StyleGroupIndex::MaskValues) == 14);
+static_assert(to_underlying(StyleGroupIndex::ContentValues) == 9);
+static_assert(to_underlying(StyleGroupIndex::TransformValues) == 16);
+static_assert(to_underlying(StyleGroupIndex::MiscLayoutValues) == 11);
+static_assert(to_underlying(StyleGroupIndex::MiscInteractionValues) == 12);
+static_assert(to_underlying(StyleGroupIndex::BackgroundValues) == 17);
+static_assert(to_underlying(StyleGroupIndex::BorderValues) == 18);
+static_assert(to_underlying(StyleGroupIndex::AlignmentValues) == 10);
+static_assert(to_underlying(StyleGroupIndex::SizingValues) == 19);
+static_assert(to_underlying(StyleGroupIndex::SurroundValues) == 20);
+static_assert(to_underlying(StyleGroupIndex::BoxValues) == 21);
+static_assert(to_underlying(StyleGroupIndex::Count) == 22);
// The enum codes the core's transform and effects lowering mirrors.
static_assert(to_underlying(TransformBox::ViewBox) == 4);
@@ -315,7 +269,7 @@ FontStyleKeyword ComputedValues::FontValues::font_style_keyword() const
return animation_style_value(font_style)->as_font_style().font_style();
}
-Optional<Utf16FlyString> ComputedValues::MiscResetValues::view_transition_name_value() const
+Optional<Utf16FlyString> ComputedValues::MiscInteractionValues::view_transition_name_value() const
{
auto const* value = static_cast<StyleValueFFI::StyleValueData const*>(view_transition_name.pointer);
VERIFY(value);
@@ -330,7 +284,7 @@ static StyleValueFFI::StyleValueData const* first_animation_item_data(ComputedVa
VERIFY(value);
if (value->tag == StyleValueFFI::StyleValueData::Tag::ValueList
&& value->value_list.separator == to_underlying(StyleValueList::Separator::Comma)) {
- VERIFY(value->value_list.values.length > 0);
+ VERIFY(value->value_list.values.length() > 0);
return static_cast<StyleValueFFI::StyleValueData const*>(value->value_list.values.pointer[0].pointer);
}
return value;
@@ -358,13 +312,13 @@ static Vector<RefPtr<AbstractImageStyleValue const>> abstract_image_items(Comput
|| value->value_list.separator != to_underlying(StyleValueList::Separator::Comma))
return { abstract_image_value(value) };
Vector<RefPtr<AbstractImageStyleValue const>> images;
- images.ensure_capacity(value->value_list.values.length);
- for (size_t i = 0; i < value->value_list.values.length; ++i)
+ images.ensure_capacity(value->value_list.values.length());
+ for (size_t i = 0; i < value->value_list.values.length(); ++i)
images.unchecked_append(abstract_image_value(static_cast<StyleValueFFI::StyleValueData const*>(value->value_list.values.pointer[i].pointer)));
return images;
}
-RefPtr<AbstractImageStyleValue const> ComputedValues::InheritedListValues::list_style_image_value() const
+RefPtr<AbstractImageStyleValue const> ComputedValues::InheritedListTableValues::list_style_image_value() const
{
auto value = animation_style_value(list_style_image);
if (!value->is_abstract_image())
@@ -397,21 +351,16 @@ Optional<URL> ComputedValues::MaskValues::mask_url_value() const
{
auto const* image = first_animation_item_data(mask_image);
if (image->tag == StyleValueFFI::StyleValueData::Tag::Url)
- return url_from_rust_data(image->url.url, image->url.url_type, image->url.modifiers);
+ return url_from_rust_data(image->url._0->url, image->url._0->url_type, image->url._0->modifiers);
return {};
}
-MaskType ComputedValues::MaskValues::mask_type_value() const
-{
- return keyword_to_mask_type(animation_style_value(mask_type)->to_keyword()).release_value();
-}
-
Optional<URL> ComputedValues::MaskValues::clip_path_value() const
{
auto const* value_data = static_cast<StyleValueFFI::StyleValueData const*>(clip_path.pointer);
VERIFY(value_data);
if (value_data->tag == StyleValueFFI::StyleValueData::Tag::Url)
- return url_from_rust_data(value_data->url.url, value_data->url.url_type, value_data->url.modifiers);
+ return url_from_rust_data(value_data->url._0->url, value_data->url._0->url_type, value_data->url._0->modifiers);
return {};
}
@@ -420,31 +369,6 @@ Vector<RefPtr<AbstractImageStyleValue const>> ComputedValues::MaskValues::mask_i
return abstract_image_items(mask_image);
}
-Vector<Utf16FlyString> ComputedValues::AnimationValues::animation_names_value() const
-{
- auto const* value = static_cast<StyleValueFFI::StyleValueData const*>(animation_name.pointer);
- VERIFY(value && value->tag == StyleValueFFI::StyleValueData::Tag::ValueList);
- auto const& items = value->value_list.values;
- Vector<Utf16FlyString> names;
- for (size_t i = 0; i < items.length; ++i) {
- auto const* item = static_cast<StyleValueFFI::StyleValueData const*>(items.pointer[i].pointer);
- switch (item->tag) {
- case StyleValueFFI::StyleValueData::Tag::Keyword:
- VERIFY(static_cast<Keyword>(item->keyword.keyword) == Keyword::None);
- break;
- case StyleValueFFI::StyleValueData::Tag::String:
- names.append(css_string_from_rust(&item->string.string));
- break;
- case StyleValueFFI::StyleValueData::Tag::CustomIdent:
- names.append(css_string_from_rust(&item->custom_ident.custom_ident));
- break;
- default:
- VERIFY_NOT_REACHED();
- }
- }
- return names;
-}
-
ComputedValues::Statistics ComputedValues::s_statistics;
ComputedValues::ComputedValues()
@@ -453,75 +377,37 @@ ComputedValues::ComputedValues()
++s_statistics.total_instances_created;
}
-ComputedValues::ComputedValues(BorrowedStyleRecord)
- : m_inherited(StyleGroupInitialization::Empty)
- , m_noninherited(StyleGroupInitialization::Empty)
- , m_is_style_record_view(true)
+StyleRecordRef::StyleRecordRef(void const* record)
+ : m_record(record)
{
- m_ref_count = 0;
+ if (m_record)
+ StyleEngineFFI::style_engine_record_retain(m_record);
}
-ComputedValues::~ComputedValues()
+StyleRecordRef::~StyleRecordRef()
{
- if (m_is_style_record_view)
- m_computed_longhand_table = nullptr;
- else {
- clear_computed_longhand_table();
- --s_statistics.live_instance_count;
- }
-}
-
-void ComputedValues::adopt_computed_longhand_table(void const* table)
-{
- if (!table) {
- clear_computed_longhand_table();
- return;
- }
- // NB: Retain before releasing, so adopting the table this style already holds stays safe.
- auto const* typed_table = ComputedValuesFFI::rust_computed_longhand_table_retain(static_cast<ComputedValuesFFI::ComputedLonghandTable const*>(table));
- clear_computed_longhand_table();
- m_computed_longhand_table = typed_table;
- refresh_computed_longhand_table_views();
+ if (m_record)
+ StyleEngineFFI::style_engine_record_release(m_record);
}
-void ComputedValues::refresh_computed_longhand_table_views()
+ComputedValues::ComputedValues(BorrowedStyleRecord)
+ : m_is_style_record_view(true)
{
- VERIFY(m_computed_longhand_table);
- auto const* table = static_cast<ComputedValuesFFI::ComputedLonghandTable const*>(m_computed_longhand_table);
- m_longhand_values = { ComputedValuesFFI::rust_computed_longhand_table_values(table), number_of_longhand_properties };
- m_property_important.copy_from({ ComputedValuesFFI::rust_computed_longhand_table_importance_bits(table), m_property_important.size_in_bytes() });
- m_property_inherited.copy_from({ ComputedValuesFFI::rust_computed_longhand_table_inheritance_bits(table), m_property_inherited.size_in_bytes() });
- size_t inheritance_dependent_value_count = 0;
- auto const* inheritance_dependent_values = ComputedValuesFFI::rust_computed_longhand_table_inheritance_dependent_values(table, &inheritance_dependent_value_count);
- m_inheritance_dependent_specified_values = { inheritance_dependent_values, inheritance_dependent_value_count };
+ m_ref_count = 0;
}
-void ComputedValues::clear_computed_longhand_table()
+ComputedValues::~ComputedValues()
{
- if (m_computed_longhand_table)
- ComputedValuesFFI::rust_computed_longhand_table_release(const_cast<ComputedValuesFFI::ComputedLonghandTable*>(static_cast<ComputedValuesFFI::ComputedLonghandTable const*>(m_computed_longhand_table)));
- m_computed_longhand_table = nullptr;
- m_longhand_values = {};
- m_inheritance_dependent_specified_values = {};
+ if (!m_is_style_record_view)
+ --s_statistics.live_instance_count;
}
-void ComputedValues::copy_computed_longhand_table_from(ComputedValues const& other)
+bool ComputedValues::is_property_important(PropertyID property_id) const
{
- if (other.m_computed_longhand_table) {
- adopt_computed_longhand_table(other.m_computed_longhand_table);
- return;
- }
- clear_computed_longhand_table();
- if (other.m_longhand_values.is_empty())
- return;
- auto* table = ComputedValuesFFI::rust_computed_longhand_table_create();
- ComputedValuesFFI::rust_computed_longhand_table_copy_from_values(table, other.m_longhand_values.data(), other.m_longhand_values.size());
- for (auto const& entry : other.m_inheritance_dependent_specified_values)
- ComputedValuesFFI::rust_computed_longhand_table_add_inheritance_dependent_value(table, entry.property, entry.value);
- ComputedValuesFFI::rust_computed_longhand_table_freeze(table);
- // The freshly created table already carries the one reference this style owns.
- m_computed_longhand_table = table;
- refresh_computed_longhand_table_views();
+ if (!m_record.get())
+ return false;
+ auto index = property_bitmap_index(property_id);
+ return ComputedValuesFFI::rust_style_record_importance_bits(m_record.get())[index / 8] & (1 << (index % 8));
}
void ComputedValues::Mutator::set_animated_properties(AnimatedProperties const* value)
@@ -632,9 +518,9 @@ RefPtr<StyleValue const> ComputedValues::computed_style_value(PropertyID propert
&& ComputedValuesFFI::rust_animated_overlay_effective_value(m_animated_properties->overlay(), to_underlying(property_id), is_property_important(property_id)))
return m_animated_properties->property(property_id);
- if (m_longhand_values.is_empty())
+ if (!m_record.get())
return {};
- auto const* stored = m_longhand_values[to_underlying(property_id) - to_underlying(first_longhand_property_id)];
+ auto const* stored = ComputedValuesFFI::rust_style_record_longhand(m_record.get(), to_underlying(property_id));
if (!stored)
return {};
if (m_style_value_cache) {
diff --git a/Libraries/LibWeb/CSS/ComputedValues.h b/Libraries/LibWeb/CSS/ComputedValues.h
index c88f5f4a82b..cfc31dc14ce 100644
--- a/Libraries/LibWeb/CSS/ComputedValues.h
+++ b/Libraries/LibWeb/CSS/ComputedValues.h
@@ -24,6 +24,7 @@
#include <LibWeb/CSS/Display.h>
#include <LibWeb/CSS/EasingFunction.h>
#include <LibWeb/CSS/Enums.h>
+#include <LibWeb/CSS/InstalledStyle.h>
#include <LibWeb/CSS/LengthBox.h>
#include <LibWeb/CSS/PercentageOr.h>
#include <LibWeb/CSS/PropertyID.h>
@@ -79,7 +80,7 @@ public:
{
auto const* value = static_cast<StyleValueFFI::StyleValueData const*>(handle.pointer);
VERIFY(value && value->tag == StyleValueFFI::StyleValueData::Tag::Url);
- auto url = url_from_rust_data(value->url.url, value->url.url_type, value->url.modifiers);
+ auto url = url_from_rust_data(value->url._0->url, value->url._0->url_type, value->url._0->modifiers);
auto const& url_string = url.url();
if (url_string.is_empty() || !url_string.starts_with('#'))
return {};
@@ -203,28 +204,19 @@ public:
static CSSPixels font_size() { return 16; }
static double font_weight() { return 400; }
static CSSPixels line_height() { return 0; }
- static CaptionSide caption_side() { return CaptionSide::Top; }
- static Color caret_color() { return Color::Black; }
- static CSSPixels text_underline_offset() { return 2; }
- static Color color() { return Color::Black; }
static Color stop_color() { return Color::Black; }
- static BorderCollapse border_collapse() { return BorderCollapse::Separate; }
- static EmptyCells empty_cells() { return EmptyCells::Show; }
// https://www.w3.org/TR/SVG/geometry.html
static int math_depth() { return 0; }
-
- static ScrollbarColorData scrollbar_color()
- {
- return ScrollbarColorData {
- .thumb_color = Color(Color::NamedColor::DarkGray).with_alpha(192),
- .track_color = Color(Color::NamedColor::WarmGray).with_alpha(192),
- .is_auto = true,
- };
- }
- static PaintOrderList paint_order() { return { PaintOrder::Fill, PaintOrder::Stroke, PaintOrder::Markers }; }
};
+// A group's color, with `currentcolor`, which the group leaves to its reader, resolved to the
+// element's color.
+inline Color resolve_style_color(ComputedValuesFFI::StyleColor color, Color current_color)
+{
+ return color.is_current_color ? current_color : Color::from_bgra(color.rgba);
+}
+
struct BorderData {
public:
Color color { Color::Transparent };
@@ -243,16 +235,17 @@ struct TransformOrigin {
bool operator==(TransformOrigin const&) const = default;
};
+// One computed shadow layer, whose color may be `currentcolor`, which `resolved_color()` resolves.
struct ShadowData {
CSSPixels offset_x { 0 };
CSSPixels offset_y { 0 };
CSSPixels blur_radius { 0 };
CSSPixels spread_distance { 0 };
- Color color {};
+ ComputedValuesFFI::StyleColor color {};
ColorSyntax color_syntax { ColorSyntax::Legacy };
ShadowPlacement placement { ShadowPlacement::Outer };
- bool operator==(ShadowData const&) const = default;
+ Color resolved_color(Color current_color) const { return resolve_style_color(color, current_color); }
};
// FIXME: Find a better place for this helper.
@@ -289,29 +282,28 @@ inline Gfx::InterpolationColorSpace to_interpolation_color_space(ColorInterpolat
// Every ComputedValues style value group, in vtable registration order:
// G(enumerator, member path, sharing-info name).
-#define LIBWEB_ENUMERATE_COMPUTED_VALUE_STYLE_GROUPS(G) \
- G(InheritedTableValues, m_inherited.table, "inheritedTable") \
- G(InheritedListValues, m_inherited.list, "inheritedList") \
- G(InheritedUIValues, m_inherited.ui, "inheritedUI") \
- G(InheritedSVGValues, m_inherited.svg, "inheritedSVG") \
- G(InheritedTextValues, m_inherited.text, "inheritedText") \
- G(InheritedBoxValues, m_inherited.box, "inheritedBox") \
- G(FontValues, m_inherited.font, "font") \
- G(AnimationValues, m_noninherited.animation, "animation") \
- G(SVGResetValues, m_noninherited.svg_reset, "svgReset") \
- G(GridValues, m_noninherited.grid, "grid") \
- G(AnchorValues, m_noninherited.anchor, "anchor") \
- G(EffectsValues, m_noninherited.effects, "effects") \
- G(MaskValues, m_noninherited.mask_data, "mask") \
- G(TextResetValues, m_noninherited.text_reset, "textReset") \
- G(ContentValues, m_noninherited.content_data, "content") \
- G(TransformValues, m_noninherited.transform, "transform") \
- G(BackgroundValues, m_noninherited.background, "background") \
- G(BorderValues, m_noninherited.border, "border") \
- G(AlignmentValues, m_noninherited.alignment, "alignment") \
- G(MiscResetValues, m_noninherited.misc, "miscReset") \
- G(SizingValues, m_noninherited.sizing, "sizing") \
- G(SurroundValues, m_noninherited.surround, "surround") \
+#define LIBWEB_ENUMERATE_COMPUTED_VALUE_STYLE_GROUPS(G) \
+ G(InheritedListTableValues, m_inherited.list_table, "inheritedListTable") \
+ G(InheritedUIValues, m_inherited.ui, "inheritedUI") \
+ G(InheritedSVGValues, m_inherited.svg, "inheritedSVG") \
+ G(InheritedTextValues, m_inherited.text, "inheritedText") \
+ G(FontValues, m_inherited.font, "font") \
+ G(AnimationValues, m_noninherited.animation, "animation") \
+ G(SVGResetValues, m_noninherited.svg_reset, "svgReset") \
+ G(GridValues, m_noninherited.grid, "grid") \
+ G(AnchorValues, m_noninherited.anchor, "anchor") \
+ G(ContentValues, m_noninherited.content_data, "content") \
+ G(AlignmentValues, m_noninherited.alignment, "alignment") \
+ G(MiscLayoutValues, m_noninherited.misc_layout, "miscLayout") \
+ G(MiscInteractionValues, m_noninherited.misc_interaction, "miscInteraction") \
+ G(EffectsValues, m_noninherited.effects, "effects") \
+ G(MaskValues, m_noninherited.mask_data, "mask") \
+ G(TextResetValues, m_noninherited.text_reset, "textReset") \
+ G(TransformValues, m_noninherited.transform, "transform") \
+ G(BackgroundValues, m_noninherited.background, "background") \
+ G(BorderValues, m_noninherited.border, "border") \
+ G(SizingValues, m_noninherited.sizing, "sizing") \
+ G(SurroundValues, m_noninherited.surround, "surround") \
G(BoxValues, m_noninherited.box, "box")
class StyleEngine;
@@ -339,46 +331,6 @@ enum class StyleRecordDependencyFlag : u8 {
};
AK_ENUM_BITWISE_OPERATORS(StyleRecordDependencyFlag);
-// The box group payload stores display values in the Rust-defined explicit
-// form; these pins keep the tag discriminants aligned with Display::Type.
-inline ComputedValuesFFI::FfiDisplay to_ffi_display(Display const& display)
-{
- static_assert(to_underlying(Display::Type::OutsideAndInside) == 0);
- static_assert(to_underlying(Display::Type::Internal) == 1);
- static_assert(to_underlying(Display::Type::Box) == 2);
-
- switch (display.type()) {
- case Display::Type::OutsideAndInside:
- return {
- .tag = to_underlying(display.type()),
- .outside = to_underlying(display.outside()),
- .inside = to_underlying(display.inside()),
- .list_item = display.is_list_item(),
- .internal = 0,
- .box_value = 0,
- };
- case Display::Type::Internal:
- return {
- .tag = to_underlying(display.type()),
- .outside = 0,
- .inside = 0,
- .list_item = false,
- .internal = to_underlying(display.internal()),
- .box_value = 0,
- };
- case Display::Type::Box:
- return {
- .tag = to_underlying(display.type()),
- .outside = 0,
- .inside = 0,
- .list_item = false,
- .internal = 0,
- .box_value = display.is_none() ? to_underlying(DisplayBox::None) : to_underlying(DisplayBox::Contents),
- };
- }
- VERIFY_NOT_REACHED();
-}
-
inline Display display_from_ffi_display(ComputedValuesFFI::FfiDisplay const& display)
{
switch (static_cast<Display::Type>(display.tag)) {
@@ -395,6 +347,137 @@ inline Display display_from_ffi_display(ComputedValuesFFI::FfiDisplay const& dis
}
VERIFY_NOT_REACHED();
}
+
+// The inherited longhands a style holds as bits beside its inherited groups, each read at its
+// field's shift and width.
+inline u8 inherited_bits_field(ComputedValuesFFI::InheritedBits bits, u32 shift, u32 width)
+{
+ return static_cast<u8>((bits >> shift) & ((1u << width) - 1));
+}
+
+inline WritingMode writing_mode_from_inherited_bits(ComputedValuesFFI::InheritedBits bits)
+{
+ return static_cast<WritingMode>(inherited_bits_field(bits, ComputedValuesFFI::INHERITED_BITS_WRITING_MODE_SHIFT, ComputedValuesFFI::INHERITED_BITS_WRITING_MODE_WIDTH));
+}
+
+inline Direction direction_from_inherited_bits(ComputedValuesFFI::InheritedBits bits)
+{
+ return static_cast<Direction>(inherited_bits_field(bits, ComputedValuesFFI::INHERITED_BITS_DIRECTION_SHIFT, ComputedValuesFFI::INHERITED_BITS_DIRECTION_WIDTH));
+}
+
+inline Visibility visibility_from_inherited_bits(ComputedValuesFFI::InheritedBits bits)
+{
+ return static_cast<Visibility>(inherited_bits_field(bits, ComputedValuesFFI::INHERITED_BITS_VISIBILITY_SHIFT, ComputedValuesFFI::INHERITED_BITS_VISIBILITY_WIDTH));
+}
+
+inline WhiteSpaceCollapse white_space_collapse_from_inherited_bits(ComputedValuesFFI::InheritedBits bits)
+{
+ return static_cast<WhiteSpaceCollapse>(inherited_bits_field(bits, ComputedValuesFFI::INHERITED_BITS_WHITE_SPACE_COLLAPSE_SHIFT, ComputedValuesFFI::INHERITED_BITS_WHITE_SPACE_COLLAPSE_WIDTH));
+}
+
+inline PointerEvents pointer_events_from_inherited_bits(ComputedValuesFFI::InheritedBits bits)
+{
+ return static_cast<PointerEvents>(inherited_bits_field(bits, ComputedValuesFFI::INHERITED_BITS_POINTER_EVENTS_SHIFT, ComputedValuesFFI::INHERITED_BITS_POINTER_EVENTS_WIDTH));
+}
+
+// https://drafts.csswg.org/css-viewport/#effective-zoom
+inline float effective_zoom_of(ComputedValuesFFI::InheritedSetValues const& values)
+{
+ return bit_cast<float>(values.effective_zoom_bits);
+}
+
+// The properties that do not inherit a style holds as bits in its root, each read at its field's
+// shift and width.
+inline u8 reset_bits_field(ComputedValuesFFI::ResetBits bits, u32 shift, u32 width)
+{
+ return static_cast<u8>((bits >> shift) & ((1u << width) - 1));
+}
+
+inline Float float_from_reset_bits(ComputedValuesFFI::ResetBits bits) { return static_cast<Float>(reset_bits_field(bits, ComputedValuesFFI::RESET_BITS_FLOAT_SHIFT, ComputedValuesFFI::RESET_BITS_FLOAT_WIDTH)); }
+inline Clear clear_from_reset_bits(ComputedValuesFFI::ResetBits bits) { return static_cast<Clear>(reset_bits_field(bits, ComputedValuesFFI::RESET_BITS_CLEAR_SHIFT, ComputedValuesFFI::RESET_BITS_CLEAR_WIDTH)); }
+inline Positioning position_from_reset_bits(ComputedValuesFFI::ResetBits bits) { return static_cast<Positioning>(reset_bits_field(bits, ComputedValuesFFI::RESET_BITS_POSITION_SHIFT, ComputedValuesFFI::RESET_BITS_POSITION_WIDTH)); }
+inline Overflow overflow_x_from_reset_bits(ComputedValuesFFI::ResetBits bits) { return static_cast<Overflow>(reset_bits_field(bits, ComputedValuesFFI::RESET_BITS_OVERFLOW_X_SHIFT, ComputedValuesFFI::RESET_BITS_OVERFLOW_X_WIDTH)); }
+inline Overflow overflow_y_from_reset_bits(ComputedValuesFFI::ResetBits bits) { return static_cast<Overflow>(reset_bits_field(bits, ComputedValuesFFI::RESET_BITS_OVERFLOW_Y_SHIFT, ComputedValuesFFI::RESET_BITS_OVERFLOW_Y_WIDTH)); }
+inline BoxSizing box_sizing_from_reset_bits(ComputedValuesFFI::ResetBits bits) { return static_cast<BoxSizing>(reset_bits_field(bits, ComputedValuesFFI::RESET_BITS_BOX_SIZING_SHIFT, ComputedValuesFFI::RESET_BITS_BOX_SIZING_WIDTH)); }
+
+// The reset bits of the initial style.
+constexpr ComputedValuesFFI::ResetBits initial_reset_bits()
+{
+ return static_cast<ComputedValuesFFI::ResetBits>(
+ (static_cast<u32>(to_underlying(Positioning::Static)) << ComputedValuesFFI::RESET_BITS_POSITION_SHIFT)
+ | (static_cast<u32>(to_underlying(Float::None)) << ComputedValuesFFI::RESET_BITS_FLOAT_SHIFT)
+ | (static_cast<u32>(to_underlying(Clear::None)) << ComputedValuesFFI::RESET_BITS_CLEAR_SHIFT)
+ | (static_cast<u32>(to_underlying(Overflow::Visible)) << ComputedValuesFFI::RESET_BITS_OVERFLOW_X_SHIFT)
+ | (static_cast<u32>(to_underlying(Overflow::Visible)) << ComputedValuesFFI::RESET_BITS_OVERFLOW_Y_SHIFT)
+ | (static_cast<u32>(to_underlying(BoxSizing::ContentBox)) << ComputedValuesFFI::RESET_BITS_BOX_SIZING_SHIFT)
+ | (static_cast<u32>(to_underlying(UnicodeBidi::Normal)) << ComputedValuesFFI::RESET_BITS_UNICODE_BIDI_SHIFT)
+ | (static_cast<u32>(to_underlying(TableLayout::Auto)) << ComputedValuesFFI::RESET_BITS_TABLE_LAYOUT_SHIFT));
+}
+
+// What the inherited set of the initial style holds beside its groups.
+constexpr ComputedValuesFFI::InheritedSetValues initial_inherited_set_values()
+{
+ return {
+ .bits = static_cast<ComputedValuesFFI::InheritedBits>(
+ (static_cast<u32>(to_underlying(WritingMode::HorizontalTb)) << ComputedValuesFFI::INHERITED_BITS_WRITING_MODE_SHIFT)
+ | (static_cast<u32>(to_underlying(Direction::Ltr)) << ComputedValuesFFI::INHERITED_BITS_DIRECTION_SHIFT)
+ | (static_cast<u32>(to_underlying(Visibility::Visible)) << ComputedValuesFFI::INHERITED_BITS_VISIBILITY_SHIFT)
+ | (static_cast<u32>(to_underlying(TextOrientation::Mixed)) << ComputedValuesFFI::INHERITED_BITS_TEXT_ORIENTATION_SHIFT)
+ | (static_cast<u32>(to_underlying(PointerEvents::Auto)) << ComputedValuesFFI::INHERITED_BITS_POINTER_EVENTS_SHIFT)
+ | (static_cast<u32>(to_underlying(ListStylePosition::Outside)) << ComputedValuesFFI::INHERITED_BITS_LIST_STYLE_POSITION_SHIFT)
+ | (static_cast<u32>(to_underlying(BorderCollapse::Separate)) << ComputedValuesFFI::INHERITED_BITS_BORDER_COLLAPSE_SHIFT)
+ | (static_cast<u32>(to_underlying(CaptionSide::Top)) << ComputedValuesFFI::INHERITED_BITS_CAPTION_SIDE_SHIFT)
+ | (static_cast<u32>(to_underlying(EmptyCells::Show)) << ComputedValuesFFI::INHERITED_BITS_EMPTY_CELLS_SHIFT)
+ | (static_cast<u32>(to_underlying(TextAlign::Start)) << ComputedValuesFFI::INHERITED_BITS_TEXT_ALIGN_SHIFT)
+ | (static_cast<u32>(to_underlying(WhiteSpaceCollapse::Collapse)) << ComputedValuesFFI::INHERITED_BITS_WHITE_SPACE_COLLAPSE_SHIFT)
+ | (static_cast<u32>(to_underlying(TextWrapMode::Wrap)) << ComputedValuesFFI::INHERITED_BITS_TEXT_WRAP_MODE_SHIFT)
+ | (static_cast<u32>(to_underlying(WordBreak::Normal)) << ComputedValuesFFI::INHERITED_BITS_WORD_BREAK_SHIFT)),
+ .effective_zoom_bits = bit_cast<u32>(1.0f),
+ };
+}
+
+// One counted reference to a style record, or none.
+class StyleRecordRef {
+public:
+ StyleRecordRef() = default;
+ explicit StyleRecordRef(void const* record);
+ // Takes over the reference to `record` the caller holds.
+ static StyleRecordRef adopt(void const* record)
+ {
+ StyleRecordRef adopted;
+ adopted.m_record = record;
+ return adopted;
+ }
+ StyleRecordRef(StyleRecordRef const& other)
+ : StyleRecordRef(other.m_record)
+ {
+ }
+ StyleRecordRef(StyleRecordRef&& other)
+ : m_record(exchange(other.m_record, nullptr))
+ {
+ }
+ ~StyleRecordRef();
+
+ StyleRecordRef& operator=(StyleRecordRef const& other)
+ {
+ StyleRecordRef copy { other };
+ swap(m_record, copy.m_record);
+ return *this;
+ }
+
+ StyleRecordRef& operator=(StyleRecordRef&& other)
+ {
+ StyleRecordRef moved { move(other) };
+ swap(m_record, moved.m_record);
+ return *this;
+ }
+
+ void const* get() const { return m_record; }
+
+private:
+ void const* m_record { nullptr };
+};
+
class WEB_API ComputedValues final : public RefCounted<ComputedValues> {
AK_MAKE_NONCOPYABLE(ComputedValues);
AK_MAKE_NONMOVABLE(ComputedValues);
@@ -417,6 +500,9 @@ public:
// Callers can serialize straight from the returned handle without minting a wrapper.
RustStyleValueHandle const* stored_style_value_handle(PropertyID) const;
+ // The style record this style is a view of, or is copied from, where it has one.
+ StyleRecordRef const& record() const { return m_record; }
+
ComputedValues const& base_values() const { return m_borrowed_base_values ? *m_borrowed_base_values : m_base_values ? *m_base_values
: *this; }
bool has_animated_values() const { return m_borrowed_base_values || m_base_values; }
@@ -445,24 +531,11 @@ public:
#undef LIBWEB_VISIT_STYLE_GROUP
}
- bool is_property_important(PropertyID property_id) const { return m_property_important.get(property_bitmap_index(property_id)); }
- ReadonlyBytes property_importance_bitmap() const LIFETIME_BOUND { return m_property_important.bytes(); }
- ReadonlyBytes property_inheritance_bitmap() const LIFETIME_BOUND { return m_property_inherited.bytes(); }
+ bool is_property_important(PropertyID) const;
bool depends_on_viewport_metrics() const { return m_depends_on_viewport_metrics; }
bool font_metrics_depend_on_viewport_metrics() const { return m_font_metrics_depend_on_viewport_metrics; }
bool in_display_none_subtree() const { return m_in_display_none_subtree; }
- bool has_pseudo_element_style(PseudoElement pseudo_element) const { return m_pseudo_element_styles & (1ull << to_underlying(pseudo_element)); }
- u64 pseudo_element_style_mask() const { return m_pseudo_element_styles; }
- ReadonlySpan<ComputedValuesFFI::FfiTableInheritanceDependentValue const> inheritance_dependent_specified_values() const { return m_inheritance_dependent_specified_values; }
-
- // The drive's frozen computed longhand table (a Rust ComputedLonghandTable), or null when
- // this style holds only a borrowed span or no table at all.
- void const* computed_longhand_table() const { return m_computed_longhand_table; }
- // One stored data pointer per longhand (null slots where the drive stored no value); empty
- // when this style carries no table. The pointers stay valid while this ComputedValues is
- // live (or, for a borrowed record view, while the style engine retains the record's table).
- ReadonlySpan<void const*> computed_longhand_values() const { return m_longhand_values; }
~ComputedValues();
@@ -470,17 +543,16 @@ private:
public:
ReadonlySpan<Utf16FlyString> anchor_names() const { return m_noninherited.anchor->anchor_names_span(); }
// The animation-name entries other than none.
- Vector<Utf16FlyString> animation_names() const { return m_noninherited.animation->animation_names_value(); }
- Float float_() const { return static_cast<Float>(m_noninherited.box->float_); }
- Clear clear() const { return static_cast<Clear>(m_noninherited.box->clear); }
+ Float float_() const { return float_from_reset_bits(m_noninherited.reset_bits); }
+ Clear clear() const { return clear_from_reset_bits(m_noninherited.reset_bits); }
// https://drafts.csswg.org/css-ui-4/#caret-color
// auto: "User agents should use currentColor." It computes to auto, so the element's own color is read here.
- Color caret_color() const { return m_inherited.ui->caret_color.is_auto ? color() : m_inherited.ui->caret_color_value(); }
+ Color caret_color() const { return m_inherited.ui->caret_color_value(color()); }
ColorInterpolation color_interpolation() const { return m_inherited.svg->color_interpolation_value(); }
FillRule fill_rule() const { return m_inherited.svg->fill_rule_value(); }
PreferredColorScheme color_scheme() const { return m_inherited.ui->color_scheme_value(); }
- ContentVisibility content_visibility() const { return static_cast<ContentVisibility>(m_inherited.box->content_visibility); }
+ ContentVisibility content_visibility() const { return static_cast<ContentVisibility>(m_noninherited.misc_layout->content_visibility); }
ReadonlySpan<ComputedValuesFFI::ComputedCursor> cursor() const { return m_inherited.ui->cursor_span(); }
NonnullRefPtr<StyleValue const> computed_content() const { return m_noninherited.content_data->computed_content_value(); }
bool content_is_normal() const { return m_noninherited.content_data->content_is_normal(); }
@@ -489,21 +561,22 @@ public:
bool content_uses_list_item_counter() const { return generated_content_facts() & ComputedValuesFFI::GENERATED_CONTENT_SHOWS_LIST_ITEM_COUNTER; }
Display display() const { return display_from_ffi_display(m_noninherited.box->display); }
Display display_before_box_type_transformation() const { return display_from_ffi_display(m_noninherited.box->display_before_box_type_transformation); }
- Color text_decoration_color() const { return Color::from_bgra(m_noninherited.text_reset->text_decoration_color); }
+ Color text_decoration_color() const { return resolve_style_color(m_noninherited.text_reset->text_decoration_color, color()); }
ReadonlySpan<ShadowData> text_shadow() const { return m_inherited.text->text_shadow_span(); }
- Positioning position() const { return static_cast<Positioning>(m_noninherited.box->position); }
- Appearance appearance() const { return static_cast<Appearance>(m_noninherited.misc->appearance); }
+ Positioning position() const { return position_from_reset_bits(m_noninherited.reset_bits); }
+ Appearance appearance() const { return static_cast<Appearance>(m_noninherited.misc_layout->appearance); }
float opacity() const { return m_noninherited.effects->opacity; }
- Visibility visibility() const { return static_cast<Visibility>(m_inherited.box->visibility); }
+ Visibility visibility() const { return visibility_from_inherited_bits(m_inherited.values.bits); }
ComputedFilterView backdrop_filter() const { return m_noninherited.effects->backdrop_filter_value(); }
ComputedFilterView filter() const { return m_noninherited.effects->filter_value(); }
ReadonlySpan<ShadowData> box_shadow() const { return m_noninherited.effects->box_shadow_span(); }
ComputedValuesFFI::ComputedSize const& width() const { return m_noninherited.sizing->width; }
ComputedValuesFFI::ComputedSize const& height() const { return m_noninherited.sizing->height; }
- Direction direction() const { return static_cast<Direction>(m_inherited.box->direction); }
- WritingMode writing_mode() const { return static_cast<WritingMode>(m_inherited.box->writing_mode); }
+ Direction direction() const { return direction_from_inherited_bits(m_inherited.values.bits); }
+ WritingMode writing_mode() const { return writing_mode_from_inherited_bits(m_inherited.values.bits); }
// https://drafts.csswg.org/css-viewport/#effective-zoom
- double effective_zoom() const { return m_inherited.box->effective_zoom_value(); }
+ double effective_zoom() const { return effective_zoom_of(m_inherited.values); }
+ ComputedValuesFFI::InheritedSetValues const& inherited_set_values() const { return m_inherited.values; }
ContainerType container_type() const
{
@@ -515,7 +588,7 @@ public:
};
}
MixBlendMode mix_blend_mode() const { return m_noninherited.effects->mix_blend_mode_value(); }
- Optional<Utf16FlyString> view_transition_name() const { return m_noninherited.misc->view_transition_name_value(); }
+ Optional<Utf16FlyString> view_transition_name() const { return m_noninherited.misc_interaction->view_transition_name_value(); }
LengthBox inset() const { return length_box(m_noninherited.surround->inset); }
RefPtr<StyleValue const> anchor_inset(PropertyID property_id) const
@@ -527,29 +600,30 @@ public:
return style_value_from_handle(property_id, reinterpret_cast<RustStyleValueHandle const&>(*handle));
}
LengthBox margin() const { return length_box(m_noninherited.surround->margin); }
- LengthBox scroll_margin() const { return length_box(m_noninherited.misc->scroll_margin); }
+ LengthBox scroll_margin() const { return length_box(m_noninherited.misc_interaction->scroll_margin); }
- BorderData const& border_left() const { return m_noninherited.border->border_left_value(); }
- BorderData const& border_top() const { return m_noninherited.border->border_top_value(); }
- BorderData const& border_right() const { return m_noninherited.border->border_right_value(); }
- BorderData const& border_bottom() const { return m_noninherited.border->border_bottom_value(); }
+ BorderData border_left() const { return m_noninherited.border->border_left_value(color()); }
+ BorderData border_top() const { return m_noninherited.border->border_top_value(color()); }
+ BorderData border_right() const { return m_noninherited.border->border_right_value(color()); }
+ BorderData border_bottom() const { return m_noninherited.border->border_bottom_value(color()); }
- Overflow overflow_x() const { return static_cast<Overflow>(m_noninherited.box->overflow_x); }
- Overflow overflow_y() const { return static_cast<Overflow>(m_noninherited.box->overflow_y); }
+ Overflow overflow_x() const { return overflow_x_from_reset_bits(m_noninherited.reset_bits); }
+ Overflow overflow_y() const { return overflow_y_from_reset_bits(m_noninherited.reset_bits); }
+ ComputedValuesFFI::ResetBits reset_bits() const { return m_noninherited.reset_bits; }
Color color() const { return m_inherited.text->color_value(); }
- Color background_color() const { return m_noninherited.background->background_color_value(); }
+ Color background_color() const { return m_noninherited.background->background_color_value(color()); }
RefPtr<StyleValue const> background_color_style_value() const;
Color webkit_text_fill_color() const { return m_inherited.text->webkit_text_fill_color_value(); }
- void const* list_style_type_data() const { return m_inherited.list->list_style_type.pointer; }
- RefPtr<AbstractImageStyleValue const> list_style_image() const { return m_inherited.list->list_style_image_value(); }
+ void const* list_style_type_data() const { return m_inherited.list_table->list_style_type.pointer; }
+ RefPtr<AbstractImageStyleValue const> list_style_image() const { return m_inherited.list_table->list_style_image_value(); }
// Whether this style reads its tree scope's counter-style registry, which a pseudo-element's does for any named
// counter style.
bool reads_counter_style_environment(bool is_pseudo) const { return ComputedValuesFFI::rust_style_reads_counter_style_environment(static_cast<StyleValueFFI::StyleValueData const*>(m_noninherited.content_data->content.pointer), static_cast<StyleValueFFI::StyleValueData const*>(list_style_type_data()), is_pseudo); }
- Color flood_color() const { return Gfx::Color::from_bgra(m_noninherited.svg_reset->flood_color); }
+ Color flood_color() const { return resolve_style_color(m_noninherited.svg_reset->flood_color, color()); }
float flood_opacity() const { return m_noninherited.svg_reset->flood_opacity; }
NonnullRefPtr<StyleValue const> d() const
@@ -574,11 +648,11 @@ public:
Gfx::FontCascadeList const& font_list() const { return m_inherited.font->font_list_value(); }
CSSPixels font_size() const { return m_inherited.font->font_size; }
double font_weight() const { return m_inherited.font->font_weight; }
- CSSPixels line_height() const { return m_inherited.font->line_height_used; }
+ CSSPixels line_height() const { return m_inherited.font->line_height_used_value(); }
- Color outline_color() const { return Color::from_bgra(m_noninherited.misc->outline_color); }
- Color column_rule_color() const { return Color::from_bgra(m_noninherited.misc->column_rule_color); }
- OutlineStyle outline_style() const { return static_cast<OutlineStyle>(m_noninherited.misc->outline_style); }
+ Color outline_color() const { return resolve_style_color(m_noninherited.misc_layout->outline_color, color()); }
+ Color column_rule_color() const { return resolve_style_color(m_noninherited.misc_layout->column_rule_color, color()); }
+ OutlineStyle outline_style() const { return static_cast<OutlineStyle>(m_noninherited.misc_layout->outline_style); }
int math_depth() const { return m_inherited.font->math_depth; }
@@ -591,7 +665,7 @@ public:
explicit ComputedValues(BorrowedStyleRecord);
private:
- void borrow_style_record_payloads(ReadonlySpan<void const*>);
+ void borrow_style_record_groups(void const* groups);
RefPtr<StyleValue const> style_value_from_handle(PropertyID, RustStyleValueHandle const&) const;
@@ -637,22 +711,17 @@ private:
}
public:
- // The layout and lifecycle of this group are defined in Rust (computed_values.rs).
- struct InheritedTableValues : ComputedValuesFFI::InheritedTableValues {
- static constexpr size_t style_group_index = to_underlying(StyleGroupIndex::InheritedTableValues);
+ struct InheritedListTableValues : ComputedValuesFFI::InheritedListTableValues {
+ static constexpr size_t style_group_index = to_underlying(StyleGroupIndex::InheritedListTableValues);
- bool operator==(InheritedTableValues const& other) const
+ bool operator==(InheritedListTableValues const& other) const
{
- return border_collapse == other.border_collapse
- && caption_side == other.caption_side
- && empty_cells == other.empty_cells
+ return list_style_type.pointer == other.list_style_type.pointer
+ && list_style_image.pointer == other.list_style_image.pointer
+ && quotes.pointer == other.quotes.pointer
&& border_spacing_horizontal == other.border_spacing_horizontal
&& border_spacing_vertical == other.border_spacing_vertical;
}
- };
-
- struct InheritedListValues : ComputedValuesFFI::InheritedListValues {
- static constexpr size_t style_group_index = to_underlying(StyleGroupIndex::InheritedListValues);
RefPtr<AbstractImageStyleValue const> list_style_image_value() const;
};
@@ -660,7 +729,8 @@ public:
struct InheritedUIValues : ComputedValuesFFI::InheritedUIValues {
static constexpr size_t style_group_index = to_underlying(StyleGroupIndex::InheritedUIValues);
- Color caret_color_value() const { return Color::from_bgra(caret_color.used_color); }
+ // An auto caret-color holds `currentcolor`, so it resolves to the element's color too.
+ Color caret_color_value(Color current_color) const { return resolve_style_color(caret_color.color, current_color); }
ReadonlySpan<ComputedValuesFFI::ComputedCursor> cursor_span() const { return { cursor.pointer, cursor.length }; }
static RefPtr<CursorStyleValue const> cursor_style_value(ComputedValuesFFI::ComputedCursor const& value)
{
@@ -670,7 +740,6 @@ public:
static_cast<StyleValueFFI::StyleValueData const*>(value.cursor.pointer)));
return style_value->as_cursor();
}
- PointerEvents pointer_events_value() const { return static_cast<PointerEvents>(pointer_events); }
PreferredColorScheme color_scheme_value() const { return static_cast<PreferredColorScheme>(color_scheme); }
ReadonlySpan<Utf16FlyString> color_schemes_span() const
{
@@ -690,32 +759,19 @@ public:
return {};
auto const* url = static_cast<StyleValueFFI::StyleValueData const*>(paint.url.pointer);
VERIFY(url && url->tag == StyleValueFFI::StyleValueData::Tag::Url);
- return url_from_rust_data(url->url.url, url->url.url_type, url->url.modifiers);
+ return url_from_rust_data(url->url._0->url, url->url._0->url_type, url->url._0->modifiers);
}
Optional<URL> fill_url_value() const { return paint_url_value(fill); }
Optional<URL> stroke_url_value() const { return paint_url_value(stroke); }
FillRule fill_rule_value() const { return static_cast<FillRule>(fill_rule); }
- StrokeLinecap stroke_linecap_value() const { return static_cast<StrokeLinecap>(stroke_linecap); }
- StrokeLinejoin stroke_linejoin_value() const { return static_cast<StrokeLinejoin>(stroke_linejoin); }
ColorInterpolation color_interpolation_value() const { return static_cast<ColorInterpolation>(color_interpolation); }
ColorInterpolation color_interpolation_filters_value() const { return static_cast<ColorInterpolation>(color_interpolation_filters); }
- TextAnchor text_anchor_value() const { return static_cast<TextAnchor>(text_anchor); }
- PaintOrderList paint_order_value() const
- {
- return {
- static_cast<PaintOrder>(paint_order[0]),
- static_cast<PaintOrder>(paint_order[1]),
- static_cast<PaintOrder>(paint_order[2]),
- };
- }
};
struct InheritedTextValues : ComputedValuesFFI::InheritedTextValues {
static constexpr size_t style_group_index = to_underlying(StyleGroupIndex::InheritedTextValues);
- TextAlign text_align_value() const { return static_cast<TextAlign>(text_align); }
- WhiteSpaceCollapse white_space_collapse_value() const { return static_cast<WhiteSpaceCollapse>(white_space_collapse); }
CSSPixels letter_spacing_value() const { return letter_spacing; }
Color color_value() const { return Color::from_bgra(color); }
Color webkit_text_fill_color_value() const { return Color::from_bgra(webkit_text_fill_color); }
@@ -724,32 +780,6 @@ public:
static_assert(sizeof(ShadowData) == sizeof(ComputedValuesFFI::ComputedShadow));
return { reinterpret_cast<ShadowData const*>(text_shadow.pointer), text_shadow.length };
}
- TextTransform text_transform_value() const { return static_cast<TextTransform>(text_transform); }
- };
-
- // The layout and lifecycle of this group are defined in Rust (computed_values.rs). The
- // fields hold the underlying values of the corresponding C++ enums, and the lens getters
- // and setters convert.
- struct InheritedBoxValues : ComputedValuesFFI::InheritedBoxValues {
- static constexpr size_t style_group_index = to_underlying(StyleGroupIndex::InheritedBoxValues);
-
- Visibility visibility_value() const { return static_cast<Visibility>(visibility); }
- Direction direction_value() const { return static_cast<Direction>(direction); }
- WritingMode writing_mode_value() const { return static_cast<WritingMode>(writing_mode); }
- ContentVisibility content_visibility_value() const { return static_cast<ContentVisibility>(content_visibility); }
- // https://drafts.csswg.org/css-viewport/#effective-zoom
- float effective_zoom_value() const { return bit_cast<float>(effective_zoom_bits); }
-
- bool operator==(InheritedBoxValues const& other) const
- {
- return visibility == other.visibility
- && direction == other.direction
- && writing_mode == other.writing_mode
- && content_visibility == other.content_visibility
- && image_rendering == other.image_rendering
- && text_orientation == other.text_orientation
- && effective_zoom_bits == other.effective_zoom_bits;
- }
};
// Rust owns the canonical font values and the derived layout-facing facts.
@@ -759,30 +789,20 @@ public:
WEB_API Gfx::FontCascadeList const& font_list_value() const;
FontStyleKeyword font_style_keyword() const;
+ CSSPixels line_height_used_value() const { return CSSPixels::from_raw(ComputedValuesFFI::rust_font_values_line_height_used_raw(this)); }
};
private:
struct InheritedValues {
InheritedValues() = default;
- explicit InheritedValues(StyleGroupInitialization initialization)
- : table(initialization)
- , list(initialization)
- , ui(initialization)
- , svg(initialization)
- , text(initialization)
- , box(initialization)
- , font(initialization)
- {
- }
-
- StyleStructRef<InheritedTableValues> table;
- StyleStructRef<InheritedListValues> list;
+ StyleStructRef<InheritedListTableValues> list_table;
StyleStructRef<InheritedUIValues> ui;
StyleStructRef<InheritedSVGValues> svg;
StyleStructRef<InheritedTextValues> text;
- StyleStructRef<InheritedBoxValues> box;
StyleStructRef<FontValues> font;
+ // The inherited longhands held as bits beside the inherited groups, and the effective zoom.
+ ComputedValuesFFI::InheritedSetValues values { initial_inherited_set_values() };
};
InheritedValues m_inherited;
@@ -790,8 +810,6 @@ private:
public:
struct AnimationValues : ComputedValuesFFI::AnimationValues {
static constexpr size_t style_group_index = to_underlying(StyleGroupIndex::AnimationValues);
-
- Vector<Utf16FlyString> animation_names_value() const;
};
// The layout and lifecycle of this group are defined in Rust (computed_values.rs).
@@ -823,7 +841,6 @@ public:
ComputedFilterView filter_value() const { return ComputedFilterView { filter }; }
ComputedFilterView backdrop_filter_value() const { return ComputedFilterView { backdrop_filter }; }
MixBlendMode mix_blend_mode_value() const { return static_cast<MixBlendMode>(mix_blend_mode); }
- Isolation isolation_value() const { return static_cast<Isolation>(isolation); }
ReadonlySpan<ShadowData> box_shadow_span() const
{
static_assert(sizeof(ShadowData) == sizeof(ComputedValuesFFI::ComputedShadow));
@@ -837,7 +854,6 @@ public:
// The mask layer the first mask-image names by URL, if it does.
Optional<URL> mask_url_value() const;
- MaskType mask_type_value() const;
Vector<RefPtr<AbstractImageStyleValue const>> mask_images_value() const;
// https://drafts.fxtf.org/css-masking/#the-clip-path
// TODO: Support basic shapes and geometry boxes.
@@ -914,15 +930,9 @@ public:
};
}
TransformStyle transform_style_value() const { return static_cast<TransformStyle>(transform_style); }
- BackfaceVisibility backface_visibility_value() const { return static_cast<BackfaceVisibility>(backface_visibility); }
RefPtr<TransformationStyleValue const> rotate_value() const { return transformation_value(rotate); }
RefPtr<TransformationStyleValue const> translate_value() const { return transformation_value(translate); }
RefPtr<TransformationStyleValue const> scale_value() const { return transformation_value(scale); }
- static void set_transformation(ComputedValuesFFI::ComputedStyleValueHandle& handle, TransformationStyleValue const* value)
- {
- StyleValueFFI::rust_style_value_release(static_cast<StyleValueFFI::StyleValueData const*>(handle.pointer));
- handle.pointer = value ? StyleValueFFI::rust_style_value_retain(value->rust_style_value_data()) : nullptr;
- }
Optional<CSSPixels> perspective_value() const
{
if (!has_perspective)
@@ -943,17 +953,22 @@ public:
struct BackgroundValues : ComputedValuesFFI::BackgroundValues {
static constexpr size_t style_group_index = to_underlying(StyleGroupIndex::BackgroundValues);
- Color background_color_value() const { return Color::from_bgra(background_color); }
+ Color background_color_value(Color current_color) const { return resolve_style_color(background_color, current_color); }
Vector<RefPtr<AbstractImageStyleValue const>> background_images_value() const;
};
struct BorderValues : ComputedValuesFFI::BorderValues {
static constexpr size_t style_group_index = to_underlying(StyleGroupIndex::BorderValues);
- BorderData const& border_left_value() const { return reinterpret_cast<BorderData const&>(border_left); }
- BorderData const& border_top_value() const { return reinterpret_cast<BorderData const&>(border_top); }
- BorderData const& border_right_value() const { return reinterpret_cast<BorderData const&>(border_right); }
- BorderData const& border_bottom_value() const { return reinterpret_cast<BorderData const&>(border_bottom); }
+ BorderData border_left_value(Color current_color) const { return side(border_left, current_color); }
+ BorderData border_top_value(Color current_color) const { return side(border_top, current_color); }
+ BorderData border_right_value(Color current_color) const { return side(border_right, current_color); }
+ BorderData border_bottom_value(Color current_color) const { return side(border_bottom, current_color); }
+
+ static BorderData side(ComputedValuesFFI::ComputedBorderSide const& side, Color current_color)
+ {
+ return { resolve_style_color(side.color, current_color), static_cast<LineStyle>(side.line_style), bit_cast<CSSPixels>(side.width) };
+ }
RefPtr<AbstractImageStyleValue const> border_image_source_value() const;
};
@@ -961,8 +976,12 @@ public:
static constexpr size_t style_group_index = to_underlying(StyleGroupIndex::AlignmentValues);
};
- struct MiscResetValues : ComputedValuesFFI::MiscResetValues {
- static constexpr size_t style_group_index = to_underlying(StyleGroupIndex::MiscResetValues);
+ struct MiscLayoutValues : ComputedValuesFFI::MiscLayoutValues {
+ static constexpr size_t style_group_index = to_underlying(StyleGroupIndex::MiscLayoutValues);
+ };
+
+ struct MiscInteractionValues : ComputedValuesFFI::MiscInteractionValues {
+ static constexpr size_t style_group_index = to_underlying(StyleGroupIndex::MiscInteractionValues);
Optional<Utf16FlyString> view_transition_name_value() const;
ScrollSnapStrictness scroll_snap_strictness_value() const { return static_cast<ScrollSnapStrictness>(scroll_snap_strictness); }
@@ -978,42 +997,20 @@ public:
struct BoxValues : ComputedValuesFFI::BoxValues {
static constexpr size_t style_group_index = to_underlying(StyleGroupIndex::BoxValues);
-
- Display display_value() const { return display_from_ffi_display(display); }
- Float float_value() const { return static_cast<Float>(float_); }
- Clear clear_value() const { return static_cast<Clear>(clear); }
- Positioning position_value() const { return static_cast<Positioning>(position); }
};
private:
struct NonInheritedValues {
NonInheritedValues() = default;
- explicit NonInheritedValues(StyleGroupInitialization initialization)
- : animation(initialization)
- , box(initialization)
- , surround(initialization)
- , sizing(initialization)
- , misc(initialization)
- , alignment(initialization)
- , border(initialization)
- , background(initialization)
- , transform(initialization)
- , effects(initialization)
- , mask_data(initialization)
- , text_reset(initialization)
- , content_data(initialization)
- , anchor(initialization)
- , grid(initialization)
- , svg_reset(initialization)
- {
- }
-
StyleStructRef<AnimationValues> animation;
StyleStructRef<BoxValues> box;
+ // The properties that do not inherit held as bits in the style's root.
+ ComputedValuesFFI::ResetBits reset_bits { initial_reset_bits() };
StyleStructRef<SurroundValues> surround;
StyleStructRef<SizingValues> sizing;
- StyleStructRef<MiscResetValues> misc;
+ StyleStructRef<MiscLayoutValues> misc_layout;
+ StyleStructRef<MiscInteractionValues> misc_interaction;
StyleStructRef<AlignmentValues> alignment;
StyleStructRef<BorderValues> border;
StyleStructRef<BackgroundValues> background;
@@ -1027,47 +1024,103 @@ private:
StyleStructRef<SVGResetValues> svg_reset;
};
- // Retains `table` (releasing any table held before) and points the value span at it.
- void adopt_computed_longhand_table(void const* table);
- void refresh_computed_longhand_table_views();
- // Takes `previous`'s table when every slot and the inheritance inventory hold equal values,
- // so the next publication interns the same pointers and keeps the style-record identity.
- void clear_computed_longhand_table();
- // Takes `other`'s table by reference count, or materializes an owned table from `other`'s
- // borrowed record span, so the copy never outlives its source's storage.
- void copy_computed_longhand_table_from(ComputedValues const& other);
-
NonInheritedValues m_noninherited;
- AK::FixedBitmap<number_of_longhand_properties> m_property_important { false };
- AK::FixedBitmap<number_of_longhand_properties> m_property_inherited { false };
- ReadonlySpan<ComputedValuesFFI::FfiTableInheritanceDependentValue const> m_inheritance_dependent_specified_values;
mutable OwnPtr<HashMap<PropertyID, NonnullRefPtr<StyleValue const>>> m_style_value_cache;
- // The drive's frozen computed longhand table, retained when this style owns a reference;
- // null for borrowed style-record views and for styles built without a drive.
- void const* m_computed_longhand_table { nullptr };
- // One stored data pointer per longhand (null where the drive stored none): the owned table's
- // span, or the span borrowed from the style record's interned table. Empty without a table.
- ReadonlySpan<void const*> m_longhand_values;
+ // The style record the values are a view of, or a copy of a view of, which they keep alive
+ // and read their longhands from.
+ StyleRecordRef m_record;
RefPtr<ComputedValues const> m_base_values;
ComputedValues const* m_borrowed_base_values { nullptr };
RefPtr<AnimatedProperties const> m_animated_properties;
- u64 m_pseudo_element_styles { 0 };
bool m_depends_on_viewport_metrics { false };
bool m_font_metrics_depend_on_viewport_metrics { false };
bool m_in_display_none_subtree { false };
bool m_is_style_record_view { false };
};
-// Reads one group out of a style record's payload array, for a caller that already holds the array
-// and wants more than one group out of it.
+// Reads one group of the style whose groups `record` points at: a style record's, or a style layout
+// made of its own. This is the only place C++ knows how a style finds a group: the groups from
+// ROOT_START on are in the style's root, and a pointer to each of its group sets follows them.
+template<size_t index>
+void const* style_record_group_payload(void const* record)
+{
+ VERIFY(record);
+ auto const* slots = static_cast<void const* const*>(record);
+ constexpr auto root_count = to_underlying(StyleGroupIndex::Count) - ComputedValuesFFI::STYLE_GROUP_ROOT_START;
+ if constexpr (index >= ComputedValuesFFI::STYLE_GROUP_ROOT_START)
+ return slots[index - ComputedValuesFFI::STYLE_GROUP_ROOT_START];
+ else if constexpr (index >= ComputedValuesFFI::STYLE_GROUP_VISUAL_SET_START)
+ return static_cast<void const* const*>(slots[root_count + 2])[index - ComputedValuesFFI::STYLE_GROUP_VISUAL_SET_START];
+ else if constexpr (index >= ComputedValuesFFI::STYLE_GROUP_RARE_SET_START)
+ return static_cast<void const* const*>(slots[root_count + 1])[index - ComputedValuesFFI::STYLE_GROUP_RARE_SET_START];
+ else
+ return static_cast<void const* const*>(slots[root_count])[index];
+}
+
+// Reads what the inherited set of the style whose groups `record` points at holds beside its
+// groups, which follow them in the set.
+inline ComputedValuesFFI::InheritedSetValues const& style_record_inherited_values(void const* record)
+{
+ VERIFY(record);
+ auto const* slots = static_cast<void const* const*>(record);
+ constexpr auto root_count = to_underlying(StyleGroupIndex::Count) - ComputedValuesFFI::STYLE_GROUP_ROOT_START;
+ auto const* inherited_set = static_cast<void const* const*>(slots[root_count]);
+ return *reinterpret_cast<ComputedValuesFFI::InheritedSetValues const*>(inherited_set + ComputedValuesFFI::STYLE_GROUP_RARE_SET_START);
+}
+
+// Reads the reset bits of the style whose groups `record` points at, which follow its set pointers.
+inline ComputedValuesFFI::ResetBits style_record_reset_bits(void const* record)
+{
+ VERIFY(record);
+ auto const* slots = static_cast<void const* const*>(record);
+ constexpr auto root_count = to_underlying(StyleGroupIndex::Count) - ComputedValuesFFI::STYLE_GROUP_ROOT_START;
+ return *reinterpret_cast<ComputedValuesFFI::ResetBits const*>(slots + root_count + 3);
+}
+
+// The groups of a style, laid out as a style record's are, over `payloads`, one per group in group
+// order, with `values` beside the inherited ones and `reset` after the set pointers, for a reader of
+// a style record's groups to read a style no record holds. It counts no reference, and `payloads`
+// must outlive it.
+struct StyleRecordGroupsOverPayloads {
+ AK_MAKE_NONCOPYABLE(StyleRecordGroupsOverPayloads);
+ AK_MAKE_NONMOVABLE(StyleRecordGroupsOverPayloads);
+
+public:
+ StyleRecordGroupsOverPayloads(Array<void const*, to_underlying(StyleGroupIndex::Count)> const& payloads, ComputedValuesFFI::InheritedSetValues values, ComputedValuesFFI::ResetBits reset)
+ : root { payloads[ComputedValuesFFI::STYLE_GROUP_ROOT_START], payloads[ComputedValuesFFI::STYLE_GROUP_ROOT_START + 1], payloads[ComputedValuesFFI::STYLE_GROUP_ROOT_START + 2] }
+ , inherited(inherited_set.groups)
+ , rare(payloads.data() + ComputedValuesFFI::STYLE_GROUP_RARE_SET_START)
+ , visual(payloads.data() + ComputedValuesFFI::STYLE_GROUP_VISUAL_SET_START)
+ , reset(reset)
+ {
+ static_assert(to_underlying(StyleGroupIndex::Count) - ComputedValuesFFI::STYLE_GROUP_ROOT_START == 3);
+ for (size_t index = 0; index < ComputedValuesFFI::STYLE_GROUP_RARE_SET_START; ++index)
+ inherited_set.groups[index] = payloads[index];
+ inherited_set.values = values;
+ }
+
+ void const* root[3];
+ void const* const* inherited;
+ void const* const* rare;
+ void const* const* visual;
+ ComputedValuesFFI::ResetBits reset;
+
+private:
+ // Laid out as a style's inherited set is: its groups, then what it holds beside them, with no
+ // custom properties.
+ struct {
+ void const* groups[ComputedValuesFFI::STYLE_GROUP_RARE_SET_START];
+ ComputedValuesFFI::InheritedSetValues values;
+ void const* custom_properties { nullptr };
+ } inherited_set;
+};
+
template<typename StyleGroup>
-StyleGroup const* style_group_from_payloads(void const* payloads)
+StyleGroup const& style_record_group(void const* record)
{
- if (!payloads)
- return nullptr;
- auto const* payload = static_cast<void const* const*>(payloads)[StyleGroup::style_group_index];
+ auto const* payload = style_record_group_payload<StyleGroup::style_group_index>(record);
VERIFY(payload);
- return static_cast<StyleGroup const*>(payload);
+ return *static_cast<StyleGroup const*>(payload);
}
// A synchronous, allocation-free compatibility surface over the payloads of
@@ -1078,7 +1131,8 @@ class WEB_API ComputedStyleRecordView {
public:
ComputedStyleRecordView() = default;
- ComputedStyleRecordView(StyleEngineFFI::FfiStyleRecordView const&, StyleComputer const&, StyleRecordID, bool owns_style_record_pin);
+ // Holds `style`, which must be present, for as long as the view reads it.
+ explicit ComputedStyleRecordView(InstalledStyle style);
~ComputedStyleRecordView();
explicit operator bool() const { return m_values.has_value(); }
@@ -1094,9 +1148,7 @@ private:
Optional<ComputedValues> m_base_values;
// NB: Only a present view builds its values, so a view of no record costs nothing to make.
Optional<ComputedValues> m_values;
- GC::Ptr<StyleComputer const> m_style_computer;
- StyleRecordID m_style_record_identity;
- bool m_owns_style_record_pin { false };
+ InstalledStyle m_style;
};
class ComputedValues::Mutator final {
@@ -1127,15 +1179,12 @@ public:
{
m_values->m_inherited = values.m_inherited;
m_values->m_noninherited = values.m_noninherited;
- m_values->m_property_important = values.m_property_important;
- m_values->m_property_inherited = values.m_property_inherited;
- m_values->copy_computed_longhand_table_from(values);
+ m_values->m_record = values.m_record;
if (values.m_borrowed_base_values)
m_values->m_base_values = Builder { *values.m_borrowed_base_values }.build();
else
m_values->m_base_values = values.m_base_values;
m_mutator.set_animated_properties(values.m_animated_properties.ptr());
- m_values->m_pseudo_element_styles = values.m_pseudo_element_styles;
m_values->m_depends_on_viewport_metrics = values.m_depends_on_viewport_metrics;
m_values->m_font_metrics_depend_on_viewport_metrics = values.m_font_metrics_depend_on_viewport_metrics;
m_values->m_in_display_none_subtree = values.m_in_display_none_subtree;
diff --git a/Libraries/LibWeb/CSS/CustomPropertyData.cpp b/Libraries/LibWeb/CSS/CustomPropertyData.cpp
index a2a9ac6588f..08077cd7f42 100644
--- a/Libraries/LibWeb/CSS/CustomPropertyData.cpp
+++ b/Libraries/LibWeb/CSS/CustomPropertyData.cpp
@@ -14,77 +14,111 @@
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Element.h>
+// NB: The style engine's store, not the host, allocates an environment.
+template<>
+inline constexpr bool AllocatedWithCustomAllocator<Web::CSS::CustomPropertyData> = true;
+
namespace Web::CSS {
-static Atomic<u64> s_next_custom_property_data_identity { 1 };
static constexpr u8 max_ancestor_count = 32;
static constexpr size_t absorb_threshold = 8;
-CustomPropertyData::CustomPropertyData(OrderedHashMap<Utf16FlyString, StyleProperty> own_values, RefPtr<CustomPropertyData const> parent, RefPtr<CustomPropertyData const> inheritance_parent, u8 ancestor_count, size_t declared_count, void const* prebuilt_rust_store, u64 identity)
- : m_own_values(move(own_values))
- , m_parent(move(parent))
- , m_ancestor_count(ancestor_count)
- , m_declared_count(declared_count)
- , m_identity(identity ? identity : s_next_custom_property_data_identity.fetch_add(1, AK::MemoryOrder::memory_order_relaxed))
- , m_rust_store(prebuilt_rust_store)
+// NB: An environment is its store, so a reference to one is a pointer.
+static_assert(sizeof(RefPtr<CustomPropertyData const>) == sizeof(void*));
+
+static NonnullRefPtr<CustomPropertyData> adopt_store(void const* rust_store)
+{
+ VERIFY(rust_store);
+ return adopt_ref(*const_cast<CustomPropertyData*>(static_cast<CustomPropertyData const*>(rust_store)));
+}
+
+static void const* create_store(OrderedHashMap<Utf16FlyString, StyleProperty> const& own_values, size_t declared_count, CustomPropertyData const* parent, CustomPropertyData const* inheritance_parent)
{
- if (m_rust_store)
- return;
Vector<ComputedValuesFFI::FfiCustomPropertyStoreEntry> entries;
- entries.ensure_capacity(m_own_values.size());
- for (auto const& [name, property] : m_own_values) {
+ entries.ensure_capacity(own_values.size());
+ for (auto const& [name, property] : own_values) {
entries.unchecked_append({
.name_raw = name.to_raw_leaked(),
.important = property.important == Important::Yes,
.data = StyleValueFFI::rust_style_value_retain(property.value->rust_style_value_data()),
});
}
- m_rust_store = ComputedValuesFFI::rust_custom_property_store_create(
- entries.data(), entries.size(), m_declared_count, m_parent ? m_parent->rust_store() : nullptr,
+ return ComputedValuesFFI::rust_custom_property_store_create(
+ entries.data(), entries.size(), declared_count, parent ? parent->rust_store() : nullptr,
inheritance_parent ? inheritance_parent->rust_store() : nullptr);
}
-CustomPropertyData::~CustomPropertyData()
+NonnullRefPtr<CustomPropertyData const> CustomPropertyData::of_store(void const* rust_store)
+{
+ return *static_cast<CustomPropertyData const*>(rust_store);
+}
+
+void CustomPropertyData::ref() const
+{
+ ComputedValuesFFI::rust_custom_property_store_retain(rust_store());
+}
+
+void CustomPropertyData::unref() const
+{
+ ComputedValuesFFI::rust_custom_property_store_destroy(rust_store());
+}
+
+size_t CustomPropertyData::ref_count() const
+{
+ return ComputedValuesFFI::rust_custom_property_store_reference_count(rust_store());
+}
+
+u8 CustomPropertyData::ancestor_count() const
+{
+ return ComputedValuesFFI::rust_custom_property_store_ancestor_count(rust_store());
+}
+
+RefPtr<CustomPropertyData const> CustomPropertyData::parent() const
{
- ComputedValuesFFI::rust_custom_property_store_destroy(m_rust_store);
+ auto const* parent = ComputedValuesFFI::rust_custom_property_store_chain_parent(rust_store());
+ if (!parent)
+ return nullptr;
+ return of_store(parent);
}
NonnullRefPtr<CustomPropertyData> CustomPropertyData::create(
OrderedHashMap<Utf16FlyString, StyleProperty> own_values,
RefPtr<CustomPropertyData const> parent,
- void const* prebuilt_rust_store,
- u64 identity)
+ void const* prebuilt_rust_store)
{
+ // NB: A store the style engine built holds its values already, and lies over its own chain, which compacts itself.
+ if (prebuilt_rust_store)
+ return adopt_store(prebuilt_rust_store);
+
auto declared_count = own_values.size();
if (!parent)
- return adopt_ref(*new CustomPropertyData(move(own_values), nullptr, nullptr, 0, declared_count, prebuilt_rust_store, identity));
+ return adopt_store(create_store(own_values, declared_count, nullptr, nullptr));
- auto inheritance_parent = parent;
+ auto const& inheritance_parent = parent;
// If parent chain is too deep, flatten by copying all ancestor values into own.
- if (parent->m_ancestor_count >= max_ancestor_count - 1) {
+ if (parent->ancestor_count() >= max_ancestor_count - 1) {
parent->for_each_property([&](Utf16FlyString const& name, StyleProperty const& property) {
own_values.ensure(name, [&] { return property; });
});
- return adopt_ref(*new CustomPropertyData(move(own_values), nullptr, move(inheritance_parent), 0, declared_count, prebuilt_rust_store, identity));
+ return adopt_store(create_store(own_values, declared_count, nullptr, inheritance_parent));
}
// If parent has few own values, absorb them to shorten the chain.
- if (parent->m_own_values.size() <= absorb_threshold) {
- for (auto const& [name, property] : parent->m_own_values)
+ if (parent->own_value_count() <= absorb_threshold) {
+ parent->for_each_own_value([&](Utf16FlyString const& name, StyleProperty const& property) {
own_values.ensure(name, [&] { return property; });
- auto grandparent = parent->m_parent;
- u8 ancestor_count = grandparent ? grandparent->m_ancestor_count + 1 : 0;
- return adopt_ref(*new CustomPropertyData(move(own_values), move(grandparent), move(inheritance_parent), ancestor_count, declared_count, prebuilt_rust_store, identity));
+ });
+ auto grandparent = parent->parent();
+ return adopt_store(create_store(own_values, declared_count, grandparent, inheritance_parent));
}
- u8 ancestor_count = parent->m_ancestor_count + 1;
- return adopt_ref(*new CustomPropertyData(move(own_values), move(parent), move(inheritance_parent), ancestor_count, declared_count, prebuilt_rust_store, identity));
+ return adopt_store(create_store(own_values, declared_count, parent, inheritance_parent));
}
NonnullRefPtr<CustomPropertyData> CustomPropertyData::create_animation_overlay(
OrderedHashMap<Utf16FlyString, StyleProperty> animated_values,
- RefPtr<CustomPropertyData const> base, DOM::AbstractElement const& owner)
+ RefPtr<CustomPropertyData const> base)
{
Vector<ComputedValuesFFI::FfiCustomPropertyStoreEntry> entries;
entries.ensure_capacity(animated_values.size());
@@ -95,148 +129,98 @@ NonnullRefPtr<CustomPropertyData> CustomPropertyData::create_animation_overlay(
.data = StyleValueFFI::rust_style_value_retain(property.value->rust_style_value_data()),
});
}
- auto const* rust_store = ComputedValuesFFI::rust_custom_property_store_create_animation_overlay(
- entries.data(), entries.size(), base ? base->rust_store() : nullptr);
- auto declared_count = animated_values.size();
- u8 ancestor_count = base ? base->m_ancestor_count + 1 : 0;
- auto inheritance_parent = base;
- auto data = adopt_ref(*new CustomPropertyData(move(animated_values), move(base), move(inheritance_parent), ancestor_count, declared_count, rust_store));
- data->m_animation_owner = AnimationOwner { owner.element().unique_id(), owner.pseudo_element() };
- return data;
+ return adopt_store(ComputedValuesFFI::rust_custom_property_store_create_animation_overlay(
+ entries.data(), entries.size(), base ? base->rust_store() : nullptr));
+}
+
+static StyleProperty property_of_store_value(bool important, void const* data)
+{
+ return StyleProperty {
+ .important = important ? Important::Yes : Important::No,
+ .property_id = PropertyID::Custom,
+ .value = StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(static_cast<StyleValueFFI::StyleValueData const*>(data))),
+ };
+}
+
+using StoreValueCallback = Function<void(Utf16FlyString const&, StyleProperty const&)>;
+
+static void call_with_store_value(void* context, size_t name_raw, bool important, void const* data)
+{
+ (*static_cast<StoreValueCallback const*>(context))(Utf16FlyString::from_raw(name_raw), property_of_store_value(important, data));
+}
+
+Optional<StyleProperty> CustomPropertyData::get(Utf16FlyString const& name) const
+{
+ bool important = false;
+ auto const* data = ComputedValuesFFI::rust_custom_property_store_get(rust_store(), name.raw_identity(), &important);
+ if (!data)
+ return {};
+ return property_of_store_value(important, data);
+}
+
+void CustomPropertyData::for_each_own_value(StoreValueCallback const& callback) const
+{
+ ComputedValuesFFI::rust_custom_property_store_for_each_own_value(rust_store(), const_cast<StoreValueCallback*>(&callback), call_with_store_value);
+}
+
+void CustomPropertyData::for_each_declared_value(StoreValueCallback const& callback) const
+{
+ ComputedValuesFFI::rust_custom_property_store_for_each_own_entry(rust_store(), const_cast<StoreValueCallback*>(&callback), call_with_store_value);
+}
+
+size_t CustomPropertyData::declared_count() const
+{
+ return ComputedValuesFFI::rust_custom_property_store_declared_count(rust_store());
}
-bool CustomPropertyData::is_animation_overlay_for(DOM::AbstractElement const& element) const
+size_t CustomPropertyData::own_value_count() const
{
- // Compare with the id the element already has rather than ask it for one, which would give an id to every element
- // that inherits an overlay: the owner was given one when the overlay was made.
- return m_animation_owner.has_value()
- && m_animation_owner->pseudo_element == element.pseudo_element()
- && element.element().unique_id_if_assigned() == m_animation_owner->element;
+ return ComputedValuesFFI::rust_custom_property_store_own_count(rust_store());
}
-StyleProperty const* CustomPropertyData::get(Utf16FlyString const& name) const
+bool CustomPropertyData::declares_value(Utf16FlyString const& name, StyleValue const& value) const
{
- if (auto it = m_own_values.find(name); it != m_own_values.end())
- return &it->value;
- if (m_parent)
- return m_parent->get(name);
- return nullptr;
+ return ComputedValuesFFI::rust_custom_property_store_declares_value(rust_store(), name.raw_identity(), value.rust_style_value_data());
}
RefPtr<CustomPropertyData const> CustomPropertyData::inheritable_impl(RefPtr<CustomPropertyData const> inheritable_parent, AK::Function<Optional<CustomPropertyRegistration const&>(Utf16FlyString const&)> get_custom_property_registration) const
{
OrderedHashMap<Utf16FlyString, StyleProperty> inheritable_own_values;
-
- for (auto const& [name, property] : m_own_values) {
+ size_t own_value_count = 0;
+ for_each_own_value([&](Utf16FlyString const& name, StyleProperty const& property) {
+ ++own_value_count;
auto registration = get_custom_property_registration(name);
if (registration.has_value() && !registration->inherit)
- continue;
+ return;
inheritable_own_values.set(name, property);
- }
+ });
// Filtering only non-inherited properties leaves the parent's environment unchanged.
// Preserve its identity instead of inserting an empty layer into the chain.
if (inheritable_own_values.is_empty())
return inheritable_parent;
- if (inheritable_own_values.size() == m_own_values.size() && inheritable_parent.ptr() == m_parent.ptr())
+ if (inheritable_own_values.size() == own_value_count && inheritable_parent.ptr() == parent().ptr())
return this;
return CustomPropertyData::create(move(inheritable_own_values), move(inheritable_parent));
}
-bool CustomPropertyData::declares_same_names(CustomPropertyData const& other) const
-{
- if (m_declared_count != other.m_declared_count)
- return false;
- auto own = m_own_values.begin();
- auto other_own = other.m_own_values.begin();
- for (size_t index = 0; index < m_declared_count; ++index, ++own, ++other_own) {
- if (own->key != other_own->key)
- return false;
- }
- return true;
-}
-
RefPtr<CustomPropertyData const> CustomPropertyData::inheritable(Layout::BegunRead const& read, DOM::Document const& document) const
{
- auto document_identity = reinterpret_cast<FlatPtr>(&document);
- auto generation = document.custom_property_registration_generation();
- if (m_cached_inheritable_document_identity == document_identity && m_cached_inheritable_generation == generation) {
- if (m_cached_inheritable_is_self)
- return RefPtr<CustomPropertyData const>(this);
- return m_cached_inheritable_data;
- }
-
- RefPtr<CustomPropertyData const> inheritable_parent;
- if (m_parent)
- inheritable_parent = m_parent->inheritable(read, document);
-
- // 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.
- RefPtr<CustomPropertyData const> inheritable;
- if (StyleEngine::is_engine_custom_property_environment(m_identity)) {
- auto const& style_computer = document.style_computer();
- auto inheritable_identity = StyleEngineFFI::style_engine_inheritable_custom_property_environment(style_computer.style_engine().host(), &read, m_identity);
- if (inheritable_identity == m_identity)
- inheritable = this;
- else if (inheritable_identity == (inheritable_parent ? inheritable_parent->identity() : 0))
- inheritable = inheritable_parent;
- else
- inheritable = style_computer.engine_custom_property_environment(read, inheritable_identity, inheritable_parent);
- }
- if (!inheritable) {
- inheritable = inheritable_impl(
- inheritable_parent,
- [&](Utf16FlyString const& name) { return document.get_registered_custom_property(name); });
- }
-
- set_inheritable(document, inheritable);
- return inheritable;
-}
-
-void CustomPropertyData::set_inheritable(DOM::Document const& document, RefPtr<CustomPropertyData const> inheritable) const
-{
- // Registration generations are local to each document, so the cache has to include the destination document
- // identity as well. Otherwise a subtree adopted into another document can incorrectly reuse a filtered result
- // that was computed under a different registration set.
- m_cached_inheritable_document_identity = reinterpret_cast<FlatPtr>(&document);
- m_cached_inheritable_generation = document.custom_property_registration_generation();
-
- // We can't store a RefPtr to `this` in m_cached_inheritable_data since it would create a reference cycle so we store
- // that case as a special boolean flag instead.
- m_cached_inheritable_is_self = inheritable.ptr() == this;
- m_cached_inheritable_data = m_cached_inheritable_is_self ? nullptr : move(inheritable);
+ return document.style_computer().inheritable_custom_property_environment(read, *this);
}
void CustomPropertyData::for_each_property(Function<void(Utf16FlyString const&, StyleProperty const&)> callback) const
{
- HashTable<Utf16FlyString> seen;
- for (auto const* node = this; node; node = node->m_parent.ptr()) {
- for (auto const& [name, property] : node->m_own_values) {
- if (seen.set(name) == HashSetResult::KeptExistingEntry)
- continue;
- callback(name, property);
- }
- }
+ ComputedValuesFFI::rust_custom_property_store_for_each_entry(rust_store(), &callback, call_with_store_value);
}
bool CustomPropertyData::is_empty() const
{
- return m_own_values.is_empty() && (!m_parent || m_parent->is_empty());
-}
-
-}
-
-// The style engine keeps the custom-property environment each element holds, with a reference of its own.
-extern "C" void web_css_custom_property_data_reference(void const* data)
-{
- static_cast<Web::CSS::CustomPropertyData const*>(data)->ref();
+ return ComputedValuesFFI::rust_custom_property_store_is_empty(rust_store());
}
-extern "C" void web_css_custom_property_data_unreference(void const* data)
-{
- static_cast<Web::CSS::CustomPropertyData const*>(data)->unref();
}
diff --git a/Libraries/LibWeb/CSS/CustomPropertyData.h b/Libraries/LibWeb/CSS/CustomPropertyData.h
index 56e2cce1d6a..ef23a430de1 100644
--- a/Libraries/LibWeb/CSS/CustomPropertyData.h
+++ b/Libraries/LibWeb/CSS/CustomPropertyData.h
@@ -6,9 +6,9 @@
#pragma once
-#include <AK/AtomicRefCounted.h>
#include <AK/Function.h>
#include <AK/HashMap.h>
+#include <AK/Noncopyable.h>
#include <AK/NumericLimits.h>
#include <AK/QuickSort.h>
#include <AK/RefPtr.h>
@@ -20,114 +20,76 @@
namespace Web::CSS {
-// Chain of custom property maps with structural sharing.
-// Each node stores only the properties declared directly on its element,
-// with a parent pointer to the inherited chain.
-// NB: The style engine references the data elements hold, and may take and give up those references on whichever
+// Whether the custom-property environment an element or pseudo-element holds is the overlay of what its own
+// animations sample, over the environment its style resolves to.
+enum class IsAnimationOverlay : bool {
+ No,
+ Yes,
+};
+
+// Chain of custom property environments with structural sharing. Each node is a Rust store, which holds the
+// properties declared directly on its element, with those it took in from the chain above it, and lies over the store
+// of its parent: a reference to one of these is a reference to the store, counted by the store's own count.
+// NB: The style engine references the stores elements hold, and may take and give up those references on whichever
// thread it runs on.
-class WEB_API CustomPropertyData : public AtomicRefCounted<CustomPropertyData> {
+class WEB_API CustomPropertyData {
+ AK_MAKE_NONCOPYABLE(CustomPropertyData);
+ AK_MAKE_NONMOVABLE(CustomPropertyData);
+
public:
static NonnullRefPtr<CustomPropertyData> create(
OrderedHashMap<Utf16FlyString, StyleProperty> own_values,
RefPtr<CustomPropertyData const> parent,
- // Transfers one strong Rust store reference when non-null.
- void const* prebuilt_rust_store = nullptr,
- // The identity the style engine minted for an environment it resolved; zero mints one here.
- u64 identity = 0);
- // The values `owner`'s animations sample over `base`, the environment it holds beneath them.
+ // Transfers one strong Rust store reference when non-null, which holds the values in place of `own_values`.
+ void const* prebuilt_rust_store = nullptr);
+ // The values an element's animations sample over `base`, the environment it holds beneath them.
static NonnullRefPtr<CustomPropertyData> create_animation_overlay(
OrderedHashMap<Utf16FlyString, StyleProperty> animated_values,
- RefPtr<CustomPropertyData const> base, DOM::AbstractElement const& owner);
- ~CustomPropertyData();
+ RefPtr<CustomPropertyData const> base);
+ // The environment whose store is `rust_store`, a live store, taking a reference to it.
+ static NonnullRefPtr<CustomPropertyData const> of_store(void const* rust_store);
- // Whether these are the values the element's own animations sample. A child that inherits all of its parent's
- // custom properties holds its parent's overlay itself, which is not an animation of the child's.
- bool is_animation_overlay_for(DOM::AbstractElement const&) const;
+ void ref() const;
+ void unref() const;
+ [[nodiscard]] size_t ref_count() const;
- StyleProperty const* get(Utf16FlyString const& name) const;
+ Optional<StyleProperty> get(Utf16FlyString const& name) const;
RefPtr<CustomPropertyData const> inheritable_impl(RefPtr<CustomPropertyData const> inheritable_parent, AK::Function<Optional<CustomPropertyRegistration const&>(Utf16FlyString const&)> get_custom_property_registration) const;
RefPtr<CustomPropertyData const> inheritable(Layout::BegunRead const& read, DOM::Document const&) const;
- // What a child inherits of an environment the style engine resolved, which the engine decided.
- void set_inheritable(DOM::Document const&, RefPtr<CustomPropertyData const>) const;
- OrderedHashMap<Utf16FlyString, StyleProperty> const& own_values() const { return m_own_values; }
+ // The values this node holds itself: the ones its own cascade declared, in declaration order, then the ones it took
+ // in from the chain above it.
+ void for_each_own_value(Function<void(Utf16FlyString const&, StyleProperty const&)> const& callback) const;
+ // The values this node's own cascade declared, in declaration order.
+ void for_each_declared_value(Function<void(Utf16FlyString const&, StyleProperty const&)> const& callback) const;
+ [[nodiscard]] size_t own_value_count() const;
+ // Whether this node's own cascade declared `name` with a value equal to `value`.
+ [[nodiscard]] bool declares_value(Utf16FlyString const& name, StyleValue const& value) const;
// How many of the own values this element's own cascade declared. The rest were absorbed from
// the chain above to keep it short, and are already what that chain resolved them to - so they
// are neither this element's to declare nor its to resolve again. They sit after the declared
// ones, because absorption appends.
- [[nodiscard]] size_t declared_count() const { return m_declared_count; }
-
- // Whether this environment declares the same names, in the same order, as another: what its
- // declared name atoms are made of, whatever the values.
- [[nodiscard]] bool declares_same_names(CustomPropertyData const&) const;
-
- // The engine's identities for the names this environment declares, sorted and deduplicated,
- // worked out once for the environment rather than once for each element handed it: a page whose
- // theme declares a thousand names hands the same thousand to every element under it. Atom ids
- // are process-global, but each document must acquire its own references, so the document that
- // asked is part of what the answer is good for.
- template<typename InternName>
- [[nodiscard]] ReadonlySpan<StyleAtomID> declared_name_atoms(FlatPtr document_identity, u64 atom_generation, InternName&& intern) const
- {
- if (m_cached_name_atoms_document_identity == document_identity && m_cached_name_atoms_generation == atom_generation)
- return m_cached_declared_name_atoms.span();
- m_cached_declared_name_atoms.clear_with_capacity();
- m_cached_declared_name_atoms.ensure_capacity(m_declared_count);
- size_t declared = 0;
- for (auto const& own : m_own_values) {
- if (declared++ >= m_declared_count)
- break;
- m_cached_declared_name_atoms.unchecked_append(intern(own.key));
- }
- quick_sort(m_cached_declared_name_atoms);
- size_t unique = 0;
- for (size_t index = 0; index < m_cached_declared_name_atoms.size(); ++index) {
- if (index == 0 || m_cached_declared_name_atoms[index] != m_cached_declared_name_atoms[unique - 1])
- m_cached_declared_name_atoms[unique++] = m_cached_declared_name_atoms[index];
- }
- m_cached_declared_name_atoms.shrink(unique);
- m_cached_name_atoms_document_identity = document_identity;
- m_cached_name_atoms_generation = atom_generation;
- return m_cached_declared_name_atoms.span();
- }
+ [[nodiscard]] size_t declared_count() const;
void for_each_property(Function<void(Utf16FlyString const&, StyleProperty const&)> callback) const;
- RefPtr<CustomPropertyData const> parent() const { return m_parent; }
+ // The node this one lies over in its chain, or, for the values an element's animations sample, the environment they
+ // lie over. An environment the style engine resolved names the one it was resolved over as its parent instead,
+ // instead.
+ RefPtr<CustomPropertyData const> parent() const;
bool is_empty() const;
- // This monotonic identity remains unambiguous after the object dies, so retained StyleEngine
- // catalogs can name an environment without retaining or dereferencing the C++ object.
- u64 identity() const { return m_identity; }
- void const* rust_store() const { return m_rust_store; }
+ // The environment's identity: the address of its store, which the style engine's catalogs keep alive for as long
+ // as they name it, so no other store takes the address while they do.
+ u64 identity() const { return reinterpret_cast<FlatPtr>(this); }
+ void const* rust_store() const { return this; }
private:
- CustomPropertyData(OrderedHashMap<Utf16FlyString, StyleProperty> own_values, RefPtr<CustomPropertyData const> parent, RefPtr<CustomPropertyData const> inheritance_parent, u8 ancestor_count, size_t declared_count, void const* prebuilt_rust_store, u64 identity = 0);
-
- OrderedHashMap<Utf16FlyString, StyleProperty> m_own_values;
- RefPtr<CustomPropertyData const> m_parent;
- u8 m_ancestor_count { 0 };
- size_t m_declared_count { 0 };
- u64 m_identity { 0 };
- mutable FlatPtr m_cached_name_atoms_document_identity { NumericLimits<FlatPtr>::max() };
- mutable u64 m_cached_name_atoms_generation { 0 };
- mutable Vector<StyleAtomID> m_cached_declared_name_atoms;
- mutable FlatPtr m_cached_inheritable_document_identity { NumericLimits<FlatPtr>::max() };
- mutable size_t m_cached_inheritable_generation { NumericLimits<size_t>::max() };
- mutable RefPtr<CustomPropertyData const> m_cached_inheritable_data;
- mutable bool m_cached_inheritable_is_self { false };
- struct AnimationOwner {
- UniqueNodeID element;
- Optional<PseudoElement> pseudo_element;
- };
- Optional<AnimationOwner> m_animation_owner;
- void const* m_rust_store { nullptr };
+ CustomPropertyData() = delete;
+ ~CustomPropertyData() = delete;
+ u8 ancestor_count() const;
};
}
-
-// The style engine keeps the custom-property environment each element holds, with a reference of its own.
-extern "C" WEB_API void web_css_custom_property_data_reference(void const*);
-extern "C" WEB_API void web_css_custom_property_data_unreference(void const*);
diff --git a/Libraries/LibWeb/CSS/Parser/Helpers.cpp b/Libraries/LibWeb/CSS/Parser/Helpers.cpp
index f8a170a0d1a..11befc7daf7 100644
--- a/Libraries/LibWeb/CSS/Parser/Helpers.cpp
+++ b/Libraries/LibWeb/CSS/Parser/Helpers.cpp
@@ -23,20 +23,19 @@ NonnullRefPtr<CSS::StyleSheetState> parse_css_stylesheet(CSS::Parser::ParsingPar
NonnullRefPtr<CSS::StyleSheetState> parse_css_stylesheet(CSS::Parser::ParsingParams const& context, Utf16View css, Optional<::URL::URL> location, CSS::RustMediaList media_list)
{
if (css.is_empty()) {
- auto style_sheet = CSS::StyleSheetState::create(CSS::RustRuleList {}, nullptr, move(media_list), location);
- style_sheet->set_source_text({});
- return style_sheet;
+ return CSS::StyleSheetState::create(CSS::RustRuleList {}, nullptr, move(media_list), location);
}
- auto style_sheet = CSS::Parser::Parser { context }.parse_as_css_stylesheet(css, location, move(media_list));
- style_sheet->set_source_text(Utf16String::from_utf16(css));
- return style_sheet;
+ return CSS::Parser::Parser { context }.parse_as_css_stylesheet(css, location, move(media_list));
}
-CSS::RustDeclarationBlock parse_css_property_declaration_block(CSS::Parser::ParsingParams const& context, Utf16View css)
+CSS::RustDeclarationBlock parse_css_property_declaration_block(CSS::Parser::ParsingParams const& context, Utf16View css, bool* parsed_cleanly)
{
- if (css.is_empty())
+ if (css.is_empty()) {
+ if (parsed_cleanly)
+ *parsed_cleanly = true;
return { {}, {} };
- return CSS::Parser::Parser { context }.parse_as_property_declaration_block(css);
+ }
+ return CSS::Parser::Parser { context }.parse_as_property_declaration_block(css, parsed_cleanly);
}
CSS::RustDescriptorBlock parse_css_descriptor_declaration_block(CSS::Parser::ParsingParams const& parsing_params, CSS::AtRuleID at_rule_id, Utf16View css)
diff --git a/Libraries/LibWeb/CSS/Parser/Parser.h b/Libraries/LibWeb/CSS/Parser/Parser.h
index 3fd5aeb8713..842fb006f4a 100644
--- a/Libraries/LibWeb/CSS/Parser/Parser.h
+++ b/Libraries/LibWeb/CSS/Parser/Parser.h
@@ -94,7 +94,8 @@ public:
NonnullRefPtr<CSS::StyleSheetState> parse_as_css_stylesheet(Utf16View, Optional<::URL::URL> location, RustMediaList = {});
NonnullRefPtr<StyleSheetState> create_css_stylesheet(RustStyleSheetParse const&, Optional<::URL::URL> location, RustMediaList = {});
- RustDeclarationBlock parse_as_property_declaration_block(Utf16View);
+ // NB: When given, `parsed_cleanly` is set to whether the parse reported no diagnostics or rejected declarations.
+ RustDeclarationBlock parse_as_property_declaration_block(Utf16View, bool* parsed_cleanly = nullptr);
Vector<DevToolsStyleDeclaration> parse_as_devtools_property_declaration_block(Utf16View);
RustDescriptorBlock parse_as_descriptor_declaration_block(Utf16View, AtRuleID);
Optional<RustRule> parse_as_css_rule(Utf16View, bool nested = false);
@@ -185,7 +186,7 @@ namespace Web {
NonnullRefPtr<CSS::StyleSheetState> parse_css_stylesheet(CSS::Parser::ParsingParams const&, StringView, Optional<::URL::URL> location = {}, CSS::RustMediaList media_list = {});
NonnullRefPtr<CSS::StyleSheetState> parse_css_stylesheet(CSS::Parser::ParsingParams const&, Utf16View, Optional<::URL::URL> location = {}, CSS::RustMediaList media_list = {});
-CSS::RustDeclarationBlock parse_css_property_declaration_block(CSS::Parser::ParsingParams const&, Utf16View);
+CSS::RustDeclarationBlock parse_css_property_declaration_block(CSS::Parser::ParsingParams const&, Utf16View, bool* parsed_cleanly = nullptr);
CSS::RustDescriptorBlock parse_css_descriptor_declaration_block(CSS::Parser::ParsingParams const&, CSS::AtRuleID, Utf16View);
RefPtr<CSS::StyleValue const> parse_css_value(CSS::Parser::ParsingParams const&, StringView, CSS::PropertyID);
RefPtr<CSS::StyleValue const> parse_css_value(CSS::Parser::ParsingParams const&, Utf16View, CSS::PropertyID);
diff --git a/Libraries/LibWeb/CSS/Parser/RustSyntaxParsing.cpp b/Libraries/LibWeb/CSS/Parser/RustSyntaxParsing.cpp
index cf2b4e7776c..9df3995032a 100644
--- a/Libraries/LibWeb/CSS/Parser/RustSyntaxParsing.cpp
+++ b/Libraries/LibWeb/CSS/Parser/RustSyntaxParsing.cpp
@@ -235,7 +235,7 @@ Optional<RustRule> Parser::parse_as_keyframe_rule(Utf16View source)
return rules.at(0);
}
-RustDeclarationBlock Parser::parse_as_property_declaration_block(Utf16View source)
+RustDeclarationBlock Parser::parse_as_property_declaration_block(Utf16View source, bool* parsed_cleanly)
{
auto context = make_parse_context(ParseContextMode::Syntax);
// https://drafts.csswg.org/cssom/#parse-a-css-declaration-block
@@ -244,6 +244,8 @@ RustDeclarationBlock Parser::parse_as_property_declaration_block(Utf16View sourc
RustStyleSheetParse parse { handle };
report_diagnostics(parse);
rust_css_syntax_visit_declaration_errors(parse.handle(), report_declaration_error);
+ if (parsed_cleanly)
+ *parsed_cleanly = rust_css_syntax_parse_is_clean(parse.handle());
return RustDeclarationBlock { rust_css_syntax_parse_declaration_block(handle) };
}
diff --git a/Libraries/LibWeb/CSS/Properties.json b/Libraries/LibWeb/CSS/Properties.json
index 9e4e114b7bf..f16b2000af8 100644
--- a/Libraries/LibWeb/CSS/Properties.json
+++ b/Libraries/LibWeb/CSS/Properties.json
@@ -498,7 +498,7 @@
]
},
"appearance": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscLayoutValues",
"animation-type": "discrete",
"inherited": false,
"initial": "none",
@@ -992,7 +992,6 @@
"needs-layout-node-for-resolved-value": true
},
"border-collapse": {
- "style-group": "InheritedTableValues",
"animation-type": "discrete",
"inherited": true,
"initial": "separate",
@@ -1341,7 +1340,7 @@
"requires-computation": "cascaded-value"
},
"border-spacing": {
- "style-group": "InheritedTableValues",
+ "style-group": "InheritedListTableValues",
"_comment": "Follows the newer definition from: https://drafts.csswg.org/css-tables-3/#border-spacing-property",
"animation-type": "by-computed-value",
"inherited": true,
@@ -1500,7 +1499,7 @@
"needs-layout-for-getcomputedstyle": true
},
"box-decoration-break": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscLayoutValues",
"animation-type": "discrete",
"inherited": false,
"initial": "slice",
@@ -1533,7 +1532,7 @@
]
},
"break-after": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscLayoutValues",
"animation-type": "discrete",
"inherited": false,
"initial": "auto",
@@ -1543,7 +1542,7 @@
]
},
"break-before": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscLayoutValues",
"animation-type": "discrete",
"inherited": false,
"initial": "auto",
@@ -1553,7 +1552,7 @@
]
},
"break-inside": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscLayoutValues",
"animation-type": "discrete",
"inherited": false,
"initial": "auto",
@@ -1563,7 +1562,6 @@
]
},
"caption-side": {
- "style-group": "InheritedTableValues",
"animation-type": "discrete",
"inherited": true,
"initial": "top",
@@ -1709,7 +1707,7 @@
]
},
"column-fill": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscLayoutValues",
"animation-type": "discrete",
"inherited": false,
"initial": "balance",
@@ -1734,7 +1732,7 @@
"percentages-resolve-to": "length"
},
"column-height": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscLayoutValues",
"animation-type": "by-computed-value",
"inherited": false,
"initial": "auto",
@@ -1756,7 +1754,7 @@
]
},
"column-rule-color": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscLayoutValues",
"affects-layout": false,
"animation-type": "by-computed-value",
"inherited": false,
@@ -1768,7 +1766,7 @@
]
},
"column-rule-style": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscLayoutValues",
"affects-layout": false,
"animation-type": "discrete",
"inherited": false,
@@ -1779,7 +1777,7 @@
]
},
"column-rule-width": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscLayoutValues",
"affects-layout": false,
"animation-type": "by-computed-value",
"inherited": false,
@@ -1791,7 +1789,7 @@
]
},
"column-span": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscLayoutValues",
"animation-type": "discrete",
"inherited": false,
"initial": "none",
@@ -1938,7 +1936,7 @@
]
},
"content-visibility": {
- "style-group": "InheritedBoxValues",
+ "style-group": "MiscLayoutValues",
"affects-stacking-context": true,
"animation-type": "custom",
"inherited": false,
@@ -2222,7 +2220,6 @@
"requires-computation": "never"
},
"direction": {
- "style-group": "InheritedBoxValues",
"animation-type": "none",
"inherited": true,
"initial": "ltr",
@@ -2263,7 +2260,6 @@
]
},
"empty-cells": {
- "style-group": "InheritedTableValues",
"animation-type": "discrete",
"inherited": true,
"initial": "show",
@@ -3078,7 +3074,7 @@
]
},
"image-rendering": {
- "style-group": "InheritedBoxValues",
+ "style-group": "InheritedUIValues",
"animation-type": "discrete",
"affects-layout": false,
"inherited": true,
@@ -3322,7 +3318,7 @@
]
},
"list-style-image": {
- "style-group": "InheritedListValues",
+ "style-group": "InheritedListTableValues",
"animation-type": "discrete",
"inherited": true,
"initial": "none",
@@ -3335,7 +3331,6 @@
]
},
"list-style-position": {
- "style-group": "InheritedListValues",
"animation-type": "discrete",
"inherited": true,
"initial": "outside",
@@ -3345,7 +3340,7 @@
]
},
"list-style-type": {
- "style-group": "InheritedListValues",
+ "style-group": "InheritedListTableValues",
"animation-type": "discrete",
"inherited": true,
"initial": "disc",
@@ -3846,7 +3841,7 @@
]
},
"object-fit": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscLayoutValues",
"affects-layout": false,
"animation-type": "discrete",
"inherited": false,
@@ -3857,7 +3852,7 @@
]
},
"object-position": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscLayoutValues",
"affects-layout": false,
"animation-type": "repeatable-list",
"affects-layout": false,
@@ -4004,7 +3999,7 @@
]
},
"outline-color": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscLayoutValues",
"affects-layout": false,
"animation-type": "by-computed-value",
"inherited": false,
@@ -4017,7 +4012,7 @@
]
},
"outline-offset": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscLayoutValues",
"affects-layout": false,
"animation-type": "by-computed-value",
"inherited": false,
@@ -4028,7 +4023,7 @@
]
},
"outline-style": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscLayoutValues",
"affects-layout": false,
"animation-type": "by-computed-value",
"inherited": false,
@@ -4039,7 +4034,7 @@
]
},
"outline-width": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscLayoutValues",
"affects-layout": false,
"animation-type": "by-computed-value",
"inherited": false,
@@ -4105,7 +4100,7 @@
}
},
"overflow-clip-margin-bottom": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscLayoutValues",
"animation-type": "by-computed-value",
"inherited": false,
"initial": "0px",
@@ -4137,7 +4132,7 @@
}
},
"overflow-clip-margin-left": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscLayoutValues",
"animation-type": "by-computed-value",
"inherited": false,
"initial": "0px",
@@ -4147,7 +4142,7 @@
"requires-computation": "cascaded-value"
},
"overflow-clip-margin-right": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscLayoutValues",
"animation-type": "by-computed-value",
"inherited": false,
"initial": "0px",
@@ -4157,7 +4152,7 @@
"requires-computation": "cascaded-value"
},
"overflow-clip-margin-top": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscLayoutValues",
"animation-type": "by-computed-value",
"inherited": false,
"initial": "0px",
@@ -4235,7 +4230,7 @@
},
"overscroll-behavior-x": {
"affects-hit-testing": true,
- "style-group": "MiscResetValues",
+ "style-group": "MiscInteractionValues",
"affects-layout": false,
"animation-type": "discrete",
"inherited": false,
@@ -4247,7 +4242,7 @@
},
"overscroll-behavior-y": {
"affects-hit-testing": true,
- "style-group": "MiscResetValues",
+ "style-group": "MiscInteractionValues",
"affects-layout": false,
"animation-type": "discrete",
"inherited": false,
@@ -4481,7 +4476,6 @@
},
"pointer-events": {
"affects-hit-testing": true,
- "style-group": "InheritedUIValues",
"affects-layout": false,
"animation-type": "discrete",
"inherited": true,
@@ -4578,7 +4572,7 @@
]
},
"quotes": {
- "style-group": "InheritedListValues",
+ "style-group": "InheritedListTableValues",
"animation-type": "discrete",
"inherited": true,
"initial": "auto",
@@ -4718,7 +4712,7 @@
},
"scroll-behavior": {
"__comment": "INTEROP: The spec says 'not animatable', but we animate it discretely, matching other engines. See https://github.com/w3c/csswg-drafts/issues/14706",
- "style-group": "MiscResetValues",
+ "style-group": "MiscInteractionValues",
"initial": "auto",
"inherited": false,
"affects-layout": false,
@@ -4766,7 +4760,7 @@
}
},
"scroll-margin-bottom": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscInteractionValues",
"animation-type": "by-computed-value",
"initial": "0",
"inherited": false,
@@ -4799,7 +4793,7 @@
}
},
"scroll-margin-left": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscInteractionValues",
"animation-type": "by-computed-value",
"inherited": false,
"initial": "0",
@@ -4809,7 +4803,7 @@
]
},
"scroll-margin-right": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscInteractionValues",
"animation-type": "by-computed-value",
"inherited": false,
"initial": "0",
@@ -4819,7 +4813,7 @@
]
},
"scroll-margin-top": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscInteractionValues",
"animation-type": "by-computed-value",
"inherited": false,
"initial": "0",
@@ -4875,7 +4869,7 @@
}
},
"scroll-padding-bottom": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscInteractionValues",
"animation-type": "by-computed-value",
"initial": "auto",
"inherited": false,
@@ -4918,7 +4912,7 @@
}
},
"scroll-padding-left": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscInteractionValues",
"animation-type": "by-computed-value",
"inherited": false,
"initial": "auto",
@@ -4933,7 +4927,7 @@
"percentages-resolve-to": "length"
},
"scroll-padding-right": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscInteractionValues",
"animation-type": "by-computed-value",
"inherited": false,
"initial": "auto",
@@ -4948,7 +4942,7 @@
"percentages-resolve-to": "length"
},
"scroll-padding-top": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscInteractionValues",
"animation-type": "by-computed-value",
"inherited": false,
"initial": "auto",
@@ -4963,7 +4957,7 @@
"percentages-resolve-to": "length"
},
"scroll-snap-align": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscInteractionValues",
"affects-layout": false,
"animation-type": "discrete",
"inherited": false,
@@ -4975,7 +4969,7 @@
]
},
"scroll-snap-stop": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscInteractionValues",
"affects-layout": false,
"animation-type": "discrete",
"inherited": false,
@@ -4986,7 +4980,7 @@
]
},
"scroll-snap-type": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscInteractionValues",
"affects-layout": false,
"animation-type": "discrete",
"inherited": false,
@@ -5038,7 +5032,7 @@
"requires-computation": "cascaded-value"
},
"scrollbar-gutter": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscInteractionValues",
"affects-layout": false,
"animation-type": "discrete",
"__comment": "This property should affect layout per-spec, but ladybird always uses overlay scrollbars so it doesn't in practice.",
@@ -5047,7 +5041,7 @@
"requires-computation": "never"
},
"scrollbar-width": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscInteractionValues",
"affects-layout": false,
"animation-type": "by-computed-value",
"inherited": false,
@@ -5063,7 +5057,7 @@
]
},
"shape-image-threshold": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscLayoutValues",
"affects-layout": false,
"animation-type": "by-computed-value",
"inherited": false,
@@ -5074,7 +5068,7 @@
]
},
"shape-margin": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscLayoutValues",
"animation-type": "by-computed-value",
"inherited": false,
"initial": "0",
@@ -5086,7 +5080,7 @@
"percentages-resolve-to": "length"
},
"shape-outside": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscLayoutValues",
"affects-layout": true,
"animation-type": "by-computed-value",
"inherited": false,
@@ -5240,7 +5234,6 @@
]
},
"text-align": {
- "style-group": "InheritedTextValues",
"animation-type": "discrete",
"inherited": true,
"initial": "start",
@@ -5393,7 +5386,6 @@
]
},
"text-orientation": {
- "style-group": "InheritedBoxValues",
"animation-type": "none",
"inherited": true,
"initial": "mixed",
@@ -5482,7 +5474,6 @@
]
},
"text-wrap-mode": {
- "style-group": "InheritedTextValues",
"animation-type": "discrete",
"inherited": true,
"initial": "wrap",
@@ -5530,7 +5521,7 @@
"needs-layout-for-getcomputedstyle": true
},
"touch-action": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscInteractionValues",
"affects-layout": false,
"animation-type": "discrete",
"inherited": false,
@@ -5714,7 +5705,7 @@
]
},
"user-select": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscInteractionValues",
"affects-layout": false,
"animation-type": "discrete",
"inherited": false,
@@ -5802,7 +5793,7 @@
"multiplicity": "coordinating-list"
},
"view-transition-class": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscInteractionValues",
"affects-layout": false,
"animation-type": "discrete",
"inherited": false,
@@ -5817,7 +5808,7 @@
]
},
"view-transition-name": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscInteractionValues",
"affects-layout": false,
"affects-stacking-context": true,
"animation-type": "discrete",
@@ -5833,7 +5824,6 @@
},
"visibility": {
"affects-hit-testing": true,
- "style-group": "InheritedBoxValues",
"animation-type": "custom",
"inherited": true,
"initial": "visible",
@@ -5854,7 +5844,6 @@
]
},
"white-space-collapse": {
- "style-group": "InheritedTextValues",
"animation-type": "discrete",
"inherited": true,
"initial": "collapse",
@@ -5911,7 +5900,7 @@
"needs-layout-for-getcomputedstyle": true
},
"will-change": {
- "style-group": "MiscResetValues",
+ "style-group": "MiscInteractionValues",
"affects-layout": false,
"affects-stacking-context": true,
"animation-type": "none",
@@ -5930,7 +5919,6 @@
]
},
"word-break": {
- "style-group": "InheritedTextValues",
"animation-type": "discrete",
"initial": "normal",
"inherited": true,
@@ -5964,7 +5952,6 @@
"legacy-alias-for": "overflow-wrap"
},
"writing-mode": {
- "style-group": "InheritedBoxValues",
"animation-type": "none",
"inherited": true,
"initial": "horizontal-tb",
diff --git a/Libraries/LibWeb/CSS/RustDeclarationBlock.cpp b/Libraries/LibWeb/CSS/RustDeclarationBlock.cpp
index 4e814f36c65..7c7fcdcdae2 100644
--- a/Libraries/LibWeb/CSS/RustDeclarationBlock.cpp
+++ b/Libraries/LibWeb/CSS/RustDeclarationBlock.cpp
@@ -31,7 +31,7 @@ static StyleProperty wrap_property(FfiDeclaredProperty const& property, HashMap<
return { property.important ? Important::Yes : Important::No, static_cast<PropertyID>(property.property_id), move(value) };
}
-RustDeclarationBlockSnapshot::RustDeclarationBlockSnapshot(DeclarationBlockData const* data)
+RustDeclarationBlockSnapshot::RustDeclarationBlockSnapshot(DeclarationBlockHeader const* data)
: m_data(data)
{
VERIFY(m_data);
@@ -39,7 +39,9 @@ RustDeclarationBlockSnapshot::RustDeclarationBlockSnapshot(DeclarationBlockData
RustDeclarationBlockSnapshot::~RustDeclarationBlockSnapshot()
{
- rust_declaration_data_release(m_data);
+ // NB: A snapshot that was moved from holds no reference.
+ if (m_data)
+ rust_declaration_data_release(m_data);
}
RustDeclarationBlockSnapshot::RustDeclarationBlockSnapshot(RustDeclarationBlockSnapshot&& other)
diff --git a/Libraries/LibWeb/CSS/RustDeclarationBlock.h b/Libraries/LibWeb/CSS/RustDeclarationBlock.h
index 69f337bdcc8..61cdb5dc915 100644
--- a/Libraries/LibWeb/CSS/RustDeclarationBlock.h
+++ b/Libraries/LibWeb/CSS/RustDeclarationBlock.h
@@ -14,20 +14,20 @@
namespace Web::CSS {
-// A read-only Arc<DeclarationBlockData>. The cascade never needs a live CSSOM owner.
+// A read-only reference to a declaration block. The cascade never needs a live CSSOM owner.
class WEB_API RustDeclarationBlockSnapshot {
AK_MAKE_NONCOPYABLE(RustDeclarationBlockSnapshot);
public:
- explicit RustDeclarationBlockSnapshot(Parser::ValueParserFFI::DeclarationBlockData const*);
+ explicit RustDeclarationBlockSnapshot(Parser::ValueParserFFI::DeclarationBlockHeader const*);
~RustDeclarationBlockSnapshot();
RustDeclarationBlockSnapshot(RustDeclarationBlockSnapshot&&);
RustDeclarationBlockSnapshot& operator=(RustDeclarationBlockSnapshot&&);
- Parser::ValueParserFFI::DeclarationBlockData const* data() const { return m_data; }
+ Parser::ValueParserFFI::DeclarationBlockHeader const* data() const { return m_data; }
private:
- Parser::ValueParserFFI::DeclarationBlockData const* m_data;
+ Parser::ValueParserFFI::DeclarationBlockHeader const* m_data;
};
// The declarations live in Rust. These document-thread views retain facade-local resource state.
diff --git a/Libraries/LibWeb/CSS/RustInlineStyleBlocks.h b/Libraries/LibWeb/CSS/RustInlineStyleBlocks.h
new file mode 100644
index 00000000000..22a95694407
--- /dev/null
+++ b/Libraries/LibWeb/CSS/RustInlineStyleBlocks.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Noncopyable.h>
+#include <AK/Utf16View.h>
+#include <LibWeb/CSS/Parser/RustSyntaxParsing.h>
+#include <LibWeb/ValueParserRustFFI.h>
+
+namespace Web::CSS {
+
+// The declaration blocks of a document's style attributes, by their text, so that elements that write the same text
+// hold one block.
+class RustInlineStyleBlocks {
+ AK_MAKE_NONCOPYABLE(RustInlineStyleBlocks);
+ AK_MAKE_NONMOVABLE(RustInlineStyleBlocks);
+
+public:
+ RustInlineStyleBlocks()
+ : m_blocks(Parser::ValueParserFFI::rust_inline_style_blocks_create())
+ {
+ }
+
+ ~RustInlineStyleBlocks() { Parser::ValueParserFFI::rust_inline_style_blocks_destroy(m_blocks); }
+
+ // A new handle to the block of an element that wrote `text`, or null.
+ Parser::ValueParserFFI::DeclarationBlock* find(Utf16View text, bool quirks) const
+ {
+ return Parser::ValueParserFFI::rust_inline_style_blocks_find(m_blocks, Parser::ffi_utf16_view(text), quirks);
+ }
+
+ void insert(Utf16View text, bool quirks, Parser::ValueParserFFI::DeclarationBlock const& block)
+ {
+ Parser::ValueParserFFI::rust_inline_style_blocks_insert(m_blocks, Parser::ffi_utf16_view(text), quirks, &block);
+ }
+
+private:
+ Parser::ValueParserFFI::InlineStyleBlocks* m_blocks;
+};
+
+}
diff --git a/Libraries/LibWeb/CSS/RustRule.h b/Libraries/LibWeb/CSS/RustRule.h
index 2f50d532adc..df211b23aa1 100644
--- a/Libraries/LibWeb/CSS/RustRule.h
+++ b/Libraries/LibWeb/CSS/RustRule.h
@@ -104,7 +104,7 @@ public:
RustFontFeatureValuesSnapshot font_feature_values() const { return RustFontFeatureValuesSnapshot { Parser::ValueParserFFI::rust_rule_view_font_feature_values(&m_view) }; }
RustCompiledFunction compile_function() const { return RustCompiledFunction { Parser::ValueParserFFI::rust_rule_view_compile_function(&m_view) }; }
// The declarations of a @position-try rule, retained for the caller.
- Parser::ValueParserFFI::DeclarationBlockData const* position_try_declarations() const { return Parser::ValueParserFFI::rust_rule_view_position_try_declarations(&m_view); }
+ Parser::ValueParserFFI::DeclarationBlockHeader const* position_try_declarations() const { return Parser::ValueParserFFI::rust_rule_view_position_try_declarations(&m_view); }
Utf16String name() const
{
Utf16String name;
@@ -115,7 +115,7 @@ public:
}
void for_each_keyframe(Function<void(ReadonlySpan<double>, RustDeclarationBlockSnapshot const&)> const& callback) const
{
- Parser::ValueParserFFI::rust_rule_view_keyframes(&m_view, &callback, [](void const* context, double const* keys, size_t count, Parser::ValueParserFFI::DeclarationBlockData const* declarations) {
+ Parser::ValueParserFFI::rust_rule_view_keyframes(&m_view, &callback, [](void const* context, double const* keys, size_t count, Parser::ValueParserFFI::DeclarationBlockHeader const* declarations) {
RustDeclarationBlockSnapshot snapshot { Parser::ValueParserFFI::rust_declaration_data_retain(declarations) };
(*static_cast<Function<void(ReadonlySpan<double>, RustDeclarationBlockSnapshot const&)> const*>(context))({ keys, count }, snapshot);
});
diff --git a/Libraries/LibWeb/CSS/StyleStructRef.h b/Libraries/LibWeb/CSS/StyleStructRef.h
index a2f65989241..cdc4893658b 100644
--- a/Libraries/LibWeb/CSS/StyleStructRef.h
+++ b/Libraries/LibWeb/CSS/StyleStructRef.h
@@ -7,7 +7,6 @@
#pragma once
#include <AK/Atomic.h>
-#include <AK/NumericLimits.h>
#include <AK/StdLibExtras.h>
#include <AK/Types.h>
#include <LibWeb/ComputedValuesRustFFI.h>
@@ -15,14 +14,6 @@
namespace Web::CSS {
-// NB: Must match STYLE_GROUP_STATIC_REFCOUNT in computed_values.rs.
-static constexpr size_t style_group_static_refcount = NumericLimits<size_t>::max();
-
-enum class StyleGroupInitialization {
- Defaults,
- Empty,
-};
-
// A copy-on-write reference to a style value group struct.
//
// The payloads are owned by the Rust side of LibWeb (see computed_values.rs),
@@ -35,8 +26,8 @@ enum class StyleGroupInitialization {
// Copying a StyleStructRef shares the underlying payload by bumping the
// reference count instead of copying the struct. access() returns a mutable
// reference to the payload, cloning it first if it is shared with anyone
-// else. Default-constructed refs share a single intentionally-leaked
-// default-value payload per group type, so they cost no allocation.
+// else. A default-constructed ref is empty until a payload is borrowed,
+// adopted or assigned.
//
// NB: This models the same copy-on-write scheme as WebKit's DataRef and
// Blink's ComputedStyleBase groups, with Stylo's arrangement of the
@@ -44,20 +35,13 @@ enum class StyleGroupInitialization {
template<typename T>
class StyleStructRef {
public:
- StyleStructRef()
- : StyleStructRef(StyleGroupInitialization::Defaults)
- {
- }
-
- // NB: An empty borrowed reference is filled by borrow() or adopt() before its payload is read.
- explicit StyleStructRef(StyleGroupInitialization initialization)
- : m_payload(initialization == StyleGroupInitialization::Defaults ? static_cast<T*>(const_cast<void*>(default_payload())) : nullptr)
- , m_is_borrowed(initialization == StyleGroupInitialization::Empty)
- {
- }
+ // NB: An empty reference is borrowed, so that it is filled by borrow(), adopt() or assignment before
+ // its payload is read.
+ StyleStructRef() = default;
StyleStructRef(StyleStructRef const& other)
: m_payload(other.m_payload)
+ , m_is_borrowed(false)
{
ref();
}
@@ -82,7 +66,7 @@ public:
T const* operator->() const { return m_payload; }
// Returns a mutable reference to the payload, cloning it first if it is
- // shared with anyone else (including the leaked default payload).
+ // shared with anyone else.
T& access()
{
VERIFY(m_payload);
@@ -116,11 +100,8 @@ public:
bool ptr_equals(StyleStructRef const& other) const { return m_payload == other.m_payload; }
- // The shared payload's address, which is the group's identity: two references to the same
- // payload are the same group, and interning a style record is interning that tuple of addresses.
- bool is_default() const { return m_payload == default_payload(); }
-
- static T const& default_value() { return *static_cast<T const*>(default_payload()); }
+ // Whether the payload holds the group's initial values.
+ bool is_default() const { return ComputedValuesFFI::rust_style_group_holds_default_values(T::style_group_index, m_payload); }
bool operator==(StyleStructRef const& other) const
{
@@ -139,20 +120,14 @@ private:
void ref() const
{
VERIFY(m_payload);
- auto& count = refcount();
- if (count.load(AK::memory_order_relaxed) == style_group_static_refcount)
- return;
- count.fetch_add(1, AK::memory_order_relaxed);
+ refcount().fetch_add(1, AK::memory_order_relaxed);
}
void deref()
{
if (m_is_borrowed)
return;
- auto& count = refcount();
- if (count.load(AK::memory_order_relaxed) == style_group_static_refcount)
- return;
- if (count.fetch_sub(1, AK::memory_order_acq_rel) == 1)
+ if (refcount().fetch_sub(1, AK::memory_order_acq_rel) == 1)
ComputedValuesFFI::rust_style_group_free(T::style_group_index, m_payload);
}
@@ -161,14 +136,8 @@ private:
return static_cast<T*>(ComputedValuesFFI::rust_style_group_clone(T::style_group_index, source));
}
- static void const* default_payload()
- {
- static void const* payload = ComputedValuesFFI::rust_style_group_default_payload(T::style_group_index);
- return payload;
- }
-
T* m_payload { nullptr };
- bool m_is_borrowed { false };
+ bool m_is_borrowed { true };
};
}
diff --git a/Libraries/LibWeb/CSS/StyleValues/BackgroundSizeStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/BackgroundSizeStyleValue.h
index 4fbd1b36ae4..e77173c1fb9 100644
--- a/Libraries/LibWeb/CSS/StyleValues/BackgroundSizeStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/BackgroundSizeStyleValue.h
@@ -18,8 +18,8 @@ class BackgroundSizeStyleValue final : public StyleValueWithDefaultOperators<Bac
public:
virtual ~BackgroundSizeStyleValue() override = default;
- ValueComparingNonnullRefPtr<StyleValue const> size_x() const { return wrap_rust_child(m_value->background_size.size_x); }
- ValueComparingNonnullRefPtr<StyleValue const> size_y() const { return wrap_rust_child(m_value->background_size.size_y); }
+ ValueComparingNonnullRefPtr<StyleValue const> size_x() const { return wrap_rust_child(m_value->background_size._0->size_x); }
+ ValueComparingNonnullRefPtr<StyleValue const> size_y() const { return wrap_rust_child(m_value->background_size._0->size_y); }
private:
friend class StyleValue;
diff --git a/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.cpp
index cfed38b89de..280b1bd0309 100644
--- a/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.cpp
+++ b/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.cpp
@@ -85,12 +85,12 @@ ValueComparingNonnullRefPtr<CalculatedStyleValue const> CalculatedStyleValue::cr
NumericType CalculatedStyleValue::resolved_type() const
{
- return from_ffi_numeric_type(m_value->calculated.resolved_type).release_value();
+ return from_ffi_numeric_type(m_value->calculated._0->resolved_type).release_value();
}
CalculationContext CalculatedStyleValue::calculation_context() const
{
- auto const& data = m_value->calculated;
+ auto const& data = *m_value->calculated._0;
CalculationContext context;
if (data.has_percentages_resolve_as)
context.percentages_resolve_as = static_cast<ValueType>(data.percentages_resolve_as);
@@ -285,7 +285,7 @@ Optional<i32> CalculatedStyleValue::resolve_integer(CalculationResolutionContext
bool CalculatedStyleValue::contains_percentage() const
{
// The Rust mirror answers.
- return StyleValueFFI::rust_calc_node_contains_percentage(m_value->calculated.rust_calculation.node);
+ return StyleValueFFI::rust_calc_node_contains_percentage(m_value->calculated._0->rust_calculation.node);
}
// https://drafts.css-houdini.org/css-typed-om-1/#reify-a-math-expression
diff --git a/Libraries/LibWeb/CSS/StyleValues/ColorFunctionStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/ColorFunctionStyleValue.h
index 2b774a7f0f0..f698e929886 100644
--- a/Libraries/LibWeb/CSS/StyleValues/ColorFunctionStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/ColorFunctionStyleValue.h
@@ -33,7 +33,7 @@ public:
ValueComparingNonnullRefPtr<StyleValue const> channel(size_t index) const
{
- auto const& color_function = m_value->color_function;
+ auto const& color_function = *m_value->color_function._0;
switch (index) {
case 0:
return wrap_rust_child(color_function.channel_0);
@@ -48,14 +48,14 @@ public:
{
return { channel(0), channel(1), channel(2) };
}
- ValueComparingRefPtr<StyleValue const> alpha() const { return wrap_rust_child_or_null(m_value->color_function.alpha); }
+ ValueComparingRefPtr<StyleValue const> alpha() const { return wrap_rust_child_or_null(m_value->color_function._0->alpha); }
Optional<Utf16FlyString> name() const
{
- if (!m_value->color_function.has_name)
+ if (!m_value->color_function._0->has_name)
return {};
- return css_string_from_rust(&m_value->color_function.name);
+ return css_string_from_rust(&m_value->color_function._0->name);
}
- ValueComparingRefPtr<StyleValue const> origin_color() const { return wrap_rust_child_or_null(m_value->color_function.origin_color); }
+ ValueComparingRefPtr<StyleValue const> origin_color() const { return wrap_rust_child_or_null(m_value->color_function._0->origin_color); }
ColorFunctionDescriptor const& descriptor() const { return color_function_descriptor_for(*color_type()); }
diff --git a/Libraries/LibWeb/CSS/StyleValues/ColorSchemeStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/ColorSchemeStyleValue.h
index d33074a2ad5..d60305585e2 100644
--- a/Libraries/LibWeb/CSS/StyleValues/ColorSchemeStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/ColorSchemeStyleValue.h
@@ -16,14 +16,14 @@ public:
Vector<Utf16FlyString> schemes() const
{
- auto const& list = m_value->color_scheme.schemes;
+ auto const& list = m_value->color_scheme._0->schemes;
Vector<Utf16FlyString> schemes;
schemes.ensure_capacity(list.length);
for (size_t i = 0; i < list.length; ++i)
schemes.unchecked_append(css_string_from_rust(&list.pointer[i]));
return schemes;
}
- bool only() const { return m_value->color_scheme.only; }
+ bool only() const { return m_value->color_scheme._0->only; }
private:
friend class StyleValue;
diff --git a/Libraries/LibWeb/CSS/StyleValues/ColorStyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/ColorStyleValue.cpp
index 00a36a61907..33a4e323fd0 100644
--- a/Libraries/LibWeb/CSS/StyleValues/ColorStyleValue.cpp
+++ b/Libraries/LibWeb/CSS/StyleValues/ColorStyleValue.cpp
@@ -21,13 +21,21 @@
namespace Web::CSS {
-// The base class color_type()/color_syntax() accessors read the ColorBase prefix through the
-// color_function arm without knowing which color variant they have; every color variant payload
-// must keep the prefix immediately after the Rust discriminant.
-static_assert(offsetof(StyleValueFFI::StyleValueData::ColorFunction_Body, color_base) == sizeof(StyleValueFFI::StyleValueData::Tag));
-static_assert(offsetof(StyleValueFFI::StyleValueData::ColorMix_Body, color_base) == sizeof(StyleValueFFI::StyleValueData::Tag));
-static_assert(offsetof(StyleValueFFI::StyleValueData::LightDark_Body, color_base) == sizeof(StyleValueFFI::StyleValueData::Tag));
-static_assert(offsetof(StyleValueFFI::StyleValueData::ContrastColor_Body, color_base) == sizeof(StyleValueFFI::StyleValueData::Tag));
+StyleValueFFI::ColorBase const& ColorStyleValue::color_base() const
+{
+ switch (m_value->tag) {
+ case StyleValueFFI::StyleValueData::Tag::ColorFunction:
+ return m_value->color_function._0->color_base;
+ case StyleValueFFI::StyleValueData::Tag::ColorMix:
+ return m_value->color_mix._0->color_base;
+ case StyleValueFFI::StyleValueData::Tag::LightDark:
+ return m_value->light_dark._0->color_base;
+ case StyleValueFFI::StyleValueData::Tag::ContrastColor:
+ return m_value->contrast_color.color_base;
+ default:
+ VERIFY_NOT_REACHED();
+ }
+}
ValueComparingNonnullRefPtr<ColorStyleValue const> ColorStyleValue::create_from_color(Color color, ColorSyntax color_syntax, Optional<Utf16FlyString> name)
{
diff --git a/Libraries/LibWeb/CSS/StyleValues/ColorStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/ColorStyleValue.h
index f104ff97916..8424efa2fe1 100644
--- a/Libraries/LibWeb/CSS/StyleValues/ColorStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/ColorStyleValue.h
@@ -45,21 +45,20 @@ public:
XYZD65,
Alpha, // This is used for alpha(from ...), whose result is in the color space of its origin color.
};
- // AD-HOC: Every color variant payload starts with the same ColorBase prefix, so the base
- // class reads it through one arm without knowing which color variant it has. The
- // static_asserts in ColorStyleValue.cpp keep the prefixes in place.
Optional<ColorType> color_type() const
{
- auto const& color_base = m_value->color_function.color_base;
- if (!color_base.has_color_type)
+ auto const& base = color_base();
+ if (!base.has_color_type)
return {};
- return static_cast<ColorType>(color_base.color_type);
+ return static_cast<ColorType>(base.color_type);
}
- ColorSyntax color_syntax() const { return static_cast<ColorSyntax>(m_value->color_function.color_base.color_syntax); }
+ ColorSyntax color_syntax() const { return static_cast<ColorSyntax>(color_base().color_syntax); }
protected:
friend class StyleValue;
+ StyleValueFFI::ColorBase const& color_base() const;
+
explicit ColorStyleValue(StyleValueFFI::StyleValueData const* value)
: StyleValue(Type::Color, value)
{
diff --git a/Libraries/LibWeb/CSS/StyleValues/ContentStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/ContentStyleValue.h
index e6057f3cac4..d24520dd003 100644
--- a/Libraries/LibWeb/CSS/StyleValues/ContentStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/ContentStyleValue.h
@@ -27,9 +27,9 @@ private:
explicit ContentStyleValue(StyleValueFFI::StyleValueData const* data)
: StyleValueWithDefaultOperators(Type::Content, data)
- , m_content(StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(static_cast<StyleValueFFI::StyleValueData const*>(data->content.content.pointer)))->as_value_list())
+ , m_content(StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(static_cast<StyleValueFFI::StyleValueData const*>(data->content._0->content.pointer)))->as_value_list())
{
- auto const* alt_text_data = static_cast<StyleValueFFI::StyleValueData const*>(data->content.alt_text.pointer);
+ auto const* alt_text_data = static_cast<StyleValueFFI::StyleValueData const*>(data->content._0->alt_text.pointer);
if (alt_text_data)
m_alt_text = StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(alt_text_data))->as_value_list();
}
diff --git a/Libraries/LibWeb/CSS/StyleValues/CounterDefinitionsStyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/CounterDefinitionsStyleValue.cpp
index 8adc72cfe42..4234b258f7b 100644
--- a/Libraries/LibWeb/CSS/StyleValues/CounterDefinitionsStyleValue.cpp
+++ b/Libraries/LibWeb/CSS/StyleValues/CounterDefinitionsStyleValue.cpp
@@ -15,7 +15,7 @@ CounterDefinitionsStyleValue::CounterDefinitionsStyleValue(StyleValueFFI::StyleV
Vector<CounterDefinition> CounterDefinitionsStyleValue::counter_definitions() const
{
- auto const& list = m_value->counter_definitions.counter_definitions;
+ auto const& list = m_value->counter_definitions._0->counter_definitions;
Vector<CounterDefinition> counter_definitions;
counter_definitions.ensure_capacity(list.length);
for (size_t i = 0; i < list.length; ++i) {
diff --git a/Libraries/LibWeb/CSS/StyleValues/CursorStyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/CursorStyleValue.cpp
index b0a53d5bc6b..e04673edb33 100644
--- a/Libraries/LibWeb/CSS/StyleValues/CursorStyleValue.cpp
+++ b/Libraries/LibWeb/CSS/StyleValues/CursorStyleValue.cpp
@@ -24,7 +24,7 @@ namespace Web::CSS {
CursorStyleValue::CursorStyleValue(StyleValueFFI::StyleValueData const* data)
: StyleValueWithDefaultOperators(Type::Cursor, data)
, m_image(StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(
- static_cast<StyleValueFFI::StyleValueData const*>(data->cursor.image.pointer)))
+ static_cast<StyleValueFFI::StyleValueData const*>(data->cursor._0->image.pointer)))
->as_abstract_image())
{
}
diff --git a/Libraries/LibWeb/CSS/StyleValues/CursorStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/CursorStyleValue.h
index 414aeca0158..89a818aae1d 100644
--- a/Libraries/LibWeb/CSS/StyleValues/CursorStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/CursorStyleValue.h
@@ -27,8 +27,8 @@ private:
explicit CursorStyleValue(StyleValueFFI::StyleValueData const*);
- ValueComparingRefPtr<StyleValue const> x() const { return wrap_rust_child_or_null(m_value->cursor.x); }
- ValueComparingRefPtr<StyleValue const> y() const { return wrap_rust_child_or_null(m_value->cursor.y); }
+ ValueComparingRefPtr<StyleValue const> x() const { return wrap_rust_child_or_null(m_value->cursor._0->x); }
+ ValueComparingRefPtr<StyleValue const> y() const { return wrap_rust_child_or_null(m_value->cursor._0->y); }
// NB: The image wrapper stays a member: image style values carry C++-side loading state
// (clients, resource requests) keyed on wrapper identity.
diff --git a/Libraries/LibWeb/CSS/StyleValues/FontSourceStyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/FontSourceStyleValue.cpp
index a2cf8007b77..81548a0aae6 100644
--- a/Libraries/LibWeb/CSS/StyleValues/FontSourceStyleValue.cpp
+++ b/Libraries/LibWeb/CSS/StyleValues/FontSourceStyleValue.cpp
@@ -11,7 +11,7 @@ namespace Web::CSS {
FontSourceStyleValue::Source FontSourceStyleValue::source() const
{
- auto const& data = m_value->font_source;
+ auto const& data = *m_value->font_source._0;
if (data.is_local)
return Local { wrap_rust_child(data.local_name) };
diff --git a/Libraries/LibWeb/CSS/StyleValues/FontSourceStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/FontSourceStyleValue.h
index c16a0a2b55a..0bfa3941018 100644
--- a/Libraries/LibWeb/CSS/StyleValues/FontSourceStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/FontSourceStyleValue.h
@@ -24,9 +24,9 @@ public:
Source source() const;
Optional<Utf16FlyString> format() const
{
- if (!m_value->font_source.has_format)
+ if (!m_value->font_source._0->has_format)
return {};
- return css_string_from_rust(&m_value->font_source.format);
+ return css_string_from_rust(&m_value->font_source._0->format);
}
private:
diff --git a/Libraries/LibWeb/CSS/StyleValues/FunctionStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/FunctionStyleValue.h
index 3165967cf1e..c82157e380c 100644
--- a/Libraries/LibWeb/CSS/StyleValues/FunctionStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/FunctionStyleValue.h
@@ -18,8 +18,8 @@ public:
return adopt_ref(*new FunctionStyleValue(move(name), move(value)));
}
- Utf16FlyString name() const { return css_string_from_rust(&m_value->function.name); }
- ValueComparingNonnullRefPtr<StyleValue const> value() const { return wrap_rust_child(m_value->function.value); }
+ Utf16FlyString name() const { return css_string_from_rust(&m_value->function._0->name); }
+ ValueComparingNonnullRefPtr<StyleValue const> value() const { return wrap_rust_child(m_value->function._0->value); }
private:
friend class StyleValue;
diff --git a/Libraries/LibWeb/CSS/StyleValues/ImageSetStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/ImageSetStyleValue.h
index 1f2b041be27..59b4b7e5cf0 100644
--- a/Libraries/LibWeb/CSS/StyleValues/ImageSetStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/ImageSetStyleValue.h
@@ -47,7 +47,7 @@ private:
{
if (m_options.has_value())
return *m_options;
- auto const& list = m_value->image_set.options;
+ auto const& list = m_value->image_set._0->options;
Vector<Option> options;
options.ensure_capacity(list.length);
for (size_t i = 0; i < list.length; ++i) {
diff --git a/Libraries/LibWeb/CSS/StyleValues/ImageStyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/ImageStyleValue.cpp
index 81c59b7a1b3..5f315262662 100644
--- a/Libraries/LibWeb/CSS/StyleValues/ImageStyleValue.cpp
+++ b/Libraries/LibWeb/CSS/StyleValues/ImageStyleValue.cpp
@@ -37,7 +37,7 @@ StyleValueFFI::StyleValueData const* ImageStyleValue::make_image_url_data(URL co
URL ImageStyleValue::url_value() const
{
- auto const& data = m_value->image;
+ auto const& data = *m_value->image._0;
return url_from_rust_data(data.url, data.url_type, data.url_modifiers);
}
@@ -143,7 +143,7 @@ ImageStyleValue::ImageStyleValue(URL const& url, Optional<::URL::URL> style_reso
ImageStyleValue::ImageStyleValue(StyleValueFFI::StyleValueData const* data)
: AbstractImageStyleValue(Type::Image, data)
{
- auto const& context = data->image.resource_context;
+ auto const& context = data->image._0->resource_context;
if (context.has_base_url)
m_style_resource_base_url = DOMURL::parse(url_text_from_rust_data(context.base_url));
if (context.has_parent_style_sheet_origin_clean)
@@ -283,7 +283,7 @@ Optional<::URL::URL> ImageStyleValue::resolved_url(DOM::Document const& document
if (m_resolved_url.has_value())
return m_resolved_url;
- auto url = url_text_from_rust_data(m_value->image.url);
+ auto url = url_text_from_rust_data(m_value->image._0->url);
if (url.is_empty())
return {};
@@ -305,7 +305,7 @@ Optional<ImageStyleValueResourceKey> ImageStyleValue::resource_key(DOM::Document
return {};
// OPTIMIZATION: Most url() values have no request modifiers, so don't rebuild the URL value for those.
- if (m_value->image.url_modifiers.length == 0)
+ if (m_value->image._0->url_modifiers.length == 0)
return ImageStyleValueResourceKey { .url = resolved_url.release_value(), .cross_origin = {}, .integrity = {}, .referrer_policy = {} };
return ImageStyleValueResourceKey::create(resolved_url.release_value(), url_value());
}
diff --git a/Libraries/LibWeb/CSS/StyleValues/PendingSubstitutionStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/PendingSubstitutionStyleValue.h
index 16cfe7eaae1..0f93f11ed7b 100644
--- a/Libraries/LibWeb/CSS/StyleValues/PendingSubstitutionStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/PendingSubstitutionStyleValue.h
@@ -14,6 +14,7 @@ namespace Web::CSS {
class PendingSubstitutionStyleValue final : public StyleValueWithDefaultOperators<PendingSubstitutionStyleValue> {
public:
virtual ~PendingSubstitutionStyleValue() override = default;
+ PropertyID original_shorthand() const { return static_cast<PropertyID>(m_value->pending_substitution.original_shorthand); }
ValueComparingNonnullRefPtr<StyleValue const> original_shorthand_value() const { return wrap_rust_child(m_value->pending_substitution.original_shorthand_value); }
// NB: Pending-substitution values never compare equal (their value is unknown);
diff --git a/Libraries/LibWeb/CSS/StyleValues/ShadowStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/ShadowStyleValue.h
index 0873f44a085..13100b2ea25 100644
--- a/Libraries/LibWeb/CSS/StyleValues/ShadowStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/ShadowStyleValue.h
@@ -40,11 +40,11 @@ public:
}
virtual ~ShadowStyleValue() override = default;
- ValueComparingRefPtr<StyleValue const> color_or_null() const { return wrap_rust_child_or_null(m_value->shadow.color); }
- ValueComparingNonnullRefPtr<StyleValue const> offset_x() const { return wrap_rust_child(m_value->shadow.offset_x); }
- ValueComparingNonnullRefPtr<StyleValue const> offset_y() const { return wrap_rust_child(m_value->shadow.offset_y); }
- ValueComparingRefPtr<StyleValue const> blur_radius_or_null() const { return wrap_rust_child_or_null(m_value->shadow.blur_radius); }
- ValueComparingRefPtr<StyleValue const> spread_distance_or_null() const { return wrap_rust_child_or_null(m_value->shadow.spread_distance); }
+ ValueComparingRefPtr<StyleValue const> color_or_null() const { return wrap_rust_child_or_null(m_value->shadow._0->color); }
+ ValueComparingNonnullRefPtr<StyleValue const> offset_x() const { return wrap_rust_child(m_value->shadow._0->offset_x); }
+ ValueComparingNonnullRefPtr<StyleValue const> offset_y() const { return wrap_rust_child(m_value->shadow._0->offset_y); }
+ ValueComparingRefPtr<StyleValue const> blur_radius_or_null() const { return wrap_rust_child_or_null(m_value->shadow._0->blur_radius); }
+ ValueComparingRefPtr<StyleValue const> spread_distance_or_null() const { return wrap_rust_child_or_null(m_value->shadow._0->spread_distance); }
private:
ShadowStyleValue(
diff --git a/Libraries/LibWeb/CSS/StyleValues/ShorthandStyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/ShorthandStyleValue.cpp
index 28f27eed825..d66a68b0128 100644
--- a/Libraries/LibWeb/CSS/StyleValues/ShorthandStyleValue.cpp
+++ b/Libraries/LibWeb/CSS/StyleValues/ShorthandStyleValue.cpp
@@ -12,8 +12,8 @@ namespace Web::CSS {
ShorthandStyleValue::ShorthandStyleValue(PropertyID shorthand, Vector<PropertyID> sub_properties, Vector<ValueComparingNonnullRefPtr<StyleValue const>> values)
: StyleValueWithDefaultOperators(Type::Shorthand, make_shorthand_data(shorthand, sub_properties, values))
{
- if (m_value->shorthand.sub_properties.length != m_value->shorthand.values.length) {
- dbgln("ShorthandStyleValue: sub_properties and values must be the same size! {} != {}", m_value->shorthand.sub_properties.length, m_value->shorthand.values.length);
+ if (m_value->shorthand._0->sub_properties.length != m_value->shorthand._0->values.length()) {
+ dbgln("ShorthandStyleValue: sub_properties and values must be the same size! {} != {}", m_value->shorthand._0->sub_properties.length, m_value->shorthand._0->values.length());
VERIFY_NOT_REACHED();
}
}
diff --git a/Libraries/LibWeb/CSS/StyleValues/ShorthandStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/ShorthandStyleValue.h
index 203fe9416b9..d335760d99b 100644
--- a/Libraries/LibWeb/CSS/StyleValues/ShorthandStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/ShorthandStyleValue.h
@@ -20,10 +20,10 @@ public:
StyleValueVector values() const
{
- auto const& values = m_value->shorthand.values;
+ auto const& values = m_value->shorthand._0->values;
StyleValueVector result;
- result.ensure_capacity(values.length);
- for (size_t i = 0; i < values.length; ++i) {
+ result.ensure_capacity(values.length());
+ for (size_t i = 0; i < values.length(); ++i) {
auto const* child_data = static_cast<StyleValueFFI::StyleValueData const*>(values.pointer[i].pointer);
result.unchecked_append(StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(child_data)));
}
@@ -57,16 +57,16 @@ private:
return StyleValueFFI::rust_style_value_create_shorthand(to_underlying(shorthand), property_ids.data(), property_ids.size(), pointers.data(), pointers.size());
}
- size_t size() const { return m_value->shorthand.values.length; }
+ size_t size() const { return m_value->shorthand._0->values.length(); }
PropertyID sub_property_at(size_t i) const
{
- return static_cast<PropertyID>(m_value->shorthand.sub_properties.pointer[i]);
+ return static_cast<PropertyID>(m_value->shorthand._0->sub_properties.pointer[i]);
}
ValueComparingNonnullRefPtr<StyleValue const> value_at(size_t i) const
{
- auto const* child_data = static_cast<StyleValueFFI::StyleValueData const*>(m_value->shorthand.values.pointer[i].pointer);
+ auto const* child_data = static_cast<StyleValueFFI::StyleValueData const*>(m_value->shorthand._0->values.pointer[i].pointer);
return StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(child_data));
}
};
diff --git a/Libraries/LibWeb/CSS/StyleValues/StyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/StyleValue.cpp
index 280f9c6fc85..04c72827e39 100644
--- a/Libraries/LibWeb/CSS/StyleValues/StyleValue.cpp
+++ b/Libraries/LibWeb/CSS/StyleValues/StyleValue.cpp
@@ -499,8 +499,8 @@ GC::Ref<CSSStyleValue> StyleValue::reify(Utf16FlyString const& associated_proper
return as_display().reify(associated_property);
case Type::Easing:
// NB: Preserve authored step keywords until computation canonicalizes them to steps().
- if (m_value->easing.is_keyword)
- return CSSKeywordValue::create(m_value->easing.step_position == to_underlying(StepPosition::Start) ? "step-start"_utf16_fly_string : "step-end"_utf16_fly_string);
+ if (m_value->easing._0->is_keyword)
+ return CSSKeywordValue::create(m_value->easing._0->step_position == to_underlying(StepPosition::Start) ? "step-start"_utf16_fly_string : "step-end"_utf16_fly_string);
break;
case Type::Integer:
return as_integer().reify(associated_property);
diff --git a/Libraries/LibWeb/CSS/StyleValues/StyleValueList.h b/Libraries/LibWeb/CSS/StyleValues/StyleValueList.h
index 575957f2869..fb448c955ee 100644
--- a/Libraries/LibWeb/CSS/StyleValues/StyleValueList.h
+++ b/Libraries/LibWeb/CSS/StyleValues/StyleValueList.h
@@ -28,13 +28,13 @@ public:
return adopt_ref(*new (nothrow) StyleValueList(move(values), separator, collapsible));
}
- size_t size() const { return m_value->value_list.values.length; }
+ size_t size() const { return m_value->value_list.values.length(); }
StyleValueVector values() const
{
auto const& values = m_value->value_list.values;
StyleValueVector result;
- result.ensure_capacity(values.length);
- for (size_t i = 0; i < values.length; ++i) {
+ result.ensure_capacity(values.length());
+ for (size_t i = 0; i < values.length(); ++i) {
auto* child_data = static_cast<StyleValueFFI::StyleValueData const*>(values.pointer[i].pointer);
result.unchecked_append(StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(child_data)));
}
diff --git a/Libraries/LibWeb/CSS/StyleValues/TransformationStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/TransformationStyleValue.h
index 6a8d779aff8..af973c92a24 100644
--- a/Libraries/LibWeb/CSS/StyleValues/TransformationStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/TransformationStyleValue.h
@@ -22,13 +22,13 @@ public:
}
virtual ~TransformationStyleValue() override = default;
- TransformFunction transform_function() const { return static_cast<TransformFunction>(m_value->transformation.transform_function); }
+ TransformFunction transform_function() const { return static_cast<TransformFunction>(m_value->transformation._0->transform_function); }
StyleValueVector values() const
{
- auto const& values = m_value->transformation.values;
+ auto const& values = m_value->transformation._0->values;
StyleValueVector result;
- result.ensure_capacity(values.length);
- for (size_t i = 0; i < values.length; ++i) {
+ result.ensure_capacity(values.length());
+ for (size_t i = 0; i < values.length(); ++i) {
auto* child_data = static_cast<StyleValueFFI::StyleValueData const*>(values.pointer[i].pointer);
result.unchecked_append(StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(child_data)));
}
@@ -59,15 +59,15 @@ private:
return StyleValueFFI::rust_style_value_create_transformation(to_underlying(property), static_cast<u8>(to_underlying(transform_function)), pointers.data(), pointers.size());
}
- size_t size() const { return m_value->transformation.values.length; }
+ size_t size() const { return m_value->transformation._0->values.length(); }
ValueComparingNonnullRefPtr<StyleValue const> value_at(size_t i) const
{
- auto* child_data = static_cast<StyleValueFFI::StyleValueData const*>(m_value->transformation.values.pointer[i].pointer);
+ auto* child_data = static_cast<StyleValueFFI::StyleValueData const*>(m_value->transformation._0->values.pointer[i].pointer);
return StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(child_data));
}
- PropertyID property() const { return static_cast<PropertyID>(m_value->transformation.property); }
+ PropertyID property() const { return static_cast<PropertyID>(m_value->transformation._0->property); }
};
// The transform functions of a computed or freshly parsed transform value:
diff --git a/Libraries/LibWeb/CSS/StyleValues/URLStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/URLStyleValue.h
index f6efe29a86b..5a6922537be 100644
--- a/Libraries/LibWeb/CSS/StyleValues/URLStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/URLStyleValue.h
@@ -65,7 +65,7 @@ public:
URL url() const
{
- auto const& data = m_value->url;
+ auto const& data = *m_value->url._0;
return url_from_rust_data(data.url, data.url_type, data.modifiers);
}
diff --git a/Libraries/LibWeb/CSS/StyleValues/UnresolvedStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/UnresolvedStyleValue.h
index 02fd8b03ed8..fa99438bf1d 100644
--- a/Libraries/LibWeb/CSS/StyleValues/UnresolvedStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/UnresolvedStyleValue.h
@@ -29,8 +29,8 @@ public:
static ValueComparingNonnullRefPtr<UnresolvedStyleValue const> create_attr_tainted_with_parsed_value(Utf16String token_source, Parser::SubstitutionFunctionsPresence, SourceTextMode, NonnullRefPtr<StyleValue const> parsed_value);
virtual ~UnresolvedStyleValue() override = default;
- bool contains_attr_tainted_values() const { return m_value->unresolved.contains_attr_tainted_values; }
- RefPtr<StyleValue const> parsed_value() const { return wrap_rust_child_or_null(m_value->unresolved.parsed_value); }
+ bool contains_attr_tainted_values() const { return m_value->unresolved._0.pointer->contains_attr_tainted_values; }
+ RefPtr<StyleValue const> parsed_value() const { return wrap_rust_child_or_null(m_value->unresolved._0.pointer->parsed_value); }
GC::Ref<CSSStyleValue> reify(Utf16FlyString const& associated_property) const;
diff --git a/Libraries/LibWeb/Rust/src/cow_column.rs b/Libraries/LibWeb/Rust/src/cow_column.rs
index 4d737b173bd..dec8b1d6e7f 100644
--- a/Libraries/LibWeb/Rust/src/cow_column.rs
+++ b/Libraries/LibWeb/Rust/src/cow_column.rs
@@ -109,7 +109,49 @@ impl<T, const CHUNK: usize> Clone for ColumnSnapshot<T, CHUNK> {
}
}
+/// The bytes of the spine, groups and chunks of `spine` that `sizer` reaches for the first time,
+/// with what `row_heap` says each row of such a chunk holds.
+fn spine_heap_size<T, const CHUNK: usize>(
+ spine: &Spine<T, CHUNK>,
+ sizer: &mut crate::heap_size::HeapSizer,
+ row_heap: &mut impl FnMut(&T, &mut crate::heap_size::HeapSizer) -> usize,
+) -> usize {
+ use crate::heap_size::ARC_HEADER_BYTES;
+ if !sizer.first_sight(Arc::as_ptr(spine)) {
+ return 0;
+ }
+ let mut bytes = ARC_HEADER_BYTES + size_of_val::<[Arc<Group<T, CHUNK>>]>(spine);
+ for group in spine.iter() {
+ if !sizer.first_sight(Arc::as_ptr(group)) {
+ continue;
+ }
+ bytes += ARC_HEADER_BYTES + size_of::<Group<T, CHUNK>>();
+ for chunk in group.0.iter().flatten() {
+ if !sizer.first_sight(Arc::as_ptr(chunk)) {
+ continue;
+ }
+ // NB: The chunk's alignment pads the reference counts in front of it to a cache line.
+ bytes += size_of::<Chunk<T, CHUNK>>().max(ARC_HEADER_BYTES)
+ + align_of::<Chunk<T, CHUNK>>()
+ + chunk.0.iter().map(|row| row_heap(row, sizer)).sum::<usize>();
+ }
+ }
+ bytes
+}
+
impl<T: Clone + Default, const CHUNK: usize> CowColumn<T, CHUNK> {
+ /// The bytes the column holds that `sizer` reaches for the first time, with what `row_heap`
+ /// says each row holds.
+ pub(crate) fn heap_size(
+ &self,
+ sizer: &mut crate::heap_size::HeapSizer,
+ mut row_heap: impl FnMut(&T, &mut crate::heap_size::HeapSizer) -> usize,
+ ) -> usize {
+ crate::heap_size::vec_bytes(&self.chunks)
+ + crate::heap_size::vec_bytes(&self.unshared)
+ + spine_heap_size(&self.spine, sizer, &mut row_heap)
+ }
+
const CHUNK_IS_NOT_EMPTY: () = assert!(CHUNK > 0);
#[inline]
@@ -172,6 +214,11 @@ impl<T: Clone + Default, const CHUNK: usize> CowColumn<T, CHUNK> {
}
}
+ /// How many rows the column holds: whole chunks, the rows it was never asked for reading as the default.
+ pub(crate) fn len(&self) -> usize {
+ self.chunks.len() * CHUNK
+ }
+
/// How far the column has been written. A snapshot reads as the column does for as long as the version stays what
/// it was when the snapshot was published, whoever published since: every write advances it, except one to a chunk
/// the column already made its own after it last published, whose first write did.
@@ -225,6 +272,16 @@ impl<T: Clone + Default + PartialEq, const CHUNK: usize> CowColumn<T, CHUNK> {
Some(())
}
+ /// Sets the row at `index` as [`Self::set`] does, answering what the row held. `None` if the column does not hold
+ /// the row.
+ pub(crate) fn replace(&mut self, index: usize, value: T) -> Option<T> {
+ self.get(index)?;
+ if self.owns_chunk_of(index) || *self.get(index)? != value {
+ return Some(std::mem::replace(self.owned_row(index)?, value));
+ }
+ Some(value)
+ }
+
/// The row at `index`, for writing. See [`RowMut`].
pub(crate) fn row_mut(&mut self, index: usize) -> Option<RowMut<&mut Self, T, CHUNK>> {
RowMut::new(self, index)
@@ -308,6 +365,56 @@ where
}
impl<T, const CHUNK: usize> ColumnSnapshot<T, CHUNK> {
+ /// Whether `other` is this very generation of the column: one no write came between.
+ pub(crate) fn is_same_generation_as(&self, other: &Self) -> bool {
+ Arc::ptr_eq(&self.spine, &other.spine)
+ }
+
+ /// The bytes of the snapshot's chunks that `sizer` reaches for the first time, with what
+ /// `row_heap` says each row holds.
+ pub(crate) fn heap_size(
+ &self,
+ sizer: &mut crate::heap_size::HeapSizer,
+ mut row_heap: impl FnMut(&T, &mut crate::heap_size::HeapSizer) -> usize,
+ ) -> usize {
+ spine_heap_size(&self.spine, sizer, &mut row_heap)
+ }
+
+ /// The rows of the chunks this snapshot holds other than `older` does, as ranges of row indices: a chunk either
+ /// holds and the other does not, or that the two hold different allocations of. A group both share is skipped
+ /// whole, so the cost follows the chunks written between the two generations rather than the column's size.
+ pub(crate) fn changed_rows_since(&self, older: &Self) -> Vec<std::ops::Range<usize>> {
+ let mut changed = Vec::new();
+ if Arc::ptr_eq(&self.spine, &older.spine) {
+ return changed;
+ }
+ for group_index in 0..self.spine.len().max(older.spine.len()) {
+ let (group, older_group) = (self.spine.get(group_index), older.spine.get(group_index));
+ if let (Some(group), Some(older_group)) = (group, older_group)
+ && Arc::ptr_eq(group, older_group)
+ {
+ continue;
+ }
+ for chunk_in_group in 0..GROUP {
+ let chunk = group.and_then(|group| group.0[chunk_in_group].as_ref());
+ let older_chunk = older_group.and_then(|group| group.0[chunk_in_group].as_ref());
+ let same = match (chunk, older_chunk) {
+ (Some(chunk), Some(older_chunk)) => Arc::ptr_eq(chunk, older_chunk),
+ (None, None) => true,
+ _ => false,
+ };
+ if !same {
+ let start = (group_index * GROUP + chunk_in_group) * CHUNK;
+ match changed.last_mut() {
+ Some(last) if last.end == start => last.end = start + CHUNK,
+ _ => changed.push(start..start + CHUNK),
+ }
+ }
+ }
+ }
+ changed
+ }
+
/// How many rows the snapshot has room for: every row index below it may be read.
pub(crate) fn slot_capacity(&self) -> usize {
self.spine.last().map_or(0, |last| {
@@ -342,6 +449,104 @@ const _: () = {
assert_send_and_sync::<ColumnSnapshot<u64, 64>>();
};
+/// A vector whose fork shares its storage, as a [`CowColumn`]'s does: cloning it costs a reference count per chunk,
+/// and each side copies a chunk the other shares the first time it writes there. Rows past `len` read as the default
+/// and are reset to it before the vector grows over them again.
+pub(crate) struct CowVec<T, const CHUNK: usize> {
+ column: CowColumn<T, CHUNK>,
+ len: usize,
+}
+
+impl<T, const CHUNK: usize> Default for CowVec<T, CHUNK> {
+ fn default() -> Self {
+ Self {
+ column: CowColumn::default(),
+ len: 0,
+ }
+ }
+}
+
+impl<T: Clone + Default, const CHUNK: usize> Clone for CowVec<T, CHUNK> {
+ fn clone(&self) -> Self {
+ Self {
+ column: self.column.clone(),
+ len: self.len,
+ }
+ }
+}
+
+impl<T: Clone + Default, const CHUNK: usize> CowVec<T, CHUNK> {
+ pub(crate) fn len(&self) -> usize {
+ self.len
+ }
+
+ /// The bytes the vector holds that `sizer` reaches for the first time, with what `row_heap` says each row holds.
+ pub(crate) fn heap_size(
+ &self,
+ sizer: &mut crate::heap_size::HeapSizer,
+ row_heap: impl FnMut(&T, &mut crate::heap_size::HeapSizer) -> usize,
+ ) -> usize {
+ self.column.heap_size(sizer, row_heap)
+ }
+
+ /// Every row, in order.
+ pub(crate) fn iter(&self) -> impl Iterator<Item = &T> {
+ (0..self.len).filter_map(|index| self.column.get(index))
+ }
+
+ #[inline]
+ pub(crate) fn get(&self, index: usize) -> Option<&T> {
+ if index >= self.len {
+ return None;
+ }
+ self.column.get(index)
+ }
+
+ /// The row at `index`, for writing, copying its chunk where a fork shares it.
+ #[inline]
+ pub(crate) fn get_mut(&mut self, index: usize) -> Option<&mut T> {
+ if index >= self.len {
+ return None;
+ }
+ self.column.owned_row(index)
+ }
+
+ pub(crate) fn push(&mut self, value: T) {
+ let index = self.len;
+ self.resize_with_default(index + 1);
+ self[index] = value;
+ }
+
+ /// Grows the vector to `len` rows, the new ones default, or truncates it to them.
+ pub(crate) fn resize_with_default(&mut self, len: usize) {
+ if len < self.len {
+ for index in len..self.len {
+ if self.column.get(index).is_some() {
+ *self.column.owned_row(index).expect("the row is in the column") = T::default();
+ }
+ }
+ }
+ self.column.grow_to(len);
+ self.len = len;
+ }
+}
+
+impl<T: Clone + Default, const CHUNK: usize> std::ops::Index<usize> for CowVec<T, CHUNK> {
+ type Output = T;
+
+ #[inline]
+ fn index(&self, index: usize) -> &T {
+ self.get(index).expect("index within the vector")
+ }
+}
+
+impl<T: Clone + Default, const CHUNK: usize> std::ops::IndexMut<usize> for CowVec<T, CHUNK> {
+ #[inline]
+ fn index_mut(&mut self, index: usize) -> &mut T {
+ self.get_mut(index).expect("index within the vector")
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -414,6 +619,21 @@ mod tests {
assert_eq!(rows(&column.publish(), 7), [1, 20, 3, 4, 5, 60, 7]);
}
+ #[test]
+ fn a_snapshot_names_the_rows_of_the_chunks_written_since_an_older_one() {
+ let mut column = column_of(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
+ let first = column.publish();
+ assert!(column.publish().changed_rows_since(&first).is_empty());
+ set(&mut column, 5, 60);
+ set(&mut column, 9, 90);
+ column.grow_to(13);
+ let second = column.publish();
+ assert_eq!(second.changed_rows_since(&first), [4..16]);
+ set(&mut column, 1, 20);
+ assert_eq!(column.publish().changed_rows_since(&second), [0..4]);
+ assert_eq!(first.changed_rows_since(&ColumnSnapshot::default()), [0..12]);
+ }
+
#[test]
fn a_write_copies_only_the_chunk_a_snapshot_shares_and_only_once() {
let mut column = column_of(&[1, 2, 3, 4, 5, 6, 7, 8]);
diff --git a/Libraries/LibWeb/Rust/src/css/absolutize.rs b/Libraries/LibWeb/Rust/src/css/absolutize.rs
index 93cfbaa5dca..5123028b468 100644
--- a/Libraries/LibWeb/Rust/src/css/absolutize.rs
+++ b/Libraries/LibWeb/Rust/src/css/absolutize.rs
@@ -15,10 +15,17 @@
//! allocations based on pointer equality.
// Style value data allocations are thread-confined, like style_value.rs.
-#![allow(clippy::arc_with_non_send_sync)]
+use crate::css::style_value::{
+ BackgroundSizePayload, BorderImageSlicePayload, BorderRadiusPayload, BorderRadiusRectPayload, ColorFunctionPayload,
+ ColorMixPayload, ConicGradientPayload, ContentPayload, CounterDefinitionsPayload, CounterStyleSystemPayload,
+ CursorPayload, EasingPayload, FunctionPayload, GridTrackPlacementPayload, GridTrackSizeListPayload, ImagePayload,
+ ImageSetPayload, LightDarkPayload, LinearGradientPayload, OpenTypeTaggedPayload, PositionPayload,
+ RadialGradientPayload, RadialSizePayload, RandomValueSharingPayload, RatioPayload, RayPayload, RectPayload,
+ ScrollbarColorPayload, ShadowPayload, StyleValueBox, TransformationPayload, UrlPayload,
+};
+use crate::css::style_value_arc::StyleValueArc;
use std::cell::Cell;
-use std::sync::Arc;
#[cfg(test)]
mod grid_tests {
@@ -30,7 +37,7 @@ mod grid_tests {
/// Absolutizes against a zeroed length context, handing back the value itself when it is
/// unchanged.
- fn absolutize_for_test(value: &StyleValueData) -> Arc<StyleValueData> {
+ fn absolutize_for_test(value: &StyleValueData) -> StyleValueArc {
// All fields are scalars or nullable pointers.
let length = FfiLengthResolutionContext::default();
let context = AbsolutizationContext {
@@ -45,14 +52,14 @@ mod grid_tests {
};
match absolutize(value, &context).unwrap() {
Absolutized::Unchanged => unsafe {
- Arc::increment_strong_count(value);
- Arc::from_raw(value)
+ StyleValueArc::increment_strong_count(value);
+ StyleValueArc::from_raw(value)
},
Absolutized::Changed(value) => value.into_arc(),
}
}
- fn parse(property: u16, source: &str) -> Arc<StyleValueData> {
+ fn parse(property: u16, source: &str) -> StyleValueArc {
let units: Vec<_> = source.encode_utf16().collect();
let values = consume_a_list_of_component_values(tokenize_for_parser(TokenizerInput::Utf16(&units))).unwrap();
// All fields are scalars or nullable pointers.
@@ -130,9 +137,10 @@ mod grid_tests {
unreachable!();
};
let resolved = absolutize_for_test(values.as_slice()[0].data());
- let StyleValueData::Easing { linear_stops, .. } = &*resolved else {
+ let StyleValueData::Easing(easing_payload) = &*resolved else {
unreachable!();
};
+ let EasingPayload { linear_stops, .. } = &**easing_payload;
let inputs = linear_stops
.as_slice()
.iter()
@@ -158,7 +166,7 @@ mod grid_tests {
let value = parse(property, source);
let original = crate::css::serialize::serialize_style_value_to_utf16(&value);
let same = absolutize_for_test(&value);
- assert!(Arc::ptr_eq(&value, &same));
+ assert!(StyleValueArc::ptr_eq(&value, &same));
let mut retained = Vec::new();
let mapped = map_grid_values(&value, &mut |child| {
if child.optional_data().is_some() {
@@ -184,7 +192,7 @@ mod grid_tests {
property_id::GRID_TEMPLATE_COLUMNS,
"[雪] repeat(2, minmax(10px, 1fr)) [雨]",
);
- let resolved = Arc::new(
+ let resolved = StyleValueArc::new(
map_grid_values(&value, &mut |child| {
Some(match child.optional_data() {
Some(StyleValueData::Length { value, unit }) => retain_new(StyleValueData::Length {
@@ -196,7 +204,7 @@ mod grid_tests {
})
.unwrap(),
);
- assert!(!Arc::ptr_eq(&value, &resolved));
+ assert!(!StyleValueArc::ptr_eq(&value, &resolved));
for (value, expected) in [
(&value, "[雪] repeat(2, minmax(10px, 1fr)) [雨]"),
(&resolved, "[雪] repeat(2, minmax(20px, 1fr)) [雨]"),
@@ -258,7 +266,7 @@ pub(crate) enum Absolutized {
}
fn retain_new(value: StyleValueData) -> RetainedStyleValueData {
- RetainedStyleValueData::from_arc(Arc::new(value))
+ RetainedStyleValueData::from_arc(StyleValueArc::new(value))
}
/// Absolutizes one retained child slot. Returns the child for the rebuilt parent, whether any
@@ -292,6 +300,34 @@ fn absolutize_list(
.collect()
}
+/// The absolutized children of a list, or none where every child is unchanged, allocating only once
+/// one changes.
+fn absolutize_list_if_changed(
+ values: &RetainedStyleValueDataList,
+ context: &AbsolutizationContext,
+) -> Option<Option<Vec<RetainedStyleValueData>>> {
+ let values = values.as_slice();
+ let mut changed: Option<Vec<RetainedStyleValueData>> = None;
+ for (index, child) in values.iter().enumerate() {
+ let absolutized = match child.optional_data() {
+ Some(data) => absolutize(data, context)?,
+ None => Absolutized::Unchanged,
+ };
+ match (absolutized, &mut changed) {
+ (Absolutized::Unchanged, None) => {}
+ (Absolutized::Unchanged, Some(changed)) => changed.push(child.clone_retained()),
+ (Absolutized::Changed(new_child), Some(changed)) => changed.push(new_child),
+ (Absolutized::Changed(new_child), None) => {
+ let mut list = Vec::with_capacity(values.len());
+ list.extend(values[..index].iter().map(RetainedStyleValueData::clone_retained));
+ list.push(new_child);
+ changed = Some(list);
+ }
+ }
+ }
+ Some(changed)
+}
+
fn zero_px_length() -> StyleValueData {
StyleValueData::Length {
value: 0.0,
@@ -312,15 +348,15 @@ fn retained_null() -> RetainedStyleValueData {
}
fn absolutize_image(value: &StyleValueData, context: &AbsolutizationContext) -> Option<Absolutized> {
- let StyleValueData::Image {
+ let StyleValueData::Image(image_payload) = value else {
+ return None;
+ };
+ let ImagePayload {
url,
url_type,
url_modifiers,
resource_context,
- } = value
- else {
- return None;
- };
+ } = &**image_payload;
// https://drafts.csswg.org/css-values-4/#local-urls
// When serializing a url() with the local url flag set, it must serialize as just the fragment.
if url.is_empty() || url.is_fragment() {
@@ -371,18 +407,20 @@ fn absolutize_image(value: &StyleValueData, context: &AbsolutizationContext) ->
resource_context.parent_style_sheet_origin_clean,
));
- Some(Absolutized::Changed(retain_new(StyleValueData::Image {
- url: absolutized_url,
- url_type: *url_type,
- url_modifiers: url_modifiers.clone(),
- resource_context: crate::css::style_value::ImageResourceContext {
- base_url,
- has_base_url: true,
- has_parent_style_sheet_origin_clean,
- parent_style_sheet_origin_clean,
- should_absolutize_url_for_computed_value,
- },
- })))
+ Some(Absolutized::Changed(retain_new(StyleValueData::Image(
+ StyleValueBox::new(ImagePayload {
+ url: absolutized_url,
+ url_type: *url_type,
+ url_modifiers: url_modifiers.clone(),
+ resource_context: crate::css::style_value::ImageResourceContext {
+ base_url,
+ has_base_url: true,
+ has_parent_style_sheet_origin_clean,
+ parent_style_sheet_origin_clean,
+ should_absolutize_url_for_computed_value,
+ },
+ }),
+ ))))
}
/// The color-resolution input the C++ absolutizers build from a computation context: the
@@ -405,7 +443,7 @@ fn color_resolution_input<'a>(context: &'a AbsolutizationContext) -> ColorResolu
/// The rgb() function form ColorFunctionStyleValue::create builds for an already-resolved
/// color: number channels, a number alpha, no name and no origin.
fn rgb_color_function(r: f64, g: f64, b: f64, alpha: f64, color_syntax: u8) -> StyleValueData {
- StyleValueData::ColorFunction {
+ StyleValueData::ColorFunction(StyleValueBox::new(ColorFunctionPayload {
color_base: ColorBase {
has_color_type: true,
color_type: crate::css::color_conversion::RGB,
@@ -418,7 +456,7 @@ fn rgb_color_function(r: f64, g: f64, b: f64, alpha: f64, color_syntax: u8) -> S
has_name: false,
name: CssString::none(),
origin_color: retained_null(),
- }
+ }))
}
/// The canonical computed form of a fully-resolved legacy sRGB color.
@@ -489,7 +527,7 @@ fn hwb_to_absolutized_rgb(
let gray = retain_new(StyleValueData::Number {
value: f64::from((whiteness / (whiteness + blackness) * 255.0).clamp(0.0, 255.0)),
});
- return StyleValueData::ColorFunction {
+ return StyleValueData::ColorFunction(StyleValueBox::new(ColorFunctionPayload {
color_base: ColorBase {
has_color_type: true,
color_type: crate::css::color_conversion::RGB,
@@ -504,7 +542,7 @@ fn hwb_to_absolutized_rgb(
has_name: false,
name: CssString::none(),
origin_color: retained_null(),
- };
+ }));
}
let mut hue = (hue_degrees as f32) % 360.0;
@@ -535,17 +573,17 @@ fn hwb_to_absolutized_rgb(
/// function with every present component resolved to a number (hues in degrees, other hsl() and hwb()
/// components in percent, rgb() components from 0 to 255) and alpha clamped to [0, 1].
fn resolved_srgb_function_components(value: &StyleValueData) -> Option<StyleValueData> {
- let StyleValueData::ColorFunction {
+ let StyleValueData::ColorFunction(color_function_payload) = value else {
+ return None;
+ };
+ let ColorFunctionPayload {
color_base,
channel_0,
channel_1,
channel_2,
alpha,
..
- } = value
- else {
- return None;
- };
+ } = &**color_function_payload;
let descriptor = descriptor_for_color_type(color_base.color_type);
let resolve_channel = |channel: &RetainedStyleValueData, index: usize| -> Option<RetainedStyleValueData> {
let value = channel.data();
@@ -576,30 +614,32 @@ fn resolved_srgb_function_components(value: &StyleValueData) -> Option<StyleValu
value: resolve_alpha(value, &EMPTY_INPUT)?,
}),
};
- Some(StyleValueData::ColorFunction {
- color_base: ColorBase {
- color_syntax: COLOR_SYNTAX_MODERN,
- ..*color_base
+ Some(StyleValueData::ColorFunction(StyleValueBox::new(
+ ColorFunctionPayload {
+ color_base: ColorBase {
+ color_syntax: COLOR_SYNTAX_MODERN,
+ ..*color_base
+ },
+ channel_0: resolve_channel(channel_0, 0)?,
+ channel_1: resolve_channel(channel_1, 1)?,
+ channel_2: resolve_channel(channel_2, 2)?,
+ alpha,
+ has_name: false,
+ name: CssString::none(),
+ origin_color: retained_null(),
},
- channel_0: resolve_channel(channel_0, 0)?,
- channel_1: resolve_channel(channel_1, 1)?,
- channel_2: resolve_channel(channel_2, 2)?,
- alpha,
- has_name: false,
- name: CssString::none(),
- origin_color: retained_null(),
- })
+ )))
}
/// Whether a value is an rgb(), hsl() or hwb() function that is not a relative color.
fn is_absolute_srgb_function(value: &StyleValueData) -> bool {
- matches!(value, StyleValueData::ColorFunction { color_base, origin_color, .. }
- if color_base.has_color_type
+ matches!(value, StyleValueData::ColorFunction(color_function)
+ if color_function.color_base.has_color_type
&& matches!(
- color_base.color_type,
+ color_function.color_base.color_type,
crate::css::color_conversion::RGB | crate::css::color_conversion::HSL | crate::css::color_conversion::HWB
)
- && origin_color.optional_data().is_none())
+ && color_function.origin_color.optional_data().is_none())
}
/// Absolutizes an absolute rgb(), hsl() or hwb() function into the same function with resolved components.
@@ -607,35 +647,40 @@ fn absolutize_srgb_function_keeping_form(
value: &StyleValueData,
context: &AbsolutizationContext,
) -> Option<StyleValueData> {
- let StyleValueData::ColorFunction {
+ let StyleValueData::ColorFunction(color_function_payload) = value else {
+ return None;
+ };
+ let ColorFunctionPayload {
color_base,
channel_0,
channel_1,
channel_2,
alpha,
..
- } = value
- else {
- return None;
- };
+ } = &**color_function_payload;
let mut changed = false;
- resolved_srgb_function_components(&StyleValueData::ColorFunction {
- color_base: *color_base,
- channel_0: absolutize_child(channel_0, context, &mut changed)?,
- channel_1: absolutize_child(channel_1, context, &mut changed)?,
- channel_2: absolutize_child(channel_2, context, &mut changed)?,
- alpha: absolutize_child(alpha, context, &mut changed)?,
- has_name: false,
- name: CssString::none(),
- origin_color: retained_null(),
- })
+ resolved_srgb_function_components(&StyleValueData::ColorFunction(StyleValueBox::new(
+ ColorFunctionPayload {
+ color_base: *color_base,
+ channel_0: absolutize_child(channel_0, context, &mut changed)?,
+ channel_1: absolutize_child(channel_1, context, &mut changed)?,
+ channel_2: absolutize_child(channel_2, context, &mut changed)?,
+ alpha: absolutize_child(alpha, context, &mut changed)?,
+ has_name: false,
+ name: CssString::none(),
+ origin_color: retained_null(),
+ },
+ )))
}
/// Port of ColorFunctionStyleValue::absolutized: relative forms recurse their channels, alpha
/// and origin; HSL and HWB resolve and convert to a legacy rgb() form; every other color
/// function recurses its channels and alpha.
fn absolutize_color_function(value: &StyleValueData, context: &AbsolutizationContext) -> Option<Absolutized> {
- let StyleValueData::ColorFunction {
+ let StyleValueData::ColorFunction(color_function_payload) = value else {
+ return None;
+ };
+ let ColorFunctionPayload {
color_base,
channel_0,
channel_1,
@@ -644,10 +689,7 @@ fn absolutize_color_function(value: &StyleValueData, context: &AbsolutizationCon
has_name,
name,
origin_color,
- } = value
- else {
- return None;
- };
+ } = &**color_function_payload;
// The C++ absolutization reads the descriptor through the unconditional color type.
if !color_base.has_color_type {
return None;
@@ -668,7 +710,7 @@ fn absolutize_color_function(value: &StyleValueData, context: &AbsolutizationCon
} else {
absolutize_child(origin_color, context, &mut changed)?
};
- let rebuilt = StyleValueData::ColorFunction {
+ let rebuilt = StyleValueData::ColorFunction(StyleValueBox::new(ColorFunctionPayload {
color_base: *color_base,
channel_0: absolutized_c1,
channel_1: absolutized_c2,
@@ -677,7 +719,7 @@ fn absolutize_color_function(value: &StyleValueData, context: &AbsolutizationCon
has_name: *has_name,
name: name.clone(),
origin_color: absolutized_origin,
- };
+ }));
// NB: Other properties keep currentcolor unresolved until the element's own color is available.
if !(context.current_color.is_none() && value_depends_on_current_color(&rebuilt))
&& let Some(resolved) = resolve_relative_form(&rebuilt, &color_resolution_input(context))
@@ -694,7 +736,7 @@ fn absolutize_color_function(value: &StyleValueData, context: &AbsolutizationCon
}
let descriptor = descriptor_for_color_type(color_base.color_type);
- let rebuilt = StyleValueData::ColorFunction {
+ let rebuilt = StyleValueData::ColorFunction(StyleValueBox::new(ColorFunctionPayload {
color_base: *color_base,
channel_0: absolutized_c1,
channel_1: absolutized_c2,
@@ -703,7 +745,7 @@ fn absolutize_color_function(value: &StyleValueData, context: &AbsolutizationCon
has_name: *has_name,
name: name.clone(),
origin_color: retained_null(),
- };
+ }));
// https://drafts.csswg.org/css-color-4/#css-serialization-of-srgb
// An sRGB value with missing components keeps its color function, so that those components serialize as
@@ -717,16 +759,16 @@ fn absolutize_color_function(value: &StyleValueData, context: &AbsolutizationCon
&rebuilt,
)?)));
}
- let StyleValueData::ColorFunction {
+ let StyleValueData::ColorFunction(color_function_payload) = &rebuilt else {
+ unreachable!();
+ };
+ let ColorFunctionPayload {
channel_0: absolutized_c1,
channel_1: absolutized_c2,
channel_2: absolutized_c3,
alpha: absolutized_alpha,
..
- } = &rebuilt
- else {
- unreachable!();
- };
+ } = &**color_function_payload;
if descriptor.absolutizes_to_rgb {
// https://drafts.csswg.org/css-color-4/#resolving-sRGB-values
@@ -781,15 +823,15 @@ fn absolutize_color_function(value: &StyleValueData, context: &AbsolutizationCon
/// When mixing cannot complete, rebuild the color mix around its absolutized parts.
// https://drafts.csswg.org/css-color-5/#color-mix-result
fn absolutize_color_mix(value: &StyleValueData, context: &AbsolutizationContext) -> Option<Absolutized> {
- let StyleValueData::ColorMix {
+ let StyleValueData::ColorMix(color_mix_payload) = value else {
+ return None;
+ };
+ let ColorMixPayload {
color_interpolation_method,
colors,
percentages,
..
- } = value
- else {
- return None;
- };
+ } = &**color_mix_payload;
let mut percentages_changed = false;
let absolutized_percentages = absolutize_list(percentages, context, &mut percentages_changed)?;
@@ -820,8 +862,8 @@ fn absolutize_color_mix(value: &StyleValueData, context: &AbsolutizationContext)
.as_slice()
.iter()
.map(|color| {
- if let StyleValueData::ColorFunction { origin_color, .. } = color.data()
- && origin_color.optional_data().is_some()
+ if let StyleValueData::ColorFunction(color_function_payload) = color.data()
+ && color_function_payload.origin_color.optional_data().is_some()
{
return resolve_relative_form(color.data(), &input);
}
@@ -866,24 +908,26 @@ fn absolutize_color_mix(value: &StyleValueData, context: &AbsolutizationContext)
if !colors_changed && percentages_match {
return Some(Absolutized::Unchanged);
}
- Some(Absolutized::Changed(retain_new(StyleValueData::ColorMix {
- color_base: ColorBase {
- has_color_type: false,
- color_type: 0,
- color_syntax: COLOR_SYNTAX_MODERN,
- },
- color_interpolation_method: absolutized_method,
- colors: RetainedStyleValueDataList::from_retained_values(absolutized_colors),
- percentages: RetainedStyleValueDataList::from_retained_values(
- specified_percentages
- .into_iter()
- .map(|percentage| match percentage {
- Some(value) => retain_new(StyleValueData::Percentage { value }),
- None => retained_null(),
- })
- .collect(),
- ),
- })))
+ Some(Absolutized::Changed(retain_new(StyleValueData::ColorMix(
+ StyleValueBox::new(ColorMixPayload {
+ color_base: ColorBase {
+ has_color_type: false,
+ color_type: 0,
+ color_syntax: COLOR_SYNTAX_MODERN,
+ },
+ color_interpolation_method: absolutized_method,
+ colors: RetainedStyleValueDataList::from_retained_values(absolutized_colors),
+ percentages: RetainedStyleValueDataList::from_retained_values(
+ specified_percentages
+ .into_iter()
+ .map(|percentage| match percentage {
+ Some(value) => retain_new(StyleValueData::Percentage { value }),
+ None => retained_null(),
+ })
+ .collect(),
+ ),
+ }),
+ ))))
}
/// The gradient absolutizers recurse their Rust-owned children and rebuild the retained stop
@@ -912,82 +956,91 @@ fn absolutize_gradient(value: &StyleValueData, context: &AbsolutizationContext)
))
};
match value {
- StyleValueData::LinearGradient {
- has_direction_value,
- direction_value,
- side_or_corner,
- color_stop_list,
- gradient_type,
- repeating,
- color_interpolation_method,
- color_syntax,
- } => {
+ StyleValueData::LinearGradient(linear_gradient_payload) => {
+ let LinearGradientPayload {
+ has_direction_value,
+ direction_value,
+ side_or_corner,
+ color_stop_list,
+ gradient_type,
+ repeating,
+ color_interpolation_method,
+ color_syntax,
+ } = &**linear_gradient_payload;
let direction_value = absolutize_child(direction_value, context, &mut changed)?;
let color_stop_list = absolutize_stops(color_stop_list, &mut changed)?;
let color_interpolation_method = absolutize_child(color_interpolation_method, context, &mut changed)?;
if changed {
- Some(Absolutized::Changed(retain_new(StyleValueData::LinearGradient {
- has_direction_value: *has_direction_value,
- direction_value,
- side_or_corner: *side_or_corner,
- color_stop_list,
- gradient_type: *gradient_type,
- repeating: *repeating,
- color_interpolation_method,
- color_syntax: *color_syntax,
- })))
+ Some(Absolutized::Changed(retain_new(StyleValueData::LinearGradient(
+ StyleValueBox::new(LinearGradientPayload {
+ has_direction_value: *has_direction_value,
+ direction_value,
+ side_or_corner: *side_or_corner,
+ color_stop_list,
+ gradient_type: *gradient_type,
+ repeating: *repeating,
+ color_interpolation_method,
+ color_syntax: *color_syntax,
+ }),
+ ))))
} else {
Some(Absolutized::Unchanged)
}
}
- StyleValueData::RadialGradient {
- ending_shape,
- size,
- position,
- color_stop_list,
- repeating,
- color_interpolation_method,
- color_syntax,
- } => {
+ StyleValueData::RadialGradient(radial_gradient_payload) => {
+ let RadialGradientPayload {
+ ending_shape,
+ size,
+ position,
+ color_stop_list,
+ repeating,
+ color_interpolation_method,
+ color_syntax,
+ } = &**radial_gradient_payload;
let size = absolutize_child(size, context, &mut changed)?;
let position = absolutize_child(position, context, &mut changed)?;
let color_stop_list = absolutize_stops(color_stop_list, &mut changed)?;
let color_interpolation_method = absolutize_child(color_interpolation_method, context, &mut changed)?;
if changed {
- Some(Absolutized::Changed(retain_new(StyleValueData::RadialGradient {
- ending_shape: *ending_shape,
- size,
- position,
- color_stop_list,
- repeating: *repeating,
- color_interpolation_method,
- color_syntax: *color_syntax,
- })))
+ Some(Absolutized::Changed(retain_new(StyleValueData::RadialGradient(
+ StyleValueBox::new(RadialGradientPayload {
+ ending_shape: *ending_shape,
+ size,
+ position,
+ color_stop_list,
+ repeating: *repeating,
+ color_interpolation_method,
+ color_syntax: *color_syntax,
+ }),
+ ))))
} else {
Some(Absolutized::Unchanged)
}
}
- StyleValueData::ConicGradient {
- from_angle,
- position,
- color_stop_list,
- repeating,
- color_interpolation_method,
- color_syntax,
- } => {
+ StyleValueData::ConicGradient(conic_gradient_payload) => {
+ let ConicGradientPayload {
+ from_angle,
+ position,
+ color_stop_list,
+ repeating,
+ color_interpolation_method,
+ color_syntax,
+ } = &**conic_gradient_payload;
let from_angle = absolutize_child(from_angle, context, &mut changed)?;
let position = absolutize_child(position, context, &mut changed)?;
let color_stop_list = absolutize_stops(color_stop_list, &mut changed)?;
let color_interpolation_method = absolutize_child(color_interpolation_method, context, &mut changed)?;
if changed {
- Some(Absolutized::Changed(retain_new(StyleValueData::ConicGradient {
- from_angle,
- position,
- color_stop_list,
- repeating: *repeating,
- color_interpolation_method,
- color_syntax: *color_syntax,
- })))
+ Some(Absolutized::Changed(retain_new(StyleValueData::ConicGradient(
+ StyleValueBox::new(ConicGradientPayload {
+ from_angle,
+ position,
+ color_stop_list,
+ repeating: *repeating,
+ color_interpolation_method,
+ color_syntax: *color_syntax,
+ }),
+ ))))
} else {
Some(Absolutized::Unchanged)
}
@@ -1362,7 +1415,10 @@ fn absolutize_easing(
value: &StyleValueData,
resolve: &mut impl FnMut(&RetainedStyleValueData, &mut bool) -> Option<RetainedStyleValueData>,
) -> Option<Absolutized> {
- let StyleValueData::Easing {
+ let StyleValueData::Easing(easing_payload) = value else {
+ return None;
+ };
+ let EasingPayload {
kind,
linear_stops,
x1,
@@ -1372,10 +1428,7 @@ fn absolutize_easing(
number_of_intervals,
step_position,
is_keyword,
- } = value
- else {
- return None;
- };
+ } = &**easing_payload;
let mut changed = *is_keyword;
let mut stops = Vec::with_capacity(linear_stops.as_slice().len());
for stop in linear_stops.as_slice() {
@@ -1399,17 +1452,19 @@ fn absolutize_easing(
if !changed {
return Some(Absolutized::Unchanged);
}
- Some(Absolutized::Changed(retain_new(StyleValueData::Easing {
- kind: *kind,
- linear_stops: crate::css::style_value::RetainedLinearEasingStopList::from_retained_elements(stops),
- x1,
- y1,
- x2,
- y2,
- number_of_intervals,
- step_position: *step_position,
- is_keyword: false,
- })))
+ Some(Absolutized::Changed(retain_new(StyleValueData::Easing(
+ StyleValueBox::new(EasingPayload {
+ kind: *kind,
+ linear_stops: crate::css::style_value::RetainedLinearEasingStopList::from_retained_elements(stops),
+ x1,
+ y1,
+ x2,
+ y2,
+ number_of_intervals,
+ step_position: *step_position,
+ is_keyword: false,
+ }),
+ ))))
}
/// Absolutizes a grid track entry list, recursing through repeat() entries.
@@ -1445,33 +1500,39 @@ fn map_grid_values(
map: &mut impl FnMut(&RetainedStyleValueData) -> Option<RetainedStyleValueData>,
) -> Option<StyleValueData> {
Some(match value {
- StyleValueData::GridTrackPlacement {
- kind,
- value,
- has_name,
- name,
- implicit_start_name,
- implicit_end_name,
- } => StyleValueData::GridTrackPlacement {
- kind: *kind,
- value: map(value)?,
- has_name: *has_name,
- name: name.clone(),
- implicit_start_name: implicit_start_name.clone(),
- implicit_end_name: implicit_end_name.clone(),
- },
- StyleValueData::GridTrackSizeList {
- is_subgrid,
- preserve_line_name_sets,
- entries,
- } => StyleValueData::GridTrackSizeList {
- is_subgrid: *is_subgrid,
- preserve_line_name_sets: *preserve_line_name_sets,
- entries: RetainedGridTrackEntryList::from_retained_entries(map_grid_track_entries(
- entries.as_slice(),
- map,
- )?),
- },
+ StyleValueData::GridTrackPlacement(grid_track_placement_payload) => {
+ let GridTrackPlacementPayload {
+ kind,
+ value,
+ has_name,
+ name,
+ implicit_start_name,
+ implicit_end_name,
+ } = &**grid_track_placement_payload;
+ StyleValueData::GridTrackPlacement(StyleValueBox::new(GridTrackPlacementPayload {
+ kind: *kind,
+ value: map(value)?,
+ has_name: *has_name,
+ name: name.clone(),
+ implicit_start_name: implicit_start_name.clone(),
+ implicit_end_name: implicit_end_name.clone(),
+ }))
+ }
+ StyleValueData::GridTrackSizeList(grid_track_size_list_payload) => {
+ let GridTrackSizeListPayload {
+ is_subgrid,
+ preserve_line_name_sets,
+ entries,
+ } = &**grid_track_size_list_payload;
+ StyleValueData::GridTrackSizeList(StyleValueBox::new(GridTrackSizeListPayload {
+ is_subgrid: *is_subgrid,
+ preserve_line_name_sets: *preserve_line_name_sets,
+ entries: RetainedGridTrackEntryList::from_retained_entries(map_grid_track_entries(
+ entries.as_slice(),
+ map,
+ )?),
+ }))
+ }
_ => unreachable!(),
})
}
@@ -1585,84 +1646,87 @@ pub(crate) fn absolutize(value: &StyleValueData, context: &AbsolutizationContext
}
// Structural values: recurse and rebuild only on change.
- StyleValueData::Ratio { numerator, denominator } => {
+ StyleValueData::Ratio(ratio_payload) => {
+ let RatioPayload { numerator, denominator } = &**ratio_payload;
let mut changed = false;
let numerator = absolutize_child(numerator, context, &mut changed)?;
let denominator = absolutize_child(denominator, context, &mut changed)?;
- rebuild!(changed, StyleValueData::Ratio { numerator, denominator })
+ rebuild!(
+ changed,
+ StyleValueData::Ratio(StyleValueBox::new(RatioPayload { numerator, denominator }))
+ )
}
StyleValueData::Superellipse { parameter } => {
let mut changed = false;
let parameter = absolutize_child(parameter, context, &mut changed)?;
rebuild!(changed, StyleValueData::Superellipse { parameter })
}
- StyleValueData::OpenTypeTagged {
- mode,
- tag_name: tag,
- packed_tag,
- value,
- } => {
+ StyleValueData::OpenTypeTagged(open_type_tagged_payload) => {
+ let OpenTypeTaggedPayload {
+ mode,
+ tag_name: tag,
+ packed_tag,
+ value,
+ } = &**open_type_tagged_payload;
let mut changed = false;
let value = absolutize_child(value, context, &mut changed)?;
rebuild!(
changed,
- StyleValueData::OpenTypeTagged {
+ StyleValueData::OpenTypeTagged(StyleValueBox::new(OpenTypeTaggedPayload {
mode: *mode,
tag_name: tag.clone(),
packed_tag: *packed_tag,
value,
- }
+ }))
)
}
- StyleValueData::Function { name, value } => {
+ StyleValueData::Function(function_payload) => {
+ let FunctionPayload { name, value } = &**function_payload;
let mut changed = false;
let value = absolutize_child(value, context, &mut changed)?;
rebuild!(
changed,
- StyleValueData::Function {
+ StyleValueData::Function(StyleValueBox::new(FunctionPayload {
name: name.clone(),
value,
- }
- )
- }
- StyleValueData::Tuple { values } => {
- let mut changed = false;
- let values = absolutize_list(values, context, &mut changed)?;
- rebuild!(
- changed,
- StyleValueData::Tuple {
- values: RetainedStyleValueDataList::from_retained_values(values),
- }
+ }))
)
}
+ StyleValueData::Tuple { values } => Some(match absolutize_list_if_changed(values, context)? {
+ None => Absolutized::Unchanged,
+ Some(values) => Absolutized::Changed(retain_new(StyleValueData::Tuple {
+ values: RetainedStyleValueDataList::from_retained_values(values),
+ })),
+ }),
StyleValueData::ValueList {
values,
separator,
collapsible,
- } => {
+ } => Some(match absolutize_list_if_changed(values, context)? {
+ None => Absolutized::Unchanged,
+ Some(values) => Absolutized::Changed(retain_new(StyleValueData::ValueList {
+ values: RetainedStyleValueDataList::from_retained_values(values),
+ separator: *separator,
+ collapsible: *collapsible,
+ })),
+ }),
+ StyleValueData::Content(content_payload) => {
+ let ContentPayload { content, alt_text } = &**content_payload;
let mut changed = false;
- let values = absolutize_list(values, context, &mut changed)?;
+ let content = absolutize_child(content, context, &mut changed)?;
+ let alt_text = absolutize_child(alt_text, context, &mut changed)?;
rebuild!(
changed,
- StyleValueData::ValueList {
- values: RetainedStyleValueDataList::from_retained_values(values),
- separator: *separator,
- collapsible: *collapsible,
- }
+ StyleValueData::Content(StyleValueBox::new(ContentPayload { content, alt_text }))
)
}
- StyleValueData::Content { content, alt_text } => {
- let mut changed = false;
- let content = absolutize_child(content, context, &mut changed)?;
- let alt_text = absolutize_child(alt_text, context, &mut changed)?;
- rebuild!(changed, StyleValueData::Content { content, alt_text })
- }
- StyleValueData::Rect {
- top,
- right,
- bottom,
- left,
- } => {
+ StyleValueData::Rect(rect_payload) => {
+ let RectPayload {
+ top,
+ right,
+ bottom,
+ left,
+ } = &**rect_payload;
let mut changed = false;
let top = absolutize_child(top, context, &mut changed)?;
let right = absolutize_child(right, context, &mut changed)?;
@@ -1670,21 +1734,22 @@ pub(crate) fn absolutize(value: &StyleValueData, context: &AbsolutizationContext
let left = absolutize_child(left, context, &mut changed)?;
rebuild!(
changed,
- StyleValueData::Rect {
+ StyleValueData::Rect(StyleValueBox::new(RectPayload {
top,
right,
bottom,
left
- }
+ }))
)
}
- StyleValueData::BorderImageSlice {
- top,
- right,
- bottom,
- left,
- fill,
- } => {
+ StyleValueData::BorderImageSlice(border_image_slice_payload) => {
+ let BorderImageSlicePayload {
+ top,
+ right,
+ bottom,
+ left,
+ fill,
+ } = &**border_image_slice_payload;
let mut changed = false;
let top = absolutize_child(top, context, &mut changed)?;
let right = absolutize_child(right, context, &mut changed)?;
@@ -1692,38 +1757,40 @@ pub(crate) fn absolutize(value: &StyleValueData, context: &AbsolutizationContext
let left = absolutize_child(left, context, &mut changed)?;
rebuild!(
changed,
- StyleValueData::BorderImageSlice {
+ StyleValueData::BorderImageSlice(StyleValueBox::new(BorderImageSlicePayload {
top,
right,
bottom,
left,
fill: *fill,
- }
+ }))
)
}
- StyleValueData::BorderRadius {
- is_elliptical,
- horizontal_radius,
- vertical_radius,
- } => {
+ StyleValueData::BorderRadius(border_radius_payload) => {
+ let BorderRadiusPayload {
+ is_elliptical,
+ horizontal_radius,
+ vertical_radius,
+ } = &**border_radius_payload;
let mut changed = false;
let horizontal_radius = absolutize_child(horizontal_radius, context, &mut changed)?;
let vertical_radius = absolutize_child(vertical_radius, context, &mut changed)?;
rebuild!(
changed,
- StyleValueData::BorderRadius {
+ StyleValueData::BorderRadius(StyleValueBox::new(BorderRadiusPayload {
is_elliptical: *is_elliptical,
horizontal_radius,
vertical_radius,
- }
+ }))
)
}
- StyleValueData::BorderRadiusRect {
- top_left,
- top_right,
- bottom_right,
- bottom_left,
- } => {
+ StyleValueData::BorderRadiusRect(border_radius_rect_payload) => {
+ let BorderRadiusRectPayload {
+ top_left,
+ top_right,
+ bottom_right,
+ bottom_left,
+ } = &**border_radius_rect_payload;
let mut changed = false;
let top_left = absolutize_child(top_left, context, &mut changed)?;
let top_right = absolutize_child(top_right, context, &mut changed)?;
@@ -1731,44 +1798,50 @@ pub(crate) fn absolutize(value: &StyleValueData, context: &AbsolutizationContext
let bottom_left = absolutize_child(bottom_left, context, &mut changed)?;
rebuild!(
changed,
- StyleValueData::BorderRadiusRect {
+ StyleValueData::BorderRadiusRect(StyleValueBox::new(BorderRadiusRectPayload {
top_left,
top_right,
bottom_right,
bottom_left,
- }
+ }))
)
}
- StyleValueData::BackgroundSize { size_x, size_y } => {
+ StyleValueData::BackgroundSize(background_size_payload) => {
+ let BackgroundSizePayload { size_x, size_y } = &**background_size_payload;
let mut changed = false;
let size_x = absolutize_child(size_x, context, &mut changed)?;
let size_y = absolutize_child(size_y, context, &mut changed)?;
- rebuild!(changed, StyleValueData::BackgroundSize { size_x, size_y })
+ rebuild!(
+ changed,
+ StyleValueData::BackgroundSize(StyleValueBox::new(BackgroundSizePayload { size_x, size_y }))
+ )
}
- StyleValueData::ScrollbarColor {
- thumb_color,
- track_color,
- } => {
+ StyleValueData::ScrollbarColor(scrollbar_color_payload) => {
+ let ScrollbarColorPayload {
+ thumb_color,
+ track_color,
+ } = &**scrollbar_color_payload;
let mut changed = false;
let thumb_color = absolutize_child(thumb_color, context, &mut changed)?;
let track_color = absolutize_child(track_color, context, &mut changed)?;
rebuild!(
changed,
- StyleValueData::ScrollbarColor {
+ StyleValueData::ScrollbarColor(StyleValueBox::new(ScrollbarColorPayload {
thumb_color,
track_color
- }
+ }))
)
}
- StyleValueData::Shadow {
- shadow_type,
- color,
- offset_x,
- offset_y,
- blur_radius,
- spread_distance,
- placement,
- } => {
+ StyleValueData::Shadow(shadow_payload) => {
+ let ShadowPayload {
+ shadow_type,
+ color,
+ offset_x,
+ offset_y,
+ blur_radius,
+ spread_distance,
+ placement,
+ } = &**shadow_payload;
// The C++ absolutization reads through the defaulting accessors, so absent color,
// blur and spread slots materialize as currentcolor and zero lengths.
let mut changed = false;
@@ -1779,7 +1852,7 @@ pub(crate) fn absolutize(value: &StyleValueData, context: &AbsolutizationContext
let spread_distance = absolutize_defaulted_child(spread_distance, zero_px_length, context, &mut changed)?;
rebuild!(
changed,
- StyleValueData::Shadow {
+ StyleValueData::Shadow(StyleValueBox::new(ShadowPayload {
shadow_type: *shadow_type,
color,
offset_x,
@@ -1787,7 +1860,7 @@ pub(crate) fn absolutize(value: &StyleValueData, context: &AbsolutizationContext
blur_radius,
spread_distance,
placement: *placement,
- }
+ }))
)
}
StyleValueData::FontStyle {
@@ -1836,21 +1909,22 @@ pub(crate) fn absolutize(value: &StyleValueData, context: &AbsolutizationContext
}
)
}
- StyleValueData::RadialSize {
- component_count,
- is_extent_0,
- extent_0,
- value_0,
- is_extent_1,
- extent_1,
- value_1,
- } => {
+ StyleValueData::RadialSize(radial_size_payload) => {
+ let RadialSizePayload {
+ component_count,
+ is_extent_0,
+ extent_0,
+ value_0,
+ is_extent_1,
+ extent_1,
+ value_1,
+ } = &**radial_size_payload;
let mut changed = false;
let value_0 = absolutize_child(value_0, context, &mut changed)?;
let value_1 = absolutize_child(value_1, context, &mut changed)?;
rebuild!(
changed,
- StyleValueData::RadialSize {
+ StyleValueData::RadialSize(StyleValueBox::new(RadialSizePayload {
component_count: *component_count,
is_extent_0: *is_extent_0,
extent_0: *extent_0,
@@ -1858,16 +1932,17 @@ pub(crate) fn absolutize(value: &StyleValueData, context: &AbsolutizationContext
is_extent_1: *is_extent_1,
extent_1: *extent_1,
value_1,
- }
+ }))
)
}
- StyleValueData::Transformation {
- property,
- transform_function,
- values: original_values,
- matrix_values,
- ..
- } => {
+ StyleValueData::Transformation(transformation_payload) => {
+ let TransformationPayload {
+ property,
+ transform_function,
+ values: original_values,
+ matrix_values,
+ ..
+ } = &**transformation_payload;
let mut changed = false;
let mut values = absolutize_list(original_values, context, &mut changed)?;
// https://drafts.csswg.org/css-viewport/#zoom-property
@@ -1917,12 +1992,12 @@ pub(crate) fn absolutize(value: &StyleValueData, context: &AbsolutizationContext
changed |= retained_matrix_values != *matrix_values;
rebuild!(
changed,
- StyleValueData::Transformation {
+ StyleValueData::Transformation(StyleValueBox::new(TransformationPayload {
property: *property,
transform_function: *transform_function,
values: RetainedStyleValueDataList::from_retained_values(values),
matrix_values: retained_matrix_values,
- }
+ }))
)
}
StyleValueData::Filter {
@@ -1953,7 +2028,10 @@ pub(crate) fn absolutize(value: &StyleValueData, context: &AbsolutizationContext
// drop-shadow hand-rolls its shadow absolutization in C++: color and blur
// materialize their defaults, but spread stays absent.
let value = if *kind == 1 {
- let Some(StyleValueData::Shadow {
+ let Some(StyleValueData::Shadow(shadow_payload)) = value.optional_data() else {
+ return None;
+ };
+ let ShadowPayload {
shadow_type,
color,
offset_x,
@@ -1961,16 +2039,13 @@ pub(crate) fn absolutize(value: &StyleValueData, context: &AbsolutizationContext
blur_radius,
spread_distance,
placement,
- }) = value.optional_data()
- else {
- return None;
- };
+ } = &**shadow_payload;
let color = absolutize_defaulted_child(color, currentcolor_keyword, context, &mut changed)?;
let offset_x = absolutize_child(offset_x, context, &mut changed)?;
let offset_y = absolutize_child(offset_y, context, &mut changed)?;
let blur_radius = absolutize_defaulted_child(blur_radius, zero_px_length, context, &mut changed)?;
if changed {
- retain_new(StyleValueData::Shadow {
+ retain_new(StyleValueData::Shadow(StyleValueBox::new(ShadowPayload {
shadow_type: *shadow_type,
color,
offset_x,
@@ -1978,7 +2053,7 @@ pub(crate) fn absolutize(value: &StyleValueData, context: &AbsolutizationContext
blur_radius,
spread_distance: spread_distance.clone_retained(),
placement: *placement,
- })
+ })))
} else {
value.clone_retained()
}
@@ -2041,47 +2116,57 @@ pub(crate) fn absolutize(value: &StyleValueData, context: &AbsolutizationContext
Some(absolutized) => Some(Absolutized::Changed(retain_new(absolutized))),
}
}
- StyleValueData::Position { edge_x, edge_y } => {
+ StyleValueData::Position(position_payload) => {
+ let PositionPayload { edge_x, edge_y } = &**position_payload;
let mut changed = false;
let edge_x = absolutize_child(edge_x, context, &mut changed)?;
let edge_y = absolutize_child(edge_y, context, &mut changed)?;
- rebuild!(changed, StyleValueData::Position { edge_x, edge_y })
+ rebuild!(
+ changed,
+ StyleValueData::Position(StyleValueBox::new(PositionPayload { edge_x, edge_y }))
+ )
}
StyleValueData::BasicShape { .. } => {
absolutize_basic_shape(value, &mut |child, changed| absolutize_child(child, context, changed))
}
- StyleValueData::Ray {
- size,
- contain,
- angle,
- position,
- } => {
+ StyleValueData::Ray(ray_payload) => {
+ let RayPayload {
+ size,
+ contain,
+ angle,
+ position,
+ } = &**ray_payload;
let mut changed = false;
let angle = absolutize_child(angle, context, &mut changed)?;
let position = absolutize_child(position, context, &mut changed)?;
rebuild!(
changed,
- StyleValueData::Ray {
+ StyleValueData::Ray(StyleValueBox::new(RayPayload {
size: *size,
contain: *contain,
angle,
position,
- }
+ }))
)
}
- StyleValueData::Cursor { image, x, y } => {
+ StyleValueData::Cursor(cursor_payload) => {
+ let CursorPayload { image, x, y } = &**cursor_payload;
let mut changed = false;
let image = absolutize_child(image, context, &mut changed)?;
let x = absolutize_child(x, context, &mut changed)?;
let y = absolutize_child(y, context, &mut changed)?;
- rebuild!(changed, StyleValueData::Cursor { image, x, y })
+ rebuild!(
+ changed,
+ StyleValueData::Cursor(StyleValueBox::new(CursorPayload { image, x, y }))
+ )
}
StyleValueData::Easing { .. } => {
absolutize_easing(value, &mut |child, changed| absolutize_child(child, context, changed))
}
- StyleValueData::ImageSet { options } => {
+ StyleValueData::ImageSet(image_set_payload) => {
+ let ImageSetPayload { options } = &**image_set_payload;
let mut changed = false;
let mut absolutized_options = Vec::with_capacity(options.as_slice().len());
for option in options.as_slice() {
@@ -2092,14 +2177,15 @@ pub(crate) fn absolutize(value: &StyleValueData, context: &AbsolutizationContext
}
rebuild!(
changed,
- StyleValueData::ImageSet {
+ StyleValueData::ImageSet(StyleValueBox::new(ImageSetPayload {
options: crate::css::style_value::RetainedImageSetOptionList::from_retained_elements(
absolutized_options
),
- }
+ }))
)
}
- StyleValueData::CounterDefinitions { counter_definitions } => {
+ StyleValueData::CounterDefinitions(counter_definitions_payload) => {
+ let CounterDefinitionsPayload { counter_definitions } = &**counter_definitions_payload;
let mut changed = false;
let mut definitions = Vec::with_capacity(counter_definitions.as_slice().len());
for definition in counter_definitions.as_slice() {
@@ -2108,29 +2194,30 @@ pub(crate) fn absolutize(value: &StyleValueData, context: &AbsolutizationContext
}
rebuild!(
changed,
- StyleValueData::CounterDefinitions {
+ StyleValueData::CounterDefinitions(StyleValueBox::new(CounterDefinitionsPayload {
counter_definitions: crate::css::style_value::RetainedCounterDefinitionList::from_retained_elements(
definitions
),
- }
+ }))
)
}
- StyleValueData::CounterStyleSystem {
- kind,
- system,
- first_symbol,
- name,
- } => {
+ StyleValueData::CounterStyleSystem(counter_style_system_payload) => {
+ let CounterStyleSystemPayload {
+ kind,
+ system,
+ first_symbol,
+ name,
+ } = &**counter_style_system_payload;
let mut changed = false;
let first_symbol = absolutize_child(first_symbol, context, &mut changed)?;
rebuild!(
changed,
- StyleValueData::CounterStyleSystem {
+ StyleValueData::CounterStyleSystem(StyleValueBox::new(CounterStyleSystemPayload {
kind: *kind,
system: *system,
first_symbol,
name: name.clone(),
- }
+ }))
)
}
StyleValueData::GridTrackPlacement { .. } | StyleValueData::GridTrackSizeList { .. } => {
@@ -2155,11 +2242,12 @@ pub(crate) fn absolutize(value: &StyleValueData, context: &AbsolutizationContext
}
})))
}
- StyleValueData::Url {
- url,
- url_type,
- modifiers,
- } => {
+ StyleValueData::Url(url_payload) => {
+ let UrlPayload {
+ url,
+ url_type,
+ modifiers,
+ } = &**url_payload;
// https://drafts.csswg.org/css-values-4/#local-urls
// When serializing a url() with the local url flag set, it must serialize as just the fragment.
if url.is_empty() || url.is_fragment() {
@@ -2186,35 +2274,38 @@ pub(crate) fn absolutize(value: &StyleValueData, context: &AbsolutizationContext
let Some(resolved_url) = resolved_url else {
return Some(Absolutized::Unchanged);
};
- Some(Absolutized::Changed(retain_new(StyleValueData::Url {
- url: crate::css::style_value::RetainedString::from_ascii(resolved_url.into()),
- url_type: *url_type,
- modifiers: modifiers.clone(),
- })))
+ Some(Absolutized::Changed(retain_new(StyleValueData::Url(
+ StyleValueBox::new(UrlPayload {
+ url: crate::css::style_value::RetainedString::from_ascii(resolved_url.into()),
+ url_type: *url_type,
+ modifiers: modifiers.clone(),
+ }),
+ ))))
}
StyleValueData::Image { .. } => absolutize_image(value, context),
// https://drafts.csswg.org/css-values-5/#random-caching
// If the random function's <random-value-sharing> is fixed <number>, the random base value is that number.
// Otherwise, it is the base value drawn for the function's random caching key.
- StyleValueData::RandomValueSharing {
- fixed_value,
- is_auto,
- has_name,
- name,
- element_shared,
- } => {
+ StyleValueData::RandomValueSharing(random_value_sharing_payload) => {
+ let RandomValueSharingPayload {
+ fixed_value,
+ is_auto,
+ has_name,
+ name,
+ element_shared,
+ } = &**random_value_sharing_payload;
if fixed_value.optional_data().is_some() {
let mut changed = false;
let fixed_value = absolutize_child(fixed_value, context, &mut changed)?;
return rebuild!(
changed,
- StyleValueData::RandomValueSharing {
+ StyleValueData::RandomValueSharing(StyleValueBox::new(RandomValueSharingPayload {
fixed_value,
is_auto: *is_auto,
has_name: *has_name,
name: name.clone(),
element_shared: *element_shared,
- }
+ }))
);
}
let base_value = context
@@ -2222,13 +2313,15 @@ pub(crate) fn absolutize(value: &StyleValueData, context: &AbsolutizationContext
.iter()
.find(|base_value| std::ptr::eq(base_value.source.cast(), value))?
.value;
- Some(Absolutized::Changed(retain_new(StyleValueData::RandomValueSharing {
- fixed_value: retain_new(StyleValueData::Number { value: base_value }),
- is_auto: false,
- has_name: false,
- name: CssString::none(),
- element_shared: false,
- })))
+ Some(Absolutized::Changed(retain_new(StyleValueData::RandomValueSharing(
+ StyleValueBox::new(RandomValueSharingPayload {
+ fixed_value: retain_new(StyleValueData::Number { value: base_value }),
+ is_auto: false,
+ has_name: false,
+ name: CssString::none(),
+ element_shared: false,
+ }),
+ ))))
}
StyleValueData::ColorFunction { .. } => absolutize_color_function(value, context),
@@ -2269,7 +2362,8 @@ pub(crate) fn absolutize(value: &StyleValueData, context: &AbsolutizationContext
// https://drafts.csswg.org/css-color-5/#funcdef-light-dark
// With no scheme the value computes to itself; otherwise it collapses to the matching
// branch's absolutized value.
- StyleValueData::LightDark { light, dark, .. } => {
+ StyleValueData::LightDark(light_dark_payload) => {
+ let LightDarkPayload { light, dark, .. } = &**light_dark_payload;
let Some(scheme) = context.scheme else {
return Some(Absolutized::Unchanged);
};
diff --git a/Libraries/LibWeb/Rust/src/css/animated_overlay.rs b/Libraries/LibWeb/Rust/src/css/animated_overlay.rs
index 483c775f0ab..353317df19f 100644
--- a/Libraries/LibWeb/Rust/src/css/animated_overlay.rs
+++ b/Libraries/LibWeb/Rust/src/css/animated_overlay.rs
@@ -28,6 +28,9 @@ pub struct AnimatedOverlay {
/// Properties to treat as included in will-change due to animations, separate from sampled CSS values.
pub(crate) implicit_will_change: Vec<u16>,
pub(crate) animation_preparation: Option<Arc<crate::css::animation::PreparedAnimationBatch>>,
+ /// The keyframe values the last sample substituted against the element, which the next reuses while what they
+ /// read stands.
+ pub(crate) keyframe_conversions: Option<Arc<crate::css::animation::KeyframeConversions>>,
}
impl Clone for AnimatedOverlay {
@@ -37,6 +40,7 @@ impl Clone for AnimatedOverlay {
entries,
implicit_will_change: self.implicit_will_change.clone(),
animation_preparation: self.animation_preparation.clone(),
+ keyframe_conversions: self.keyframe_conversions.clone(),
}
}
}
@@ -130,6 +134,7 @@ impl AnimatedOverlay {
entries,
implicit_will_change: Vec::new(),
animation_preparation: self.animation_preparation.clone(),
+ keyframe_conversions: self.keyframe_conversions.clone(),
}
}
@@ -193,6 +198,7 @@ pub extern "C" fn rust_animated_overlay_create() -> *mut AnimatedOverlay {
entries: Vec::new(),
implicit_will_change: Vec::new(),
animation_preparation: None,
+ keyframe_conversions: None,
}))
}
@@ -228,7 +234,7 @@ pub extern "C" fn rust_animated_overlay_free(overlay: OwnedBox<AnimatedOverlay>)
pub extern "C" fn rust_animated_overlay_set(
overlay: &mut AnimatedOverlay,
property: u16,
- value: crate::css::ffi_support::ArcRef<'_, StyleValueData>,
+ value: crate::css::style_value_arc::StyleValueRef<'_>,
inherited: bool,
result_of_transition: bool,
) {
diff --git a/Libraries/LibWeb/Rust/src/css/animation.rs b/Libraries/LibWeb/Rust/src/css/animation.rs
index fd71814337e..ccfbadff3be 100644
--- a/Libraries/LibWeb/Rust/src/css/animation.rs
+++ b/Libraries/LibWeb/Rust/src/css/animation.rs
@@ -9,6 +9,13 @@
// Animation values use the same thread-confined shared graph as the rest of the style core.
#![allow(clippy::arc_with_non_send_sync)]
+use crate::css::style_value::{
+ BackgroundSizePayload, BorderImageSlicePayload, BorderRadiusPayload, BorderRadiusRectPayload, CalculatedPayload,
+ ColorFunctionPayload, FunctionPayload, GridTrackSizeListPayload, OpenTypeTaggedPayload, PositionPayload,
+ RadialSizePayload, RandomValueSharingPayload, RatioPayload, RayPayload, RectPayload, ScrollbarColorPayload,
+ ShadowPayload, StyleValueBox, TransformationPayload, UnresolvedPayload,
+};
+use crate::css::style_value_arc::StyleValueArc;
use std::collections::BTreeMap;
use std::sync::Arc;
@@ -144,7 +151,7 @@ impl AnimationValueResult {
FfiAnimationValueResult {
value: self
.value
- .map_or(std::ptr::null(), |value| Arc::into_raw(value.into_arc())),
+ .map_or(std::ptr::null(), |value| StyleValueArc::into_raw(value.into_arc())),
handled: self.handled,
}
}
@@ -158,7 +165,7 @@ impl AnimationValueResult {
pub(crate) unsafe fn style_value_from_easing(descriptor: &FfiEasingDescriptor) -> *const StyleValueData {
use crate::css::easing::FfiEasingKind;
use crate::css::style_value::{RetainedLinearEasingStop, RetainedLinearEasingStopList};
- let retain = |value| RetainedStyleValueData::from_arc(Arc::new(value));
+ let retain = |value| RetainedStyleValueData::from_arc(StyleValueArc::new(value));
let mut stops = Vec::new();
let mut x1 = empty_retained_style_value();
let mut y1 = empty_retained_style_value();
@@ -193,17 +200,19 @@ pub(crate) unsafe fn style_value_from_easing(descriptor: &FfiEasingDescriptor) -
});
}
}
- Arc::into_raw(Arc::new(StyleValueData::Easing {
- kind: descriptor.kind as u8,
- linear_stops: RetainedLinearEasingStopList::from_retained_elements(stops),
- x1,
- y1,
- x2,
- y2,
- number_of_intervals,
- step_position: descriptor.step_position,
- is_keyword: false,
- }))
+ StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::Easing(StyleValueBox::new(
+ crate::css::style_value::EasingPayload {
+ kind: descriptor.kind as u8,
+ linear_stops: RetainedLinearEasingStopList::from_retained_elements(stops),
+ x1,
+ y1,
+ x2,
+ y2,
+ number_of_intervals,
+ step_position: descriptor.step_position,
+ is_keyword: false,
+ },
+ ))))
}
/// Evaluate a resolved easing descriptor without consulting C++.
@@ -294,17 +303,12 @@ pub struct FfiAnimationContext<'a> {
/// Whether the computed interpolate-size of a style lets sizing keywords interpolate with lengths.
/// https://drafts.csswg.org/css-values-5/#valdef-interpolate-size-allow-keywords
pub(crate) fn allows_keyword_size_interpolation(
- table: &crate::css::computed_longhand_table::ComputedLonghandTable,
+ longhands: crate::css::style::ViewLonghands<'_>,
overlay: Option<&crate::css::animated_overlay::AnimatedOverlay>,
) -> bool {
matches!(
- table
- .effective_value_handle(
- overlay,
- crate::css::property_metadata::property_id::INTERPOLATE_SIZE,
- true
- )
- .0
+ longhands
+ .effective_value(overlay, crate::css::property_metadata::property_id::INTERPOLATE_SIZE)
.optional_data(),
Some(StyleValueData::Keyword {
keyword: crate::css::css_enums::keyword::ALLOW_KEYWORDS
@@ -384,7 +388,7 @@ pub(crate) struct ComputedAnimationBatch<'a> {
pub(crate) preparation_reads_custom_property_environments: bool,
/// What a preparation is made from where the overlay holds none for the sampled effects.
pub(crate) preparation_inputs: Option<AnimationPreparationInputs>,
- pub(crate) underlying_longhand_table: &'a crate::css::computed_longhand_table::ComputedLonghandTable,
+ pub(crate) underlying_longhands: crate::css::style::ViewLonghands<'a>,
pub(crate) overlay: &'a mut crate::css::animated_overlay::AnimatedOverlay,
/// What an animation of each custom property composes over, and what a keyframe saying
/// `initial` takes, indexed by the number the property animates under, less one.
@@ -582,17 +586,15 @@ fn substitution_marks_of(written: &StyleValueData) -> u8 {
SUBSTITUTION_MARK_ATTR, SUBSTITUTION_MARK_CUSTOM_FUNCTION, SUBSTITUTION_MARK_IF, SUBSTITUTION_MARK_INHERIT,
SUBSTITUTION_MARK_VAR,
};
- let StyleValueData::Unresolved {
- presence_var,
- presence_attr,
- presence_if,
- presence_inherit,
- presence_dashed_function,
- ..
- } = written
- else {
+ let StyleValueData::Unresolved(unresolved_payload) = written else {
return 0;
};
+ let unresolved_payload: &UnresolvedPayload = unresolved_payload;
+ let presence_var = &unresolved_payload.presence().var;
+ let presence_attr = &unresolved_payload.presence().attr;
+ let presence_if = &unresolved_payload.presence().if_;
+ let presence_inherit = &unresolved_payload.presence().inherit;
+ let presence_dashed_function = &unresolved_payload.presence().dashed_function;
[
(*presence_var, SUBSTITUTION_MARK_VAR),
(*presence_attr, SUBSTITUTION_MARK_ATTR),
@@ -759,9 +761,10 @@ fn resolve_animation_declarations(
.into_iter()
.map(|source| {
let sharing = unsafe { &*source };
- let StyleValueData::RandomValueSharing { has_name, name, .. } = sharing else {
+ let StyleValueData::RandomValueSharing(random_value_sharing_payload) = sharing else {
unreachable!();
};
+ let RandomValueSharingPayload { has_name, name, .. } = &**random_value_sharing_payload;
AnimationUnfixedRandomSharing {
source,
name: if *has_name { name.units().to_vec() } else { Vec::new() },
@@ -951,7 +954,7 @@ fn angle_to_degrees(value: f64, unit: u8) -> Option<f64> {
}
fn owned(value: StyleValueData) -> AnimationValueResult {
- handled_retained_value(RetainedStyleValueData::from_arc(Arc::new(value)))
+ handled_retained_value(RetainedStyleValueData::from_arc(StyleValueArc::new(value)))
}
fn not_handled() -> AnimationValueResult {
@@ -1122,9 +1125,10 @@ fn decode_scale_components(value: &StyleValueData) -> Option<Vec<f64>> {
if matches!(value, StyleValueData::Keyword { keyword } if *keyword == crate::css::style_compute::none_keyword()) {
return Some(vec![1.0, 1.0]);
}
- let StyleValueData::Transformation { values, .. } = value else {
+ let StyleValueData::Transformation(transformation_payload) = value else {
return None;
};
+ let TransformationPayload { values, .. } = &**transformation_payload;
if !matches!(values.as_slice().len(), 2 | 3) {
return None;
}
@@ -1175,16 +1179,18 @@ fn interpolate_scale(from: &StyleValueData, to: &StyleValueData, delta: f32) ->
.zip(to)
.map(|(from, to)| retained_number(interpolate_f64(from, to, delta, None)))
.collect();
- owned(StyleValueData::Transformation {
- property: crate::css::property_metadata::property_id::SCALE,
- transform_function: if is_3d {
- TRANSFORM_FUNCTION_SCALE_3D
- } else {
- TRANSFORM_FUNCTION_SCALE
+ owned(StyleValueData::Transformation(StyleValueBox::new(
+ TransformationPayload {
+ property: crate::css::property_metadata::property_id::SCALE,
+ transform_function: if is_3d {
+ TRANSFORM_FUNCTION_SCALE_3D
+ } else {
+ TRANSFORM_FUNCTION_SCALE
+ },
+ values: RetainedStyleValueDataList::from_retained_values(values),
+ matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
},
- values: RetainedStyleValueDataList::from_retained_values(values),
- matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
- })
+ )))
}
/// https://drafts.csswg.org/css-values-5/#sizing-property
@@ -1329,7 +1335,10 @@ fn length_percentage_calculation_node(value: &StyleValueData) -> Option<Arc<crat
StyleValueData::Percentage { value } => Some(Arc::new(crate::css::calc::CalcNode::Numeric(
crate::css::calc::CalcNumericValue::Percentage(*value),
))),
- StyleValueData::Calculated { rust_calculation, .. } => Some(rust_calculation.node_arc()),
+ StyleValueData::Calculated(calculated_payload) => {
+ let CalculatedPayload { rust_calculation, .. } = &**calculated_payload;
+ Some(rust_calculation.node_arc())
+ }
_ => None,
}
}
@@ -1369,7 +1378,10 @@ fn numeric_calculation_node(value: &StyleValueData) -> Option<Arc<crate::css::ca
value: *value,
unit: *unit,
},
- StyleValueData::Calculated { rust_calculation, .. } => return Some(rust_calculation.node_arc()),
+ StyleValueData::Calculated(calculated_payload) => {
+ let CalculatedPayload { rust_calculation, .. } = &**calculated_payload;
+ return Some(rust_calculation.node_arc());
+ }
_ => return None,
};
Some(Arc::new(crate::css::calc::CalcNode::Numeric(numeric)))
@@ -1385,7 +1397,10 @@ struct AnimationCalculationContext<'a> {
}
fn animation_calculation_context(value: &StyleValueData) -> Option<AnimationCalculationContext<'_>> {
- let StyleValueData::Calculated {
+ let StyleValueData::Calculated(calculated_payload) = value else {
+ return None;
+ };
+ let CalculatedPayload {
resolve_as_is_number,
resolve_as_base,
has_percentages_resolve_as,
@@ -1393,10 +1408,7 @@ fn animation_calculation_context(value: &StyleValueData) -> Option<AnimationCalc
resolve_numbers_as_integers,
accepted_ranges,
..
- } = value
- else {
- return None;
- };
+ } = &**calculated_payload;
Some(AnimationCalculationContext {
resolve_as_is_number: *resolve_as_is_number,
resolve_as_base: *resolve_as_base,
@@ -1412,16 +1424,18 @@ fn retained_calculation(
resolved_type: crate::css::calc::FfiNumericType,
context: &AnimationCalculationContext<'_>,
) -> RetainedStyleValueData {
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Calculated {
- rust_calculation: crate::css::calc::CalcNodeHandle::from_arc(calculation),
- resolve_as_is_number: context.resolve_as_is_number,
- resolve_as_base: context.resolve_as_base,
- resolved_type,
- has_percentages_resolve_as: context.has_percentages_resolve_as,
- percentages_resolve_as: context.percentages_resolve_as,
- resolve_numbers_as_integers: context.resolve_numbers_as_integers,
- accepted_ranges: context.accepted_ranges.clone_owned(),
- }))
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Calculated(StyleValueBox::new(
+ CalculatedPayload {
+ rust_calculation: crate::css::calc::CalcNodeHandle::from_arc(calculation),
+ resolve_as_is_number: context.resolve_as_is_number,
+ resolve_as_base: context.resolve_as_base,
+ resolved_type,
+ has_percentages_resolve_as: context.has_percentages_resolve_as,
+ percentages_resolve_as: context.percentages_resolve_as,
+ resolve_numbers_as_integers: context.resolve_numbers_as_integers,
+ accepted_ranges: context.accepted_ranges.clone_owned(),
+ },
+ ))))
}
fn retained_length_percentage_calculation(
@@ -1449,7 +1463,8 @@ fn retained_length_percentage_calculation(
}
_ => {
let mut value = crate::css::calc::length_percentage_calculated_style_value(calculation, resolved_type);
- if let StyleValueData::Calculated { accepted_ranges, .. } = &mut value {
+ if let StyleValueData::Calculated(calculated_payload) = &mut value {
+ let CalculatedPayload { accepted_ranges, .. } = &mut **calculated_payload;
*accepted_ranges = crate::css::style_value::RetainedNumericRangeList::from_numeric_ranges(
[VALUE_TYPE_LENGTH, VALUE_TYPE_PERCENTAGE]
.into_iter()
@@ -1459,7 +1474,7 @@ fn retained_length_percentage_calculation(
value
}
};
- RetainedStyleValueData::from_arc(Arc::new(value))
+ RetainedStyleValueData::from_arc(StyleValueArc::new(value))
}
fn interpolate_translate_component(
@@ -1489,7 +1504,8 @@ fn interpolate_translate_component(
(StyleValueData::Percentage { value }, StyleValueData::Length { .. }) => *value * (1.0 - delta as f64),
_ => unreachable!(),
};
- let value = RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Percentage { value: percentage }));
+ let value =
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Percentage { value: percentage }));
return Some(value);
}
@@ -1503,9 +1519,10 @@ fn decode_translate_components(value: &StyleValueData) -> Option<Vec<RetainedSty
if matches!(value, StyleValueData::Keyword { keyword } if *keyword == crate::css::style_compute::none_keyword()) {
return Some(vec![retained_zero_px(), retained_zero_px()]);
}
- let StyleValueData::Transformation { values, .. } = value else {
+ let StyleValueData::Transformation(transformation_payload) = value else {
return None;
};
+ let TransformationPayload { values, .. } = &**transformation_payload;
if !matches!(values.as_slice().len(), 2 | 3) {
return None;
}
@@ -1539,7 +1556,7 @@ fn interpolate_translate(from: &StyleValueData, to: &StyleValueData, delta: f32)
};
let is_3d = from.len() == 3 || to.len() == 3;
let zero = || {
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Length {
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Length {
value: 0.0,
unit: crate::css::calc::canonical_pixel_unit(),
}))
@@ -1563,21 +1580,26 @@ fn interpolate_translate(from: &StyleValueData, to: &StyleValueData, delta: f32)
let Some(values) = values else {
return not_handled();
};
- owned(StyleValueData::Transformation {
- property: crate::css::property_metadata::property_id::TRANSLATE,
- transform_function: if is_3d {
- TRANSFORM_FUNCTION_TRANSLATE_3D
- } else {
- TRANSFORM_FUNCTION_TRANSLATE
+ owned(StyleValueData::Transformation(StyleValueBox::new(
+ TransformationPayload {
+ property: crate::css::property_metadata::property_id::TRANSLATE,
+ transform_function: if is_3d {
+ TRANSFORM_FUNCTION_TRANSLATE_3D
+ } else {
+ TRANSFORM_FUNCTION_TRANSLATE
+ },
+ values: RetainedStyleValueDataList::from_retained_values(values),
+ matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
},
- values: RetainedStyleValueDataList::from_retained_values(values),
- matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
- })
+ )))
}
fn has_transform_matrix_values(value: &StyleValueData) -> bool {
match value {
- StyleValueData::Transformation { matrix_values, .. } => !matrix_values.as_slice().is_empty(),
+ StyleValueData::Transformation(transformation_payload) => {
+ let TransformationPayload { matrix_values, .. } = &**transformation_payload;
+ !matrix_values.as_slice().is_empty()
+ }
StyleValueData::ValueList { values, .. } => values
.as_slice()
.iter()
@@ -1593,9 +1615,10 @@ fn preserve_transform_matrix_values(mut result: StyleValueData, sources: &[&Styl
return result;
}
match &mut result {
- StyleValueData::Transformation {
- values, matrix_values, ..
- } => {
+ StyleValueData::Transformation(transformation_payload) => {
+ let TransformationPayload {
+ values, matrix_values, ..
+ } = &mut **transformation_payload;
let mut mapped = Vec::new();
for (ordinal, (index, value)) in values
.as_slice()
@@ -1608,14 +1631,14 @@ fn preserve_transform_matrix_values(mut result: StyleValueData, sources: &[&Styl
let mut phase: Option<f32> = None;
let mut compatible = true;
for source in sources {
- let StyleValueData::Transformation {
+ let StyleValueData::Transformation(transformation_payload) = source else {
+ continue;
+ };
+ let TransformationPayload {
values: source_values,
matrix_values: source_matrix,
..
- } = source
- else {
- continue;
- };
+ } = &**transformation_payload;
let Some((source_index, source_value)) = source_values
.as_slice()
.iter()
@@ -1664,7 +1687,7 @@ fn preserve_transform_matrix_values(mut result: StyleValueData, sources: &[&Styl
values.as_slice().get(index).map(RetainedStyleValueData::data)
})
.collect();
- RetainedStyleValueData::from_arc(Arc::new(preserve_transform_matrix_values(
+ RetainedStyleValueData::from_arc(StyleValueArc::new(preserve_transform_matrix_values(
value.data().clone(),
&sources,
)))
@@ -1678,12 +1701,12 @@ fn preserve_transform_matrix_values(mut result: StyleValueData, sources: &[&Styl
}
fn effective_rotation_radians(value: &StyleValueData) -> Option<f64> {
- let StyleValueData::Transformation {
- values, matrix_values, ..
- } = value
- else {
+ let StyleValueData::Transformation(transformation_payload) = value else {
return None;
};
+ let TransformationPayload {
+ values, matrix_values, ..
+ } = &**transformation_payload;
let (index, angle) = values
.as_slice()
.iter()
@@ -1711,7 +1734,7 @@ fn interpolate_individual_rotate(
&endpoints[..]
};
result.value = result.value.map(|value| {
- RetainedStyleValueData::from_arc(Arc::new(preserve_transform_matrix_values(
+ RetainedStyleValueData::from_arc(StyleValueArc::new(preserve_transform_matrix_values(
value.data().clone(),
sources,
)))
@@ -1741,18 +1764,19 @@ fn interpolate_individual_rotate_impl(
let is_none = |value: &StyleValueData| matches!(value, StyleValueData::Keyword { keyword } if *keyword == none);
let is_2d = |value: &StyleValueData| {
is_none(value)
- || matches!(value, StyleValueData::Transformation { transform_function, values, .. }
- if matches!(*transform_function, TRANSFORM_FUNCTION_ROTATE | TRANSFORM_FUNCTION_ROTATE_Z)
- && values.as_slice().len() == 1)
+ || matches!(value, StyleValueData::Transformation(transformation)
+ if matches!(transformation.transform_function, TRANSFORM_FUNCTION_ROTATE | TRANSFORM_FUNCTION_ROTATE_Z)
+ && transformation.values.as_slice().len() == 1)
};
if is_2d(from) && is_2d(to) {
let angle = |value: &StyleValueData| {
if is_none(value) {
return Some(0.0);
}
- let StyleValueData::Transformation { values, .. } = value else {
+ let StyleValueData::Transformation(transformation_payload) = value else {
return None;
};
+ let TransformationPayload { values, .. } = &**transformation_payload;
let [angle] = values.as_slice() else {
return None;
};
@@ -1761,16 +1785,18 @@ fn interpolate_individual_rotate_impl(
let (Some(from), Some(to)) = (angle(from), angle(to)) else {
return not_handled();
};
- let angle = RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Angle {
+ let angle = RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Angle {
value: interpolate_f64(from, to, delta, None),
unit: 0,
}));
- return owned(StyleValueData::Transformation {
- property: crate::css::property_metadata::property_id::ROTATE,
- transform_function: TRANSFORM_FUNCTION_ROTATE,
- values: RetainedStyleValueDataList::from_retained_values(vec![angle]),
- matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
- });
+ return owned(StyleValueData::Transformation(StyleValueBox::new(
+ TransformationPayload {
+ property: crate::css::property_metadata::property_id::ROTATE,
+ transform_function: TRANSFORM_FUNCTION_ROTATE,
+ values: RetainedStyleValueDataList::from_retained_values(vec![angle]),
+ matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
+ },
+ )));
}
let axis_rotation = |x: f64, y: f64, z: f64, angle: &RetainedStyleValueData| {
@@ -1783,7 +1809,8 @@ fn interpolate_individual_rotate_impl(
};
let normalize = |value: &StyleValueData| {
if is_none(value) {
- let angle = RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Angle { value: 0.0, unit: 0 }));
+ let angle =
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Angle { value: 0.0, unit: 0 }));
return Some(RetainedStyleValueDataList::from_retained_values(vec![
retained_number(0.0),
retained_number(0.0),
@@ -1791,14 +1818,14 @@ fn interpolate_individual_rotate_impl(
angle,
]));
}
- let StyleValueData::Transformation {
+ let StyleValueData::Transformation(transformation_payload) = value else {
+ return None;
+ };
+ let TransformationPayload {
transform_function,
values,
..
- } = value
- else {
- return None;
- };
+ } = &**transformation_payload;
match (*transform_function, values.as_slice()) {
(TRANSFORM_FUNCTION_ROTATE | TRANSFORM_FUNCTION_ROTATE_Z, [angle]) => axis_rotation(0.0, 0.0, 1.0, angle),
(TRANSFORM_FUNCTION_ROTATE_X, [angle]) => axis_rotation(1.0, 0.0, 0.0, angle),
@@ -2195,21 +2222,23 @@ fn composite_grid_track_entries(
}
fn retained_percentage(value: f64) -> RetainedStyleValueData {
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Percentage { value }))
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Percentage { value }))
}
fn retained_computed_center_position() -> RetainedStyleValueData {
let edge = || {
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Edge {
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Edge {
has_edge: false,
edge: 0,
offset: retained_percentage(50.0),
}))
};
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Position {
- edge_x: edge(),
- edge_y: edge(),
- }))
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Position(StyleValueBox::new(
+ PositionPayload {
+ edge_x: edge(),
+ edge_y: edge(),
+ },
+ ))))
}
#[derive(Clone, Copy, PartialEq, Eq)]
@@ -2244,7 +2273,10 @@ fn resolve_color_component(value: &StyleValueData, reference_value: f32) -> Opti
}
fn native_color_components(value: &StyleValueData) -> Option<NativeColor> {
- let StyleValueData::ColorFunction {
+ let StyleValueData::ColorFunction(color_function_payload) = value else {
+ return None;
+ };
+ let ColorFunctionPayload {
color_base,
channel_0,
channel_1,
@@ -2252,10 +2284,7 @@ fn native_color_components(value: &StyleValueData) -> Option<NativeColor> {
alpha,
origin_color,
..
- } = value
- else {
- return None;
- };
+ } = &**color_function_payload;
if !color_base.has_color_type || origin_color.optional_data().is_some() {
return None;
}
@@ -2545,20 +2574,22 @@ fn combine_modern_color(
retained_number(value as f64)
}
};
- Some(StyleValueData::ColorFunction {
- color_base: ColorBase {
- has_color_type: true,
- color_type: COLOR_TYPE_OKLAB,
- color_syntax: COLOR_SYNTAX_MODERN,
+ Some(StyleValueData::ColorFunction(StyleValueBox::new(
+ ColorFunctionPayload {
+ color_base: ColorBase {
+ has_color_type: true,
+ color_type: COLOR_TYPE_OKLAB,
+ color_syntax: COLOR_SYNTAX_MODERN,
+ },
+ channel_0: number_or_none(result[0], result_missing[0]),
+ channel_1: number_or_none(result[1], result_missing[1]),
+ channel_2: number_or_none(result[2], result_missing[2]),
+ alpha: number_or_none(result[3], result_missing[3]),
+ has_name: false,
+ name: empty_retained_fly_string(),
+ origin_color: empty_retained_style_value(),
},
- channel_0: number_or_none(result[0], result_missing[0]),
- channel_1: number_or_none(result[1], result_missing[1]),
- channel_2: number_or_none(result[2], result_missing[2]),
- alpha: number_or_none(result[3], result_missing[3]),
- has_name: false,
- name: empty_retained_fly_string(),
- origin_color: empty_retained_style_value(),
- })
+ )))
}
fn combine_legacy_rgb(
@@ -2606,20 +2637,22 @@ fn combine_legacy_rgb(
// NB: Legacy sRGB content interpolates in sRGB and produces a legacy rgb() result.
let to_byte = |value: f32| (value * 255.0).round().clamp(0.0, 255.0) as u8;
let alpha = to_byte(result[3]);
- Some(StyleValueData::ColorFunction {
- color_base: ColorBase {
- has_color_type: true,
- color_type: COLOR_TYPE_RGB,
- color_syntax: COLOR_SYNTAX_LEGACY,
+ Some(StyleValueData::ColorFunction(StyleValueBox::new(
+ ColorFunctionPayload {
+ color_base: ColorBase {
+ has_color_type: true,
+ color_type: COLOR_TYPE_RGB,
+ color_syntax: COLOR_SYNTAX_LEGACY,
+ },
+ channel_0: retained_number(to_byte(result[0]) as f64),
+ channel_1: retained_number(to_byte(result[1]) as f64),
+ channel_2: retained_number(to_byte(result[2]) as f64),
+ alpha: retained_number(alpha as f64 / 255.0),
+ has_name: false,
+ name: empty_retained_fly_string(),
+ origin_color: empty_retained_style_value(),
},
- channel_0: retained_number(to_byte(result[0]) as f64),
- channel_1: retained_number(to_byte(result[1]) as f64),
- channel_2: retained_number(to_byte(result[2]) as f64),
- alpha: retained_number(alpha as f64 / 255.0),
- has_name: false,
- name: empty_retained_fly_string(),
- origin_color: empty_retained_style_value(),
- })
+ )))
}
fn empty_shape_points() -> RetainedShapePointList {
@@ -2679,7 +2712,7 @@ fn interpolate_radial_size(
interpolate_translate_component(property_id, from.data(), to.data(), delta)
};
if from.component_count == 1 && to.component_count == 1 {
- return Some(StyleValueData::RadialSize {
+ return Some(StyleValueData::RadialSize(StyleValueBox::new(RadialSizePayload {
component_count: 1,
is_extent_0: false,
extent_0: 0,
@@ -2687,7 +2720,7 @@ fn interpolate_radial_size(
is_extent_1: false,
extent_1: 0,
value_1: empty_retained_style_value(),
- });
+ })));
}
let from_vertical = if from.component_count == 2 {
@@ -2700,7 +2733,7 @@ fn interpolate_radial_size(
} else {
to.value_0
};
- Some(StyleValueData::RadialSize {
+ Some(StyleValueData::RadialSize(StyleValueBox::new(RadialSizePayload {
component_count: 2,
is_extent_0: false,
extent_0: 0,
@@ -2708,7 +2741,7 @@ fn interpolate_radial_size(
is_extent_1: false,
extent_1: 0,
value_1: interpolate(from_vertical, to_vertical)?,
- })
+ })))
}
fn interpolate_basic_shape(
@@ -3026,7 +3059,7 @@ fn composite_radial_size(
composite_retained_value(underlying, animated, operation)
};
if underlying.component_count == 1 && animated.component_count == 1 {
- return Some(StyleValueData::RadialSize {
+ return Some(StyleValueData::RadialSize(StyleValueBox::new(RadialSizePayload {
component_count: 1,
is_extent_0: false,
extent_0: 0,
@@ -3034,7 +3067,7 @@ fn composite_radial_size(
is_extent_1: false,
extent_1: 0,
value_1: empty_retained_style_value(),
- });
+ })));
}
let underlying_vertical = if underlying.component_count == 2 {
@@ -3047,7 +3080,7 @@ fn composite_radial_size(
} else {
animated.value_0
};
- Some(StyleValueData::RadialSize {
+ Some(StyleValueData::RadialSize(StyleValueBox::new(RadialSizePayload {
component_count: 2,
is_extent_0: false,
extent_0: 0,
@@ -3055,7 +3088,7 @@ fn composite_radial_size(
is_extent_1: false,
extent_1: 0,
value_1: composite(underlying_vertical, animated_vertical)?,
- })
+ })))
}
fn composite_basic_shape(
@@ -3207,8 +3240,8 @@ fn join_offset_path(path: StyleValueData, coord_box: u16) -> StyleValueData {
}
StyleValueData::ValueList {
values: RetainedStyleValueDataList::from_retained_values(vec![
- RetainedStyleValueData::from_arc(Arc::new(path)),
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Keyword { keyword: coord_box })),
+ RetainedStyleValueData::from_arc(StyleValueArc::new(path)),
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Keyword { keyword: coord_box })),
]),
separator: 0,
collapsible: false,
@@ -3247,23 +3280,21 @@ fn interpolate_offset_path(
/// https://drafts.csswg.org/motion-1/#ray-function
/// NB: Rays interpolate their angles and positions when they have the same size and containment.
fn interpolate_ray(property_id: u16, from: &StyleValueData, to: &StyleValueData, delta: f32) -> Option<StyleValueData> {
- let (
- StyleValueData::Ray {
- size: from_size,
- contain: from_contain,
- angle: from_angle,
- position: from_position,
- },
- StyleValueData::Ray {
- size: to_size,
- contain: to_contain,
- angle: to_angle,
- position: to_position,
- },
- ) = (from, to)
- else {
+ let (StyleValueData::Ray(ray_payload_1), StyleValueData::Ray(ray_payload_2)) = (from, to) else {
return None;
};
+ let RayPayload {
+ size: from_size,
+ contain: from_contain,
+ angle: from_angle,
+ position: from_position,
+ } = &**ray_payload_1;
+ let RayPayload {
+ size: to_size,
+ contain: to_contain,
+ angle: to_angle,
+ position: to_position,
+ } = &**ray_payload_2;
if from_size != to_size || from_contain != to_contain {
return None;
}
@@ -3275,12 +3306,12 @@ fn interpolate_ray(property_id: u16, from: &StyleValueData, to: &StyleValueData,
}
_ => return None,
};
- Some(StyleValueData::Ray {
+ Some(StyleValueData::Ray(StyleValueBox::new(RayPayload {
size: *from_size,
contain: *from_contain,
angle,
position,
- })
+ })))
}
fn composite_offset_path(
@@ -3297,20 +3328,19 @@ fn composite_offset_path(
return None;
}
let path = match (underlying_path, animated_path) {
- (
- StyleValueData::Ray {
+ (StyleValueData::Ray(ray_payload_1), StyleValueData::Ray(ray_payload_2)) => {
+ let RayPayload {
size: underlying_size,
contain: underlying_contain,
angle: underlying_angle,
position: underlying_position,
- },
- StyleValueData::Ray {
+ } = &**ray_payload_1;
+ let RayPayload {
size,
contain,
angle,
position,
- },
- ) => {
+ } = &**ray_payload_2;
if underlying_size != size || underlying_contain != contain {
return None;
}
@@ -3319,12 +3349,12 @@ fn composite_offset_path(
(Some(_), Some(_)) => composite_retained_value(underlying_position, position, operation)?,
_ => return None,
};
- StyleValueData::Ray {
+ StyleValueData::Ray(StyleValueBox::new(RayPayload {
size: *size,
contain: *contain,
angle: composite_retained_value(underlying_angle, angle, operation)?,
position,
- }
+ }))
}
(StyleValueData::BasicShape { .. }, StyleValueData::BasicShape { .. }) => {
composite_basic_shape(underlying_path, animated_path, operation)?
@@ -3363,10 +3393,10 @@ fn join_offset_rotate(auto: bool, degrees: f64) -> StyleValueData {
}
StyleValueData::ValueList {
values: RetainedStyleValueDataList::from_retained_values(vec![
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Keyword {
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Keyword {
keyword: crate::css::css_enums::keyword::AUTO,
})),
- RetainedStyleValueData::from_arc(Arc::new(angle)),
+ RetainedStyleValueData::from_arc(StyleValueArc::new(angle)),
]),
separator: 0,
collapsible: false,
@@ -3410,14 +3440,14 @@ fn decode_rotation(value: &StyleValueData) -> Option<([f64; 3], f64)> {
if matches!(value, StyleValueData::Keyword { keyword } if *keyword == crate::css::style_compute::none_keyword()) {
return Some(([0.0, 0.0, 1.0], 0.0));
}
- let StyleValueData::Transformation {
+ let StyleValueData::Transformation(transformation_payload) = value else {
+ return None;
+ };
+ let TransformationPayload {
transform_function,
values,
..
- } = value
- else {
- return None;
- };
+ } = &**transformation_payload;
match (*transform_function, values.as_slice()) {
(TRANSFORM_FUNCTION_ROTATE | TRANSFORM_FUNCTION_ROTATE_Z, [angle]) => {
Some(([0.0, 0.0, 1.0], resolve_animation_angle(None, angle.data())?))
@@ -3481,19 +3511,19 @@ fn common_rotation_axis(
}
fn individual_rotation_value(axis: [f64; 3], angle_degrees: f64) -> StyleValueData {
- let angle = RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Angle {
+ let angle = RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Angle {
value: angle_degrees,
unit: 0,
}));
if axis == [0.0, 0.0, 1.0] {
- return StyleValueData::Transformation {
+ return StyleValueData::Transformation(StyleValueBox::new(TransformationPayload {
property: crate::css::property_metadata::property_id::ROTATE,
transform_function: TRANSFORM_FUNCTION_ROTATE,
values: RetainedStyleValueDataList::from_retained_values(vec![angle]),
matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
- };
+ }));
}
- StyleValueData::Transformation {
+ StyleValueData::Transformation(StyleValueBox::new(TransformationPayload {
property: crate::css::property_metadata::property_id::ROTATE,
transform_function: TRANSFORM_FUNCTION_ROTATE_3D,
values: RetainedStyleValueDataList::from_retained_values(vec![
@@ -3503,7 +3533,7 @@ fn individual_rotation_value(axis: [f64; 3], angle_degrees: f64) -> StyleValueDa
angle,
]),
matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
- }
+ }))
}
fn composite_rotate(underlying: &StyleValueData, animated: &StyleValueData) -> Option<StyleValueData> {
@@ -3594,16 +3624,18 @@ fn composite_scale(
retained_number(value)
})
.collect();
- Some(StyleValueData::Transformation {
- property: crate::css::property_metadata::property_id::SCALE,
- transform_function: if is_3d {
- TRANSFORM_FUNCTION_SCALE_3D
- } else {
- TRANSFORM_FUNCTION_SCALE
+ Some(StyleValueData::Transformation(StyleValueBox::new(
+ TransformationPayload {
+ property: crate::css::property_metadata::property_id::SCALE,
+ transform_function: if is_3d {
+ TRANSFORM_FUNCTION_SCALE_3D
+ } else {
+ TRANSFORM_FUNCTION_SCALE
+ },
+ values: RetainedStyleValueDataList::from_retained_values(values),
+ matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
},
- values: RetainedStyleValueDataList::from_retained_values(values),
- matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
- })
+ )))
}
fn composite_translate(
@@ -3629,16 +3661,18 @@ fn composite_translate(
composite_scalar_value(underlying.data(), animated.data(), operation).into_value()
})
.collect::<Option<Vec<_>>>()?;
- Some(StyleValueData::Transformation {
- property: crate::css::property_metadata::property_id::TRANSLATE,
- transform_function: if is_3d {
- TRANSFORM_FUNCTION_TRANSLATE_3D
- } else {
- TRANSFORM_FUNCTION_TRANSLATE
+ Some(StyleValueData::Transformation(StyleValueBox::new(
+ TransformationPayload {
+ property: crate::css::property_metadata::property_id::TRANSLATE,
+ transform_function: if is_3d {
+ TRANSFORM_FUNCTION_TRANSLATE_3D
+ } else {
+ TRANSFORM_FUNCTION_TRANSLATE
+ },
+ values: RetainedStyleValueDataList::from_retained_values(values),
+ matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
},
- values: RetainedStyleValueDataList::from_retained_values(values),
- matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
- })
+ )))
}
fn composite_individual_transform(
@@ -3743,41 +3777,42 @@ fn composite_scalar_value(
(StyleValueData::BasicShape { .. }, StyleValueData::BasicShape { .. }) => {
composite_basic_shape(underlying, animated, operation).map_or_else(handled_without_value, owned)
}
- (
- StyleValueData::RadialSize {
+ (StyleValueData::RadialSize(radial_size_payload_1), StyleValueData::RadialSize(radial_size_payload_2)) => {
+ let RadialSizePayload {
component_count: underlying_component_count,
is_extent_0: underlying_is_extent_0,
value_0: underlying_value_0,
is_extent_1: underlying_is_extent_1,
value_1: underlying_value_1,
..
- },
- StyleValueData::RadialSize {
+ } = &**radial_size_payload_1;
+ let RadialSizePayload {
component_count: animated_component_count,
is_extent_0: animated_is_extent_0,
value_0: animated_value_0,
is_extent_1: animated_is_extent_1,
value_1: animated_value_1,
..
- },
- ) => composite_radial_size(
- RadialSizeComponents {
- component_count: *underlying_component_count,
- is_extent_0: *underlying_is_extent_0,
- value_0: underlying_value_0,
- is_extent_1: *underlying_is_extent_1,
- value_1: underlying_value_1,
- },
- RadialSizeComponents {
- component_count: *animated_component_count,
- is_extent_0: *animated_is_extent_0,
- value_0: animated_value_0,
- is_extent_1: *animated_is_extent_1,
- value_1: animated_value_1,
- },
- operation,
- )
- .map_or_else(handled_without_value, owned),
+ } = &**radial_size_payload_2;
+ composite_radial_size(
+ RadialSizeComponents {
+ component_count: *underlying_component_count,
+ is_extent_0: *underlying_is_extent_0,
+ value_0: underlying_value_0,
+ is_extent_1: *underlying_is_extent_1,
+ value_1: underlying_value_1,
+ },
+ RadialSizeComponents {
+ component_count: *animated_component_count,
+ is_extent_0: *animated_is_extent_0,
+ value_0: animated_value_0,
+ is_extent_1: *animated_is_extent_1,
+ value_1: animated_value_1,
+ },
+ operation,
+ )
+ .map_or_else(handled_without_value, owned)
+ }
(StyleValueData::Number { value: underlying }, StyleValueData::Number { value: animated }) => {
// https://drafts.csswg.org/css-values-4/#combine-numbers
// Addition of <number> is defined as Vresult = VA + VB.
@@ -3890,21 +3925,23 @@ fn composite_scalar_value(
// https://drafts.csswg.org/css-color-4/#propdef-opacity
// Computed value: specified number, clamped to the range [0,1]
- let number = RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Number {
+ let number = RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Number {
value: (underlying + animated).clamp(0.0, 1.0),
}));
owned(StyleValueData::OpacityValue { value: number })
}
(
- StyleValueData::BackgroundSize {
+ StyleValueData::BackgroundSize(background_size_payload_1),
+ StyleValueData::BackgroundSize(background_size_payload_2),
+ ) => {
+ let BackgroundSizePayload {
size_x: underlying_x,
size_y: underlying_y,
- },
- StyleValueData::BackgroundSize {
+ } = &**background_size_payload_1;
+ let BackgroundSizePayload {
size_x: animated_x,
size_y: animated_y,
- },
- ) => {
+ } = &**background_size_payload_2;
let x = composite_scalar_value(underlying_x.data(), animated_x.data(), operation);
let y = composite_scalar_value(underlying_y.data(), animated_y.data(), operation);
if !x.handled || !y.handled {
@@ -3913,10 +3950,12 @@ fn composite_scalar_value(
let (Some(x_value), Some(y_value)) = (x.value, y.value) else {
return handled_without_value();
};
- owned(StyleValueData::BackgroundSize {
- size_x: x_value,
- size_y: y_value,
- })
+ owned(StyleValueData::BackgroundSize(StyleValueBox::new(
+ BackgroundSizePayload {
+ size_x: x_value,
+ size_y: y_value,
+ },
+ )))
}
(StyleValueData::Edge { offset: underlying, .. }, StyleValueData::Edge { offset: animated, .. }) => {
let (Some(underlying), Some(animated)) = (underlying.optional_data(), animated.optional_data()) else {
@@ -3932,16 +3971,15 @@ fn composite_scalar_value(
offset: result_value,
})
}
- (
- StyleValueData::Position {
+ (StyleValueData::Position(position_payload_1), StyleValueData::Position(position_payload_2)) => {
+ let PositionPayload {
edge_x: underlying_x,
edge_y: underlying_y,
- },
- StyleValueData::Position {
+ } = &**position_payload_1;
+ let PositionPayload {
edge_x: animated_x,
edge_y: animated_y,
- },
- ) => {
+ } = &**position_payload_2;
let x = composite_scalar_value(underlying_x.data(), animated_x.data(), operation);
let y = composite_scalar_value(underlying_y.data(), animated_y.data(), operation);
if !x.handled || !y.handled {
@@ -3950,25 +3988,24 @@ fn composite_scalar_value(
let (Some(x_value), Some(y_value)) = (x.value, y.value) else {
return handled_without_value();
};
- owned(StyleValueData::Position {
+ owned(StyleValueData::Position(StyleValueBox::new(PositionPayload {
edge_x: x_value,
edge_y: y_value,
- })
+ })))
}
- (
- StyleValueData::Rect {
+ (StyleValueData::Rect(rect_payload_1), StyleValueData::Rect(rect_payload_2)) => {
+ let RectPayload {
top: underlying_top,
right: underlying_right,
bottom: underlying_bottom,
left: underlying_left,
- },
- StyleValueData::Rect {
+ } = &**rect_payload_1;
+ let RectPayload {
top: animated_top,
right: animated_right,
bottom: animated_bottom,
left: animated_left,
- },
- ) => {
+ } = &**rect_payload_2;
let combine = |underlying: &RetainedStyleValueData, animated: &RetainedStyleValueData| {
// NB: An auto offset has no amount to add, so combining it with another auto keeps it auto.
if let (
@@ -4005,12 +4042,12 @@ fn composite_scalar_value(
let Some(left) = combine(underlying_left, animated_left)? else {
return Ok(None);
};
- Ok(Some(StyleValueData::Rect {
+ Ok(Some(StyleValueData::Rect(StyleValueBox::new(RectPayload {
top,
right,
bottom,
left,
- }))
+ }))))
})();
match value {
Err(()) => handled_without_value(),
@@ -4019,17 +4056,20 @@ fn composite_scalar_value(
}
}
(
- StyleValueData::BorderRadius {
+ StyleValueData::BorderRadius(border_radius_payload_1),
+ StyleValueData::BorderRadius(border_radius_payload_2),
+ ) => {
+ let BorderRadiusPayload {
horizontal_radius: underlying_horizontal,
vertical_radius: underlying_vertical,
..
- },
- StyleValueData::BorderRadius {
+ } = &**border_radius_payload_1;
+ let BorderRadiusPayload {
horizontal_radius: animated_horizontal,
vertical_radius: animated_vertical,
..
- },
- ) => {
+ } = &**border_radius_payload_2;
+
let horizontal =
composite_scalar_value(underlying_horizontal.data(), animated_horizontal.data(), operation);
let Some(horizontal) = horizontal.into_value() else {
@@ -4039,26 +4079,28 @@ fn composite_scalar_value(
let Some(vertical) = vertical.into_value() else {
return handled_without_value();
};
- owned(StyleValueData::BorderRadius {
+ owned(StyleValueData::BorderRadius(StyleValueBox::new(BorderRadiusPayload {
is_elliptical: !radius_components_equal(horizontal.data(), vertical.data()),
horizontal_radius: horizontal,
vertical_radius: vertical,
- })
+ })))
}
(
- StyleValueData::BorderRadiusRect {
+ StyleValueData::BorderRadiusRect(border_radius_rect_payload_1),
+ StyleValueData::BorderRadiusRect(border_radius_rect_payload_2),
+ ) => {
+ let BorderRadiusRectPayload {
top_left: underlying_top_left,
top_right: underlying_top_right,
bottom_right: underlying_bottom_right,
bottom_left: underlying_bottom_left,
- },
- StyleValueData::BorderRadiusRect {
+ } = &**border_radius_rect_payload_1;
+ let BorderRadiusRectPayload {
top_left: animated_top_left,
top_right: animated_top_right,
bottom_right: animated_bottom_right,
bottom_left: animated_bottom_left,
- },
- ) => {
+ } = &**border_radius_rect_payload_2;
// https://drafts.csswg.org/web-animations-1/#animating-properties
// Corresponding individual components of the computed values are combined (interpolated, added, or accumulated) using the indicated procedure for that value type (see CSS Values 4 § 3 Combining Values: Interpolation, Addition, and Accumulation).
// If the number of components or the types of corresponding components do not match, or if any component value uses discrete animation and the two corresponding values do not match, then the property values combine as discrete.
@@ -4085,12 +4127,14 @@ fn composite_scalar_value(
let Some(bottom_left) = combine(underlying_bottom_left, animated_bottom_left)? else {
return Ok(None);
};
- Ok(Some(StyleValueData::BorderRadiusRect {
- top_left,
- top_right,
- bottom_right,
- bottom_left,
- }))
+ Ok(Some(StyleValueData::BorderRadiusRect(StyleValueBox::new(
+ BorderRadiusRectPayload {
+ top_left,
+ top_right,
+ bottom_right,
+ bottom_left,
+ },
+ ))))
})();
match value {
Err(()) => handled_without_value(),
@@ -4099,21 +4143,23 @@ fn composite_scalar_value(
}
}
(
- StyleValueData::BorderImageSlice {
+ StyleValueData::BorderImageSlice(border_image_slice_payload_1),
+ StyleValueData::BorderImageSlice(border_image_slice_payload_2),
+ ) => {
+ let BorderImageSlicePayload {
top: underlying_top,
right: underlying_right,
bottom: underlying_bottom,
left: underlying_left,
fill: underlying_fill,
- },
- StyleValueData::BorderImageSlice {
+ } = &**border_image_slice_payload_1;
+ let BorderImageSlicePayload {
top: animated_top,
right: animated_right,
bottom: animated_bottom,
left: animated_left,
fill: animated_fill,
- },
- ) => {
+ } = &**border_image_slice_payload_2;
// https://drafts.csswg.org/web-animations-1/#animating-properties
// Corresponding individual components of the computed values are combined (interpolated, added, or accumulated) using the indicated procedure for that value type (see CSS Values 4 § 3 Combining Values: Interpolation, Addition, and Accumulation).
// If the number of components or the types of corresponding components do not match, or if any component value uses discrete animation and the two corresponding values do not match, then the property values combine as discrete.
@@ -4143,13 +4189,15 @@ fn composite_scalar_value(
let Some(left) = combine(underlying_left, animated_left)? else {
return Ok(None);
};
- Ok(Some(StyleValueData::BorderImageSlice {
- top,
- right,
- bottom,
- left,
- fill: *underlying_fill,
- }))
+ Ok(Some(StyleValueData::BorderImageSlice(StyleValueBox::new(
+ BorderImageSlicePayload {
+ top,
+ right,
+ bottom,
+ left,
+ fill: *underlying_fill,
+ },
+ ))))
})();
match value {
Err(()) => handled_without_value(),
@@ -4158,18 +4206,21 @@ fn composite_scalar_value(
}
}
(
- StyleValueData::OpenTypeTagged {
+ StyleValueData::OpenTypeTagged(open_type_tagged_payload_1),
+ StyleValueData::OpenTypeTagged(open_type_tagged_payload_2),
+ ) => {
+ let OpenTypeTaggedPayload {
tag_name: underlying_tag,
packed_tag: underlying_packed_tag,
value: underlying_value,
..
- },
- StyleValueData::OpenTypeTagged {
+ } = &**open_type_tagged_payload_1;
+ let OpenTypeTaggedPayload {
tag_name: animated_tag,
value: animated_value,
..
- },
- ) => {
+ } = &**open_type_tagged_payload_2;
+
// https://drafts.csswg.org/web-animations-1/#animating-properties
// Corresponding individual components of the computed values are combined (interpolated, added, or accumulated) using the indicated procedure for that value type (see CSS Values 4 § 3 Combining Values: Interpolation, Addition, and Accumulation).
// If the number of components or the types of corresponding components do not match, or if any component value uses discrete animation and the two corresponding values do not match, then the property values combine as discrete.
@@ -4180,23 +4231,24 @@ fn composite_scalar_value(
let Some(retained_value) = value.into_value() else {
return handled_without_value();
};
- owned(StyleValueData::OpenTypeTagged {
- mode: OPEN_TYPE_MODE_FONT_VARIATION_SETTINGS,
- tag_name: underlying_tag.clone(),
- packed_tag: *underlying_packed_tag,
- value: retained_value,
- })
+ owned(StyleValueData::OpenTypeTagged(StyleValueBox::new(
+ OpenTypeTaggedPayload {
+ mode: OPEN_TYPE_MODE_FONT_VARIATION_SETTINGS,
+ tag_name: underlying_tag.clone(),
+ packed_tag: *underlying_packed_tag,
+ value: retained_value,
+ },
+ )))
}
- (
- StyleValueData::Function {
+ (StyleValueData::Function(function_payload_1), StyleValueData::Function(function_payload_2)) => {
+ let FunctionPayload {
name: underlying_name,
value: underlying_value,
- },
- StyleValueData::Function {
+ } = &**function_payload_1;
+ let FunctionPayload {
name: animated_name,
value: animated_value,
- },
- ) => {
+ } = &**function_payload_2;
// https://drafts.csswg.org/web-animations-1/#animating-properties
// Corresponding individual components of the computed values are combined (interpolated, added, or accumulated) using the indicated procedure for that value type (see CSS Values 4 § 3 Combining Values: Interpolation, Addition, and Accumulation).
// If the number of components or the types of corresponding components do not match, or if any component value uses discrete animation and the two corresponding values do not match, then the property values combine as discrete.
@@ -4207,10 +4259,10 @@ fn composite_scalar_value(
let Some(retained_value) = value.into_value() else {
return handled_without_value();
};
- owned(StyleValueData::Function {
+ owned(StyleValueData::Function(StyleValueBox::new(FunctionPayload {
name: underlying_name.clone(),
value: retained_value,
- })
+ })))
}
(
StyleValueData::TextIndent {
@@ -4291,17 +4343,20 @@ fn composite_scalar_value(
})
}
(
- StyleValueData::GridTrackSizeList {
+ StyleValueData::GridTrackSizeList(grid_track_size_list_payload_1),
+ StyleValueData::GridTrackSizeList(grid_track_size_list_payload_2),
+ ) => {
+ let GridTrackSizeListPayload {
is_subgrid: underlying_is_subgrid,
entries: underlying_entries,
..
- },
- StyleValueData::GridTrackSizeList {
+ } = &**grid_track_size_list_payload_1;
+ let GridTrackSizeListPayload {
is_subgrid: animated_is_subgrid,
entries: animated_entries,
..
- },
- ) => {
+ } = &**grid_track_size_list_payload_2;
+
let Some(entries) = composite_grid_track_entries(
*underlying_is_subgrid,
underlying_entries.as_slice(),
@@ -4311,32 +4366,32 @@ fn composite_scalar_value(
) else {
return handled_without_value();
};
- owned(StyleValueData::GridTrackSizeList {
- is_subgrid: false,
- preserve_line_name_sets: false,
- entries: RetainedGridTrackEntryList::from_retained_entries(entries),
- })
+ owned(StyleValueData::GridTrackSizeList(StyleValueBox::new(
+ GridTrackSizeListPayload {
+ is_subgrid: false,
+ preserve_line_name_sets: false,
+ entries: RetainedGridTrackEntryList::from_retained_entries(entries),
+ },
+ )))
}
(
- StyleValueData::Transformation {
- property: underlying_property,
- ..
- },
- StyleValueData::Transformation {
- property: animated_property,
- ..
- },
- ) if underlying_property == animated_property && is_individual_transform_property(*underlying_property) => {
- composite_individual_transform(*underlying_property, underlying, animated, operation)
+ StyleValueData::Transformation(underlying_transformation),
+ StyleValueData::Transformation(animated_transformation),
+ ) if underlying_transformation.property == animated_transformation.property
+ && is_individual_transform_property(underlying_transformation.property) =>
+ {
+ composite_individual_transform(underlying_transformation.property, underlying, animated, operation)
.map_or_else(handled_without_value, owned)
}
// none is the identity value of the individual transform properties, so composing onto or
// with it yields the other value unchanged.
- (StyleValueData::Keyword { keyword }, StyleValueData::Transformation { property, .. })
- if *keyword == crate::css::style_compute::none_keyword() && is_individual_transform_property(*property) =>
+ (StyleValueData::Keyword { keyword }, StyleValueData::Transformation(transformation))
+ if *keyword == crate::css::style_compute::none_keyword()
+ && is_individual_transform_property(transformation.property) =>
unsafe { handled_borrowed_value(animated) },
- (StyleValueData::Transformation { property, .. }, StyleValueData::Keyword { keyword })
- if *keyword == crate::css::style_compute::none_keyword() && is_individual_transform_property(*property) =>
+ (StyleValueData::Transformation(transformation), StyleValueData::Keyword { keyword })
+ if *keyword == crate::css::style_compute::none_keyword()
+ && is_individual_transform_property(transformation.property) =>
unsafe { handled_borrowed_value(underlying) },
_ => handled_without_value(),
}
@@ -4413,42 +4468,43 @@ fn interpolate_scalar_value(
(StyleValueData::BasicShape { .. }, StyleValueData::BasicShape { .. }) => {
interpolate_basic_shape(property_id, from, to, delta).map_or_else(handled_without_value, owned)
}
- (
- StyleValueData::RadialSize {
+ (StyleValueData::RadialSize(radial_size_payload_1), StyleValueData::RadialSize(radial_size_payload_2)) => {
+ let RadialSizePayload {
component_count: from_component_count,
is_extent_0: from_is_extent_0,
value_0: from_value_0,
is_extent_1: from_is_extent_1,
value_1: from_value_1,
..
- },
- StyleValueData::RadialSize {
+ } = &**radial_size_payload_1;
+ let RadialSizePayload {
component_count: to_component_count,
is_extent_0: to_is_extent_0,
value_0: to_value_0,
is_extent_1: to_is_extent_1,
value_1: to_value_1,
..
- },
- ) => interpolate_radial_size(
- property_id,
- RadialSizeComponents {
- component_count: *from_component_count,
- is_extent_0: *from_is_extent_0,
- value_0: from_value_0,
- is_extent_1: *from_is_extent_1,
- value_1: from_value_1,
- },
- RadialSizeComponents {
- component_count: *to_component_count,
- is_extent_0: *to_is_extent_0,
- value_0: to_value_0,
- is_extent_1: *to_is_extent_1,
- value_1: to_value_1,
- },
- delta,
- )
- .map_or_else(handled_without_value, owned),
+ } = &**radial_size_payload_2;
+ interpolate_radial_size(
+ property_id,
+ RadialSizeComponents {
+ component_count: *from_component_count,
+ is_extent_0: *from_is_extent_0,
+ value_0: from_value_0,
+ is_extent_1: *from_is_extent_1,
+ value_1: from_value_1,
+ },
+ RadialSizeComponents {
+ component_count: *to_component_count,
+ is_extent_0: *to_is_extent_0,
+ value_0: to_value_0,
+ is_extent_1: *to_is_extent_1,
+ value_1: to_value_1,
+ },
+ delta,
+ )
+ .map_or_else(handled_without_value, owned)
+ }
(from_value @ StyleValueData::Keyword { keyword: from }, StyleValueData::Keyword { keyword: to })
if from == to =>
unsafe { handled_borrowed_value(from_value) },
@@ -4610,7 +4666,7 @@ fn interpolate_scalar_value(
else {
return not_handled();
};
- let number = RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Number {
+ let number = RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Number {
value: interpolate_f64(*from, *to, delta, Some((0.0, 1.0))),
}));
owned(StyleValueData::OpacityValue { value: number })
@@ -4627,21 +4683,23 @@ fn interpolate_scalar_value(
let to_normalized_value = normalized_super_ellipse_half_corner(*to);
let interpolated_value =
interpolate_f64(from_normalized_value, to_normalized_value, delta, Some((0.0, 1.0)));
- let parameter = RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Number {
+ let parameter = RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Number {
value: interpolation_value_to_super_ellipse_parameter(interpolated_value),
}));
owned(StyleValueData::Superellipse { parameter })
}
(
- StyleValueData::BackgroundSize {
+ StyleValueData::BackgroundSize(background_size_payload_1),
+ StyleValueData::BackgroundSize(background_size_payload_2),
+ ) => {
+ let BackgroundSizePayload {
size_x: from_x,
size_y: from_y,
- },
- StyleValueData::BackgroundSize {
+ } = &**background_size_payload_1;
+ let BackgroundSizePayload {
size_x: to_x,
size_y: to_y,
- },
- ) => {
+ } = &**background_size_payload_2;
let x = interpolate_scalar_value(property_id, from_x.data(), to_x.data(), delta, range_overrides);
let y = interpolate_scalar_value(property_id, from_y.data(), to_y.data(), delta, range_overrides);
if !x.handled || !y.handled {
@@ -4650,10 +4708,12 @@ fn interpolate_scalar_value(
let (Some(x_value), Some(y_value)) = (x.value, y.value) else {
return handled_without_value();
};
- owned(StyleValueData::BackgroundSize {
- size_x: x_value,
- size_y: y_value,
- })
+ owned(StyleValueData::BackgroundSize(StyleValueBox::new(
+ BackgroundSizePayload {
+ size_x: x_value,
+ size_y: y_value,
+ },
+ )))
}
(StyleValueData::Edge { offset: from, .. }, StyleValueData::Edge { offset: to, .. }) => {
let (Some(from), Some(to)) = (from.optional_data(), to.optional_data()) else {
@@ -4668,16 +4728,15 @@ fn interpolate_scalar_value(
offset,
})
}
- (
- StyleValueData::Position {
+ (StyleValueData::Position(position_payload_1), StyleValueData::Position(position_payload_2)) => {
+ let PositionPayload {
edge_x: from_x,
edge_y: from_y,
- },
- StyleValueData::Position {
+ } = &**position_payload_1;
+ let PositionPayload {
edge_x: to_x,
edge_y: to_y,
- },
- ) => {
+ } = &**position_payload_2;
// https://www.w3.org/TR/css-values-4/#combine-positions
// FIXME: Interpolation of <position> is defined as the independent interpolation of each component (x, y) normalized as an offset from the top left corner as a <length-percentage>.
let x = interpolate_scalar_value(property_id, from_x.data(), to_x.data(), delta, range_overrides);
@@ -4688,25 +4747,24 @@ fn interpolate_scalar_value(
let (Some(x_value), Some(y_value)) = (x.value, y.value) else {
return handled_without_value();
};
- owned(StyleValueData::Position {
+ owned(StyleValueData::Position(StyleValueBox::new(PositionPayload {
edge_x: x_value,
edge_y: y_value,
- })
+ })))
}
- (
- StyleValueData::Rect {
+ (StyleValueData::Rect(rect_payload_1), StyleValueData::Rect(rect_payload_2)) => {
+ let RectPayload {
top: from_top,
right: from_right,
bottom: from_bottom,
left: from_left,
- },
- StyleValueData::Rect {
+ } = &**rect_payload_1;
+ let RectPayload {
top: to_top,
right: to_right,
bottom: to_bottom,
left: to_left,
- },
- ) => {
+ } = &**rect_payload_2;
let combine = |from: &RetainedStyleValueData, to: &RetainedStyleValueData| {
let result = interpolate_scalar_value(property_id, from.data(), to.data(), delta, range_overrides);
if !result.handled {
@@ -4730,12 +4788,12 @@ fn interpolate_scalar_value(
let Some(left) = combine(from_left, to_left)? else {
return Ok(None);
};
- Ok(Some(StyleValueData::Rect {
+ Ok(Some(StyleValueData::Rect(StyleValueBox::new(RectPayload {
top,
right,
bottom,
left,
- }))
+ }))))
})();
match value {
Err(()) => not_handled(),
@@ -4744,17 +4802,20 @@ fn interpolate_scalar_value(
}
}
(
- StyleValueData::BorderRadius {
+ StyleValueData::BorderRadius(border_radius_payload_1),
+ StyleValueData::BorderRadius(border_radius_payload_2),
+ ) => {
+ let BorderRadiusPayload {
horizontal_radius: from_horizontal,
vertical_radius: from_vertical,
..
- },
- StyleValueData::BorderRadius {
+ } = &**border_radius_payload_1;
+ let BorderRadiusPayload {
horizontal_radius: to_horizontal,
vertical_radius: to_vertical,
..
- },
- ) => {
+ } = &**border_radius_payload_2;
+
let horizontal = interpolate_scalar_value(
property_id,
from_horizontal.data(),
@@ -4781,26 +4842,28 @@ fn interpolate_scalar_value(
let Some(vertical) = vertical.value else {
return handled_without_value();
};
- owned(StyleValueData::BorderRadius {
+ owned(StyleValueData::BorderRadius(StyleValueBox::new(BorderRadiusPayload {
is_elliptical: !radius_components_equal(horizontal.data(), vertical.data()),
horizontal_radius: horizontal,
vertical_radius: vertical,
- })
+ })))
}
(
- StyleValueData::BorderRadiusRect {
+ StyleValueData::BorderRadiusRect(border_radius_rect_payload_1),
+ StyleValueData::BorderRadiusRect(border_radius_rect_payload_2),
+ ) => {
+ let BorderRadiusRectPayload {
top_left: from_top_left,
top_right: from_top_right,
bottom_right: from_bottom_right,
bottom_left: from_bottom_left,
- },
- StyleValueData::BorderRadiusRect {
+ } = &**border_radius_rect_payload_1;
+ let BorderRadiusRectPayload {
top_left: to_top_left,
top_right: to_top_right,
bottom_right: to_bottom_right,
bottom_left: to_bottom_left,
- },
- ) => {
+ } = &**border_radius_rect_payload_2;
// https://drafts.csswg.org/web-animations-1/#animating-properties
// Corresponding individual components of the computed values are combined (interpolated, added, or accumulated) using the indicated procedure for that value type (see CSS Values 4 § 3 Combining Values: Interpolation, Addition, and Accumulation).
// If the number of components or the types of corresponding components do not match, or if any component value uses discrete animation and the two corresponding values do not match, then the property values combine as discrete.
@@ -4828,12 +4891,14 @@ fn interpolate_scalar_value(
let Some(bottom_left) = combine(from_bottom_left, to_bottom_left)? else {
return Ok(None);
};
- Ok(Some(StyleValueData::BorderRadiusRect {
- top_left,
- top_right,
- bottom_right,
- bottom_left,
- }))
+ Ok(Some(StyleValueData::BorderRadiusRect(StyleValueBox::new(
+ BorderRadiusRectPayload {
+ top_left,
+ top_right,
+ bottom_right,
+ bottom_left,
+ },
+ ))))
})();
match value {
Err(()) => not_handled(),
@@ -4842,21 +4907,23 @@ fn interpolate_scalar_value(
}
}
(
- StyleValueData::BorderImageSlice {
+ StyleValueData::BorderImageSlice(border_image_slice_payload_1),
+ StyleValueData::BorderImageSlice(border_image_slice_payload_2),
+ ) => {
+ let BorderImageSlicePayload {
top: from_top,
right: from_right,
bottom: from_bottom,
left: from_left,
fill: from_fill,
- },
- StyleValueData::BorderImageSlice {
+ } = &**border_image_slice_payload_1;
+ let BorderImageSlicePayload {
top: to_top,
right: to_right,
bottom: to_bottom,
left: to_left,
fill: to_fill,
- },
- ) => {
+ } = &**border_image_slice_payload_2;
// https://drafts.csswg.org/web-animations-1/#animating-properties
// Corresponding individual components of the computed values are combined (interpolated, added, or accumulated) using the indicated procedure for that value type (see CSS Values 4 § 3 Combining Values: Interpolation, Addition, and Accumulation).
// If the number of components or the types of corresponding components do not match, or if any component value uses discrete animation and the two corresponding values do not match, then the property values combine as discrete.
@@ -4886,13 +4953,15 @@ fn interpolate_scalar_value(
let Some(left) = combine(from_left, to_left)? else {
return Ok(None);
};
- Ok(Some(StyleValueData::BorderImageSlice {
- top,
- right,
- bottom,
- left,
- fill: *from_fill,
- }))
+ Ok(Some(StyleValueData::BorderImageSlice(StyleValueBox::new(
+ BorderImageSlicePayload {
+ top,
+ right,
+ bottom,
+ left,
+ fill: *from_fill,
+ },
+ ))))
})();
match value {
Err(()) => not_handled(),
@@ -4901,18 +4970,21 @@ fn interpolate_scalar_value(
}
}
(
- StyleValueData::OpenTypeTagged {
+ StyleValueData::OpenTypeTagged(open_type_tagged_payload_1),
+ StyleValueData::OpenTypeTagged(open_type_tagged_payload_2),
+ ) => {
+ let OpenTypeTaggedPayload {
tag_name: from_tag,
packed_tag: from_packed_tag,
value: from_value,
..
- },
- StyleValueData::OpenTypeTagged {
+ } = &**open_type_tagged_payload_1;
+ let OpenTypeTaggedPayload {
tag_name: to_tag,
value: to_value,
..
- },
- ) => {
+ } = &**open_type_tagged_payload_2;
+
// https://drafts.csswg.org/web-animations-1/#animating-properties
// Corresponding individual components of the computed values are combined (interpolated, added, or accumulated) using the indicated procedure for that value type (see CSS Values 4 § 3 Combining Values: Interpolation, Addition, and Accumulation).
// If the number of components or the types of corresponding components do not match, or if any component value uses discrete animation and the two corresponding values do not match, then the property values combine as discrete.
@@ -4927,23 +4999,24 @@ fn interpolate_scalar_value(
let Some(retained_value) = value.value else {
return handled_without_value();
};
- owned(StyleValueData::OpenTypeTagged {
- mode: OPEN_TYPE_MODE_FONT_VARIATION_SETTINGS,
- tag_name: from_tag.clone(),
- packed_tag: *from_packed_tag,
- value: retained_value,
- })
+ owned(StyleValueData::OpenTypeTagged(StyleValueBox::new(
+ OpenTypeTaggedPayload {
+ mode: OPEN_TYPE_MODE_FONT_VARIATION_SETTINGS,
+ tag_name: from_tag.clone(),
+ packed_tag: *from_packed_tag,
+ value: retained_value,
+ },
+ )))
}
- (
- StyleValueData::Function {
+ (StyleValueData::Function(function_payload_1), StyleValueData::Function(function_payload_2)) => {
+ let FunctionPayload {
name: from_name,
value: from_value,
- },
- StyleValueData::Function {
+ } = &**function_payload_1;
+ let FunctionPayload {
name: to_name,
value: to_value,
- },
- ) => {
+ } = &**function_payload_2;
// https://drafts.csswg.org/web-animations-1/#animating-properties
// Corresponding individual components of the computed values are combined (interpolated, added, or accumulated) using the indicated procedure for that value type (see CSS Values 4 § 3 Combining Values: Interpolation, Addition, and Accumulation).
// If the number of components or the types of corresponding components do not match, or if any component value uses discrete animation and the two corresponding values do not match, then the property values combine as discrete.
@@ -4958,10 +5031,10 @@ fn interpolate_scalar_value(
let Some(retained_value) = value.value else {
return handled_without_value();
};
- owned(StyleValueData::Function {
+ owned(StyleValueData::Function(StyleValueBox::new(FunctionPayload {
name: from_name.clone(),
value: retained_value,
- })
+ })))
}
(
StyleValueData::TextIndent {
@@ -4991,16 +5064,15 @@ fn interpolate_scalar_value(
each_line: *from_each_line,
})
}
- (
- StyleValueData::Ratio {
+ (StyleValueData::Ratio(ratio_payload_1), StyleValueData::Ratio(ratio_payload_2)) => {
+ let RatioPayload {
numerator: from_numerator,
denominator: from_denominator,
- },
- StyleValueData::Ratio {
+ } = &**ratio_payload_1;
+ let RatioPayload {
numerator: to_numerator,
denominator: to_denominator,
- },
- ) => {
+ } = &**ratio_payload_2;
let (
StyleValueData::Number { value: from_numerator },
StyleValueData::Number {
@@ -5046,10 +5118,12 @@ fn interpolate_scalar_value(
accepted_range(property_id, VALUE_TYPE_RATIO, range_overrides),
)
.exp();
- owned(StyleValueData::Ratio {
- numerator: RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Number { value })),
- denominator: RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Number { value: 1.0 })),
- })
+ owned(StyleValueData::Ratio(StyleValueBox::new(RatioPayload {
+ numerator: RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Number { value })),
+ denominator: RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Number {
+ value: 1.0,
+ })),
+ })))
}
(
StyleValueData::ValueList {
@@ -5238,40 +5312,42 @@ fn interpolate_rotate_3d_with_phases(
let mut arguments = Vec::with_capacity(4);
for value in result_axis {
- let argument = RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Number { value }));
+ let argument = RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Number { value }));
arguments.push(argument);
}
- let angle = RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Angle {
+ let angle = RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Angle {
value: result_angle,
unit: 0,
}));
arguments.push(angle);
- Some(StyleValueData::Transformation {
- property,
- transform_function,
- values: RetainedStyleValueDataList::from_retained_values(arguments),
- matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
- })
+ Some(StyleValueData::Transformation(StyleValueBox::new(
+ TransformationPayload {
+ property,
+ transform_function,
+ values: RetainedStyleValueDataList::from_retained_values(arguments),
+ matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
+ },
+ )))
}
fn retained_number(value: f64) -> RetainedStyleValueData {
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Number { value }))
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Number { value }))
}
fn retained_zero_px() -> RetainedStyleValueData {
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Length {
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Length {
value: 0.0,
unit: crate::css::style_compute::px_length_unit(),
}))
}
fn retained_length(value: f64, unit: u8) -> RetainedStyleValueData {
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Length { value, unit }))
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Length { value, unit }))
}
fn retained_none_keyword() -> RetainedStyleValueData {
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Keyword {
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Keyword {
keyword: crate::css::style_compute::none_keyword(),
}))
}
@@ -5518,14 +5594,15 @@ fn identity_transformation(property: u16, function: u8) -> Option<RetainedStyleV
| TRANSFORM_FUNCTION_SKEW
| TRANSFORM_FUNCTION_SKEW_X
| TRANSFORM_FUNCTION_SKEW_Y => {
- let angle = RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Angle { value: 0.0, unit: 0 }));
+ let angle =
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Angle { value: 0.0, unit: 0 }));
vec![angle]
}
TRANSFORM_FUNCTION_ROTATE_3D => vec![
retained_number(1.0),
retained_number(1.0),
retained_number(1.0),
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Angle { value: 0.0, unit: 0 })),
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Angle { value: 0.0, unit: 0 })),
],
TRANSFORM_FUNCTION_TRANSLATE
| TRANSFORM_FUNCTION_TRANSLATE_X
@@ -5539,12 +5616,14 @@ fn identity_transformation(property: u16, function: u8) -> Option<RetainedStyleV
TRANSFORM_FUNCTION_SCALE_3D => vec![retained_number(1.0), retained_number(1.0), retained_number(1.0)],
_ => return None,
};
- let transformation = RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Transformation {
- property,
- transform_function: function,
- values: RetainedStyleValueDataList::from_retained_values(arguments),
- matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
- }));
+ let transformation = RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Transformation(
+ StyleValueBox::new(TransformationPayload {
+ property,
+ transform_function: function,
+ values: RetainedStyleValueDataList::from_retained_values(arguments),
+ matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
+ }),
+ )));
Some(transformation)
}
@@ -5994,12 +6073,12 @@ fn matrix_transformation(property: u16, matrix: Matrix4) -> StyleValueData {
let arguments = (0..16)
.map(|index| retained_number(matrix[index % 4][index / 4]))
.collect();
- StyleValueData::Transformation {
+ StyleValueData::Transformation(StyleValueBox::new(TransformationPayload {
property,
transform_function: TRANSFORM_FUNCTION_MATRIX_3D,
values: RetainedStyleValueDataList::from_retained_values(arguments),
matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
- }
+ }))
}
enum TransformMatrixInterpolationError {
@@ -6017,7 +6096,7 @@ fn interpolate_transform_matrix_suffix(
let from = post_multiply_transformations(context, from).ok_or(TransformMatrixInterpolationError::NotConvertible)?;
let to = post_multiply_transformations(context, to).ok_or(TransformMatrixInterpolationError::NotConvertible)?;
let matrix = interpolate_matrices(from, to, delta).ok_or(TransformMatrixInterpolationError::NonInvertible)?;
- let transformation = RetainedStyleValueData::from_arc(Arc::new(matrix_transformation(property, matrix)));
+ let transformation = RetainedStyleValueData::from_arc(StyleValueArc::new(matrix_transformation(property, matrix)));
Ok(transformation)
}
@@ -6037,14 +6116,14 @@ fn pad_transform_lists(
(to_values, &*from_values)
};
for transformation in &longer[shorter.len()..] {
- let StyleValueData::Transformation {
+ let StyleValueData::Transformation(transformation_payload) = transformation.data() else {
+ return None;
+ };
+ let TransformationPayload {
property,
transform_function,
..
- } = transformation.data()
- else {
- return None;
- };
+ } = &**transformation_payload;
shorter.push(identity_transformation(*property, *transform_function)?);
}
}
@@ -6114,21 +6193,24 @@ fn interpolate_transform_list_impl(
let mut transformations = Vec::with_capacity(from_values.len());
for (index, (from, to)) in from_values.iter().zip(&to_values).enumerate() {
let (
- StyleValueData::Transformation {
- property: from_property,
- transform_function: from_function,
- values: from_arguments,
- ..
- },
- StyleValueData::Transformation {
- transform_function: to_function,
- values: to_arguments,
- ..
- },
+ StyleValueData::Transformation(transformation_payload_1),
+ StyleValueData::Transformation(transformation_payload_2),
) = (from.data(), to.data())
else {
return None;
};
+ let TransformationPayload {
+ property: from_property,
+ transform_function: from_function,
+ values: from_arguments,
+ ..
+ } = &**transformation_payload_1;
+ let TransformationPayload {
+ transform_function: to_function,
+ values: to_arguments,
+ ..
+ } = &**transformation_payload_2;
+
if from_function == to_function && *from_function == TRANSFORM_FUNCTION_PERSPECTIVE {
let ([from_argument], [to_argument]) = (from_arguments.as_slice(), to_arguments.as_slice()) else {
return None;
@@ -6151,12 +6233,14 @@ fn interpolate_transform_list_impl(
// and decomposing two matrices.
let reciprocal_depth = interpolate_f64(from_reciprocal_depth, to_reciprocal_depth, delta, None);
let argument = perspective_from_reciprocal_depth(reciprocal_depth, from_unit.or(to_unit));
- let transformation = RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Transformation {
- property: *from_property,
- transform_function: *from_function,
- values: RetainedStyleValueDataList::from_retained_values(vec![argument]),
- matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
- }));
+ let transformation = RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Transformation(
+ StyleValueBox::new(TransformationPayload {
+ property: *from_property,
+ transform_function: *from_function,
+ values: RetainedStyleValueDataList::from_retained_values(vec![argument]),
+ matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
+ }),
+ )));
transformations.push(transformation);
continue;
}
@@ -6227,7 +6311,7 @@ fn interpolate_transform_list_impl(
delta,
effective_rotation_radians(from.data()).zip(effective_rotation_radians(to.data())),
)?;
- let transformation = RetainedStyleValueData::from_arc(Arc::new(transformation));
+ let transformation = RetainedStyleValueData::from_arc(StyleValueArc::new(transformation));
transformations.push(transformation);
continue;
}
@@ -6248,12 +6332,14 @@ fn interpolate_transform_list_impl(
}
arguments.push(interpolate_scalar_value(property_id, from.data(), to.data(), delta, &[]).into_value()?);
}
- let transformation = RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Transformation {
- property: *from_property,
- transform_function,
- values: RetainedStyleValueDataList::from_retained_values(arguments),
- matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
- }));
+ let transformation = RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Transformation(
+ StyleValueBox::new(TransformationPayload {
+ property: *from_property,
+ transform_function,
+ values: RetainedStyleValueDataList::from_retained_values(arguments),
+ matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
+ }),
+ )));
transformations.push(transformation);
}
@@ -6297,15 +6383,15 @@ fn post_multiply_transformations(
) -> Option<Matrix4> {
let mut result = identity_matrix();
for transformation in transformations {
- let StyleValueData::Transformation {
+ let StyleValueData::Transformation(transformation_payload) = transformation.data() else {
+ return None;
+ };
+ let TransformationPayload {
transform_function,
values,
matrix_values,
..
- } = transformation.data()
- else {
- return None;
- };
+ } = &**transformation_payload;
result = multiply_matrices(
result,
transformation_to_matrix(
@@ -6406,10 +6492,9 @@ fn accumulate_rotate_3d(
let (animated_axis, animated_angle) = decode(animated)?;
let rotation = |axis: [f64; 3], angle: f64| {
let mut arguments: Vec<_> = axis.into_iter().map(retained_number).collect();
- arguments.push(RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Angle {
- value: angle,
- unit: 0,
- })));
+ arguments.push(RetainedStyleValueData::from_arc(StyleValueArc::new(
+ StyleValueData::Angle { value: angle, unit: 0 },
+ )));
arguments
};
@@ -6468,7 +6553,7 @@ fn perspective_from_reciprocal_depth(reciprocal_depth: f64, unit: Option<u8>) ->
if reciprocal_depth <= 0.0 {
return retained_none_keyword();
}
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Length {
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Length {
value: 1.0 / reciprocal_depth,
unit: unit.unwrap_or_else(crate::css::style_compute::px_length_unit),
}))
@@ -6486,7 +6571,7 @@ fn accumulate_transform_functions(
if !has_transform_matrix_values(underlying) && !has_transform_matrix_values(animated) {
return Some(value);
}
- Some(RetainedStyleValueData::from_arc(Arc::new(
+ Some(RetainedStyleValueData::from_arc(StyleValueArc::new(
preserve_transform_matrix_values(value.data().clone(), &[underlying, animated]),
)))
}
@@ -6498,27 +6583,32 @@ fn accumulate_transform_functions_impl(
animated: &StyleValueData,
) -> Option<RetainedStyleValueData> {
let (
- StyleValueData::Transformation {
- transform_function: underlying_function,
- values: underlying_arguments,
- ..
- },
- StyleValueData::Transformation {
- transform_function: animated_function,
- values: animated_arguments,
- ..
- },
+ StyleValueData::Transformation(transformation_payload_1),
+ StyleValueData::Transformation(transformation_payload_2),
) = (underlying, animated)
else {
return None;
};
+ let TransformationPayload {
+ transform_function: underlying_function,
+ values: underlying_arguments,
+ ..
+ } = &**transformation_payload_1;
+ let TransformationPayload {
+ transform_function: animated_function,
+ values: animated_arguments,
+ ..
+ } = &**transformation_payload_2;
+
let transformation = |transform_function: u8, arguments: Vec<RetainedStyleValueData>| {
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Transformation {
- property,
- transform_function,
- values: RetainedStyleValueDataList::from_retained_values(arguments),
- matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
- }))
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Transformation(StyleValueBox::new(
+ TransformationPayload {
+ property,
+ transform_function,
+ values: RetainedStyleValueDataList::from_retained_values(arguments),
+ matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
+ },
+ ))))
};
if underlying_function == animated_function && *underlying_function == TRANSFORM_FUNCTION_PERSPECTIVE {
@@ -6638,9 +6728,10 @@ fn composite_transform_list(
for (index, (underlying_value, animated_value)) in
underlying_values.iter().zip(&animated_values).enumerate()
{
- let StyleValueData::Transformation { property, .. } = underlying_value.data() else {
+ let StyleValueData::Transformation(transformation_payload) = underlying_value.data() else {
return None;
};
+ let TransformationPayload { property, .. } = &**transformation_payload;
if let Some(value) = accumulate_transform_functions(
Some(context),
*property,
@@ -6653,10 +6744,10 @@ fn composite_transform_list(
let is_matrix_pair = matches!(
(underlying_value.data(), animated_value.data()),
(
- StyleValueData::Transformation { transform_function: underlying_function, .. },
- StyleValueData::Transformation { transform_function: animated_function, .. },
- ) if underlying_function == animated_function
- && matches!(*underlying_function, TRANSFORM_FUNCTION_MATRIX | TRANSFORM_FUNCTION_MATRIX_3D)
+ StyleValueData::Transformation(underlying_function),
+ StyleValueData::Transformation(animated_function),
+ ) if underlying_function.transform_function == animated_function.transform_function
+ && matches!(underlying_function.transform_function, TRANSFORM_FUNCTION_MATRIX | TRANSFORM_FUNCTION_MATRIX_3D)
);
let end = if is_matrix_pair {
index + 1
@@ -6667,9 +6758,9 @@ fn composite_transform_list(
let animated_matrix = post_multiply_transformations(Some(context), &animated_values[index..end])?;
// NB: Accumulating a non-invertible matrix falls back to replacing the underlying value.
let matrix = accumulate_matrices(underlying_matrix, animated_matrix)?;
- values.push(RetainedStyleValueData::from_arc(Arc::new(matrix_transformation(
- *property, matrix,
- ))));
+ values.push(RetainedStyleValueData::from_arc(StyleValueArc::new(
+ matrix_transformation(*property, matrix),
+ )));
if !is_matrix_pair {
break;
}
@@ -6680,20 +6771,22 @@ fn composite_transform_list(
}
fn retained_legacy_color(red: u8, green: u8, blue: u8, alpha: u8) -> RetainedStyleValueData {
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::ColorFunction {
- color_base: ColorBase {
- has_color_type: true,
- color_type: COLOR_TYPE_RGB,
- color_syntax: COLOR_SYNTAX_LEGACY,
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::ColorFunction(StyleValueBox::new(
+ ColorFunctionPayload {
+ color_base: ColorBase {
+ has_color_type: true,
+ color_type: COLOR_TYPE_RGB,
+ color_syntax: COLOR_SYNTAX_LEGACY,
+ },
+ channel_0: retained_number(red as f64),
+ channel_1: retained_number(green as f64),
+ channel_2: retained_number(blue as f64),
+ alpha: retained_number(alpha as f64 / 255.0),
+ has_name: false,
+ name: empty_retained_fly_string(),
+ origin_color: empty_retained_style_value(),
},
- channel_0: retained_number(red as f64),
- channel_1: retained_number(green as f64),
- channel_2: retained_number(blue as f64),
- alpha: retained_number(alpha as f64 / 255.0),
- has_name: false,
- name: empty_retained_fly_string(),
- origin_color: empty_retained_style_value(),
- }))
+ ))))
}
fn retained_transparent_legacy_color() -> RetainedStyleValueData {
@@ -6826,41 +6919,45 @@ fn resolve_root_animation_color<'a>(
}
let to_byte = |value: f32| (value * 255.0).round().clamp(0.0, 255.0) as u8;
let alpha = to_byte(components[3]);
- Some(RootAnimationColor::Owned(StyleValueData::ColorFunction {
- color_base: ColorBase {
- has_color_type: true,
- color_type: COLOR_TYPE_RGB,
- color_syntax: COLOR_SYNTAX_LEGACY,
- },
- channel_0: retained_number(to_byte(components[0]) as f64),
- channel_1: retained_number(to_byte(components[1]) as f64),
- channel_2: retained_number(to_byte(components[2]) as f64),
- alpha: retained_number(alpha as f64 / 255.0),
- has_name: false,
- name: empty_retained_fly_string(),
- origin_color: empty_retained_style_value(),
- }))
+ Some(RootAnimationColor::Owned(StyleValueData::ColorFunction(
+ StyleValueBox::new(ColorFunctionPayload {
+ color_base: ColorBase {
+ has_color_type: true,
+ color_type: COLOR_TYPE_RGB,
+ color_syntax: COLOR_SYNTAX_LEGACY,
+ },
+ channel_0: retained_number(to_byte(components[0]) as f64),
+ channel_1: retained_number(to_byte(components[1]) as f64),
+ channel_2: retained_number(to_byte(components[2]) as f64),
+ alpha: retained_number(alpha as f64 / 255.0),
+ has_name: false,
+ name: empty_retained_fly_string(),
+ origin_color: empty_retained_style_value(),
+ }),
+ )))
}
_ => None,
}
}
fn blank_shadow(other: &StyleValueData) -> Option<RetainedStyleValueData> {
- let StyleValueData::Shadow {
- shadow_type, placement, ..
- } = other
- else {
+ let StyleValueData::Shadow(shadow_payload) = other else {
return None;
};
- let value = RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Shadow {
- shadow_type: *shadow_type,
- color: retained_transparent_legacy_color(),
- offset_x: retained_zero_px(),
- offset_y: retained_zero_px(),
- blur_radius: retained_zero_px(),
- spread_distance: retained_zero_px(),
- placement: *placement,
- }));
+ let ShadowPayload {
+ shadow_type, placement, ..
+ } = &**shadow_payload;
+ let value = RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Shadow(StyleValueBox::new(
+ ShadowPayload {
+ shadow_type: *shadow_type,
+ color: retained_transparent_legacy_color(),
+ offset_x: retained_zero_px(),
+ offset_y: retained_zero_px(),
+ blur_radius: retained_zero_px(),
+ spread_distance: retained_zero_px(),
+ placement: *placement,
+ },
+ ))));
Some(value)
}
@@ -6871,29 +6968,27 @@ fn interpolate_shadow(
to: &StyleValueData,
delta: f32,
) -> Option<StyleValueData> {
- let (
- StyleValueData::Shadow {
- shadow_type: from_shadow_type,
- color: from_color,
- offset_x: from_offset_x,
- offset_y: from_offset_y,
- blur_radius: from_blur_radius,
- spread_distance: from_spread_distance,
- placement: from_placement,
- },
- StyleValueData::Shadow {
- shadow_type: to_shadow_type,
- color: to_color,
- offset_x: to_offset_x,
- offset_y: to_offset_y,
- blur_radius: to_blur_radius,
- spread_distance: to_spread_distance,
- placement: to_placement,
- },
- ) = (from, to)
- else {
+ let (StyleValueData::Shadow(shadow_payload_1), StyleValueData::Shadow(shadow_payload_2)) = (from, to) else {
return None;
};
+ let ShadowPayload {
+ shadow_type: from_shadow_type,
+ color: from_color,
+ offset_x: from_offset_x,
+ offset_y: from_offset_y,
+ blur_radius: from_blur_radius,
+ spread_distance: from_spread_distance,
+ placement: from_placement,
+ } = &**shadow_payload_1;
+ let ShadowPayload {
+ shadow_type: to_shadow_type,
+ color: to_color,
+ offset_x: to_offset_x,
+ offset_y: to_offset_y,
+ blur_radius: to_blur_radius,
+ spread_distance: to_spread_distance,
+ placement: to_placement,
+ } = &**shadow_payload_2;
// https://drafts.csswg.org/web-animations-1/#animating-shadow-lists
// However, if both input shadows are inset or both input shadows are not inset, then the interpolated shadow must
// match the input shadows in that regard. If any pair of input shadows has one inset and the other not inset, the
@@ -6954,7 +7049,7 @@ fn interpolate_shadow(
)
.or_else(|| interpolate(from_spread_distance, to_spread_distance, &[]))?;
- Some(StyleValueData::Shadow {
+ Some(StyleValueData::Shadow(StyleValueBox::new(ShadowPayload {
shadow_type: *from_shadow_type,
color,
offset_x,
@@ -6962,7 +7057,7 @@ fn interpolate_shadow(
blur_radius,
spread_distance,
placement: *from_placement,
- })
+ })))
}
fn shadow_list_entries(value: &StyleValueData) -> Option<(Vec<RetainedStyleValueData>, u8, bool)> {
@@ -7014,29 +7109,28 @@ fn accumulate_shadow(
underlying: &StyleValueData,
animated: &StyleValueData,
) -> Option<StyleValueData> {
- let (
- StyleValueData::Shadow {
- shadow_type: underlying_shadow_type,
- color: underlying_color,
- offset_x: underlying_offset_x,
- offset_y: underlying_offset_y,
- blur_radius: underlying_blur_radius,
- spread_distance: underlying_spread_distance,
- placement: underlying_placement,
- },
- StyleValueData::Shadow {
- shadow_type: animated_shadow_type,
- color: animated_color,
- offset_x: animated_offset_x,
- offset_y: animated_offset_y,
- blur_radius: animated_blur_radius,
- spread_distance: animated_spread_distance,
- placement: animated_placement,
- },
- ) = (underlying, animated)
+ let (StyleValueData::Shadow(shadow_payload_1), StyleValueData::Shadow(shadow_payload_2)) = (underlying, animated)
else {
return None;
};
+ let ShadowPayload {
+ shadow_type: underlying_shadow_type,
+ color: underlying_color,
+ offset_x: underlying_offset_x,
+ offset_y: underlying_offset_y,
+ blur_radius: underlying_blur_radius,
+ spread_distance: underlying_spread_distance,
+ placement: underlying_placement,
+ } = &**shadow_payload_1;
+ let ShadowPayload {
+ shadow_type: animated_shadow_type,
+ color: animated_color,
+ offset_x: animated_offset_x,
+ offset_y: animated_offset_y,
+ blur_radius: animated_blur_radius,
+ spread_distance: animated_spread_distance,
+ placement: animated_placement,
+ } = &**shadow_payload_2;
if underlying_shadow_type != animated_shadow_type || underlying_placement != animated_placement {
return None;
}
@@ -7060,7 +7154,7 @@ fn accumulate_shadow(
)
.into_value()?;
- Some(StyleValueData::Shadow {
+ Some(StyleValueData::Shadow(StyleValueBox::new(ShadowPayload {
shadow_type: *underlying_shadow_type,
color,
offset_x: add_lengths(underlying_offset_x, animated_offset_x)?,
@@ -7074,7 +7168,7 @@ fn accumulate_shadow(
empty_retained_style_value()
},
placement: *underlying_placement,
- })
+ })))
}
fn composite_shadow_list(
@@ -7118,7 +7212,7 @@ fn composite_shadow_list(
let Some(shadow) = accumulate_shadow(context, underlying_shadow.data(), animated_shadow.data()) else {
return handled_without_value();
};
- shadows.push(RetainedStyleValueData::from_arc(Arc::new(shadow)));
+ shadows.push(RetainedStyleValueData::from_arc(StyleValueArc::new(shadow)));
}
shadows
}
@@ -7161,7 +7255,7 @@ fn interpolate_shadow_list(
let Some(shadow) = interpolate_shadow(context, property_id, from_shadow.data(), to_shadow.data(), delta) else {
return discrete_value(context, from, to, delta);
};
- let shadow = RetainedStyleValueData::from_arc(Arc::new(shadow));
+ let shadow = RetainedStyleValueData::from_arc(StyleValueArc::new(shadow));
shadows.push(shadow);
}
@@ -7178,7 +7272,7 @@ fn interpolate_shadow_list(
}
fn retained_filter(kind: u8, color_operation: u8, value: RetainedStyleValueData) -> RetainedStyleValueData {
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Filter {
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Filter {
kind,
color_operation,
value,
@@ -7200,28 +7294,30 @@ fn initial_filter_value(
let initial = match *kind {
FILTER_KIND_BLUR => retained_zero_px(),
FILTER_KIND_DROP_SHADOW => {
- let StyleValueData::Shadow {
- shadow_type, placement, ..
- } = value.data()
- else {
+ let StyleValueData::Shadow(shadow_payload) = value.data() else {
return None;
};
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Shadow {
- shadow_type: *shadow_type,
- color: if use_transparent_drop_shadow_color {
- retained_transparent_legacy_color()
- } else {
- empty_retained_style_value()
+ let ShadowPayload {
+ shadow_type, placement, ..
+ } = &**shadow_payload;
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Shadow(StyleValueBox::new(
+ ShadowPayload {
+ shadow_type: *shadow_type,
+ color: if use_transparent_drop_shadow_color {
+ retained_transparent_legacy_color()
+ } else {
+ empty_retained_style_value()
+ },
+ offset_x: retained_zero_px(),
+ offset_y: retained_zero_px(),
+ blur_radius: retained_zero_px(),
+ spread_distance: empty_retained_style_value(),
+ placement: *placement,
},
- offset_x: retained_zero_px(),
- offset_y: retained_zero_px(),
- blur_radius: retained_zero_px(),
- spread_distance: empty_retained_style_value(),
- placement: *placement,
- }))
+ ))))
}
FILTER_KIND_HUE_ROTATE => {
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Angle { value: 0.0, unit: 0 }))
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Angle { value: 0.0, unit: 0 }))
}
FILTER_KIND_COLOR => retained_number(if matches!(*color_operation, 2 | 3 | 6) {
0.0
@@ -7281,34 +7377,38 @@ fn interpolate_filter_function(
FILTER_KIND_DROP_SHADOW => {
let mut shadow = interpolate_shadow(context, property_id, from_value.data(), to_value.data(), delta)?;
let (
- StyleValueData::Shadow {
- blur_radius: from_blur_radius,
- ..
- },
- StyleValueData::Shadow {
- blur_radius: to_blur_radius,
- ..
- },
- StyleValueData::Shadow {
- blur_radius,
- spread_distance,
- ..
- },
+ StyleValueData::Shadow(shadow_payload_1),
+ StyleValueData::Shadow(shadow_payload_2),
+ StyleValueData::Shadow(shadow_payload_3),
) = (from_value.data(), to_value.data(), &mut shadow)
else {
return None;
};
+ let ShadowPayload {
+ blur_radius: from_blur_radius,
+ ..
+ } = &**shadow_payload_1;
+ let ShadowPayload {
+ blur_radius: to_blur_radius,
+ ..
+ } = &**shadow_payload_2;
+ let ShadowPayload {
+ blur_radius,
+ spread_distance,
+ ..
+ } = &mut **shadow_payload_3;
+
let selected_blur_radius = if delta >= 0.5 { to_blur_radius } else { from_blur_radius };
if selected_blur_radius.optional_data().is_none() {
*blur_radius = empty_retained_style_value();
}
*spread_distance = empty_retained_style_value();
- RetainedStyleValueData::from_arc(Arc::new(shadow))
+ RetainedStyleValueData::from_arc(StyleValueArc::new(shadow))
}
FILTER_KIND_HUE_ROTATE => {
let from = resolve_animation_angle(context, from_value.data())?;
let to = resolve_animation_angle(context, to_value.data())?;
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Angle {
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Angle {
value: interpolate_f64(from, to, delta, None),
unit: 0,
}))
@@ -7364,7 +7464,7 @@ fn accumulate_filter_function(
+ resolve_animation_length(Some(context), animated_value.data())?,
crate::css::style_compute::px_length_unit(),
),
- FILTER_KIND_HUE_ROTATE => RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Angle {
+ FILTER_KIND_HUE_ROTATE => RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Angle {
value: resolve_animation_angle(Some(context), underlying_value.data())?
+ resolve_animation_angle(Some(context), animated_value.data())?,
unit: 0,
@@ -7379,27 +7479,28 @@ fn accumulate_filter_function(
})
}
FILTER_KIND_DROP_SHADOW => {
- let (
- StyleValueData::Shadow {
- shadow_type,
- color: underlying_color,
- offset_x: underlying_offset_x,
- offset_y: underlying_offset_y,
- blur_radius: underlying_blur_radius,
- placement,
- ..
- },
- StyleValueData::Shadow {
- color: animated_color,
- offset_x: animated_offset_x,
- offset_y: animated_offset_y,
- blur_radius: animated_blur_radius,
- ..
- },
- ) = (underlying_value.data(), animated_value.data())
+ let (StyleValueData::Shadow(shadow_payload), StyleValueData::Shadow(animated_shadow)) =
+ (underlying_value.data(), animated_value.data())
else {
return None;
};
+ let ShadowPayload {
+ color: animated_color,
+ offset_x: animated_offset_x,
+ offset_y: animated_offset_y,
+ blur_radius: animated_blur_radius,
+ ..
+ } = &**animated_shadow;
+
+ let ShadowPayload {
+ shadow_type,
+ color: underlying_color,
+ offset_x: underlying_offset_x,
+ offset_y: underlying_offset_y,
+ blur_radius: underlying_blur_radius,
+ placement,
+ ..
+ } = &**shadow_payload;
let add_lengths = |underlying: &RetainedStyleValueData, animated: &RetainedStyleValueData| {
Some(retained_length(
resolve_animation_length(Some(context), underlying.data())?
@@ -7444,15 +7545,17 @@ fn accumulate_filter_function(
add_color_component(underlying_color[2], animated_color[2]),
add_color_component(underlying_color[3], animated_color[3]),
);
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Shadow {
- shadow_type: *shadow_type,
- color,
- offset_x,
- offset_y,
- blur_radius,
- spread_distance: empty_retained_style_value(),
- placement: *placement,
- }))
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Shadow(StyleValueBox::new(
+ ShadowPayload {
+ shadow_type: *shadow_type,
+ color,
+ offset_x,
+ offset_y,
+ blur_radius,
+ spread_distance: empty_retained_style_value(),
+ placement: *placement,
+ },
+ ))))
}
_ => return None,
};
@@ -7684,7 +7787,7 @@ fn expand_four_sides(value: &StyleValueData) -> Option<[RetainedStyleValueData;
} => values.as_slice(),
StyleValueData::ValueList { .. } => return None,
_ => {
- let side = RetainedStyleValueData::from_arc(Arc::new(value.clone()));
+ let side = RetainedStyleValueData::from_arc(StyleValueArc::new(value.clone()));
return Some([side.clone(), side.clone(), side.clone(), side]);
}
};
@@ -7759,27 +7862,31 @@ fn combine_scrollbar_color(
// Computed value: specified keyword or two computed colors
// Animation type: by computed value
let (
- StyleValueData::ScrollbarColor {
- thumb_color: from_thumb_color,
- track_color: from_track_color,
- },
- StyleValueData::ScrollbarColor {
- thumb_color: to_thumb_color,
- track_color: to_track_color,
- },
+ StyleValueData::ScrollbarColor(scrollbar_color_payload_1),
+ StyleValueData::ScrollbarColor(scrollbar_color_payload_2),
) = (from, to)
else {
return None;
};
+ let ScrollbarColorPayload {
+ thumb_color: from_thumb_color,
+ track_color: from_track_color,
+ } = &**scrollbar_color_payload_1;
+ let ScrollbarColorPayload {
+ thumb_color: to_thumb_color,
+ track_color: to_track_color,
+ } = &**scrollbar_color_payload_2;
let combine_colors = |from: &RetainedStyleValueData, to: &RetainedStyleValueData| {
let from = resolve_animation_color(context, from)?;
let to = resolve_animation_color(context, to)?;
combine(from.data(), to.data()).into_value()
};
- Some(StyleValueData::ScrollbarColor {
- thumb_color: combine_colors(from_thumb_color, to_thumb_color)?,
- track_color: combine_colors(from_track_color, to_track_color)?,
- })
+ Some(StyleValueData::ScrollbarColor(StyleValueBox::new(
+ ScrollbarColorPayload {
+ thumb_color: combine_colors(from_thumb_color, to_thumb_color)?,
+ track_color: combine_colors(from_track_color, to_track_color)?,
+ },
+ )))
}
pub(crate) fn interpolate_value(
@@ -7984,7 +8091,7 @@ pub(crate) fn interpolate_value(
) else {
return discrete_value(context, from, to, delta);
};
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Angle {
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Angle {
value: interpolate_f64(from_value, to_value, delta, Some((-90.0, 90.0))),
unit: 0,
}))
@@ -8076,18 +8183,20 @@ pub(crate) fn interpolate_value(
| crate::css::property_metadata::property_id::GRID_TEMPLATE_ROWS
)
&& let (
- StyleValueData::GridTrackSizeList {
- is_subgrid: from_is_subgrid,
- entries: from_entries,
- ..
- },
- StyleValueData::GridTrackSizeList {
- is_subgrid: to_is_subgrid,
- entries: to_entries,
- ..
- },
+ StyleValueData::GridTrackSizeList(grid_track_size_list_payload_1),
+ StyleValueData::GridTrackSizeList(grid_track_size_list_payload_2),
) = (from, to)
{
+ let GridTrackSizeListPayload {
+ is_subgrid: from_is_subgrid,
+ entries: from_entries,
+ ..
+ } = &**grid_track_size_list_payload_1;
+ let GridTrackSizeListPayload {
+ is_subgrid: to_is_subgrid,
+ entries: to_entries,
+ ..
+ } = &**grid_track_size_list_payload_2;
let Some(entries) = interpolate_grid_track_entries(
property_id,
*from_is_subgrid,
@@ -8098,11 +8207,13 @@ pub(crate) fn interpolate_value(
) else {
return discrete_value(context, from, to, delta);
};
- return owned(StyleValueData::GridTrackSizeList {
- is_subgrid: false,
- preserve_line_name_sets: false,
- entries: RetainedGridTrackEntryList::from_retained_entries(entries),
- });
+ return owned(StyleValueData::GridTrackSizeList(StyleValueBox::new(
+ GridTrackSizeListPayload {
+ is_subgrid: false,
+ preserve_line_name_sets: false,
+ entries: RetainedGridTrackEntryList::from_retained_entries(entries),
+ },
+ )));
}
if animation_type == ANIMATION_TYPE_CUSTOM {
// NB: C++ treats values declined by a property's specialized custom algorithm as discrete.
@@ -8134,7 +8245,7 @@ pub(crate) fn interpolate_value(
enum BatchAnimationValue<'a> {
Borrowed(&'a StyleValueData),
- Owned(Arc<StyleValueData>),
+ Owned(StyleValueArc),
}
impl BatchAnimationValue<'_> {
@@ -8356,6 +8467,171 @@ impl KeyframeStores {
}
}
+/// What the substitution of a keyframe value against an element read: the custom-property stores the element holds
+/// and inherits from, held so that neither address names another store while a conversion made against them is kept,
+/// and the generation of the custom property registrations.
+struct KeyframeConversionInputs {
+ substitution: Option<Arc<crate::css::custom_properties::CustomPropertyStore>>,
+ inheritance: Option<Arc<crate::css::custom_properties::CustomPropertyStore>>,
+ registration_generation: u64,
+}
+
+impl KeyframeConversionInputs {
+ /// # Safety
+ /// Each store of `stores` must be null or a live custom-property store.
+ unsafe fn retain(stores: KeyframeStores, registration_generation: u64) -> Self {
+ let retain = |store: *const std::ffi::c_void| {
+ let store = store.cast::<crate::css::custom_properties::CustomPropertyStore>();
+ // SAFETY: Guaranteed by the caller: a store lives in the Arc its holders count.
+ (!store.is_null()).then(|| unsafe {
+ Arc::increment_strong_count(store);
+ Arc::from_raw(store)
+ })
+ };
+ Self {
+ substitution: retain(stores.substitution),
+ inheritance: retain(stores.inheritance),
+ registration_generation,
+ }
+ }
+
+ /// Whether these are the inputs `stores` and `registration_generation` name.
+ fn are(&self, stores: KeyframeStores, registration_generation: u64) -> bool {
+ let address = |store: &Option<Arc<crate::css::custom_properties::CustomPropertyStore>>| {
+ store
+ .as_ref()
+ .map_or(std::ptr::null(), Arc::as_ptr)
+ .cast::<std::ffi::c_void>()
+ };
+ address(&self.substitution) == stores.substitution
+ && address(&self.inheritance) == stores.inheritance
+ && self.registration_generation == registration_generation
+ }
+}
+
+/// A keyframe value an effect wrote, for the property it was written for, and the value it substituted to.
+struct KeyframeConversion {
+ written: RetainedStyleValueData,
+ property: u16,
+ root_custom_property_name: Box<[u16]>,
+ converted: RetainedStyleValueData,
+}
+
+impl KeyframeConversion {
+ fn converts(&self, property: u16, root_custom_property_name: &[u16], written: &RetainedStyleValueData) -> bool {
+ self.written.pointer() == written.pointer()
+ && self.property == property
+ && *self.root_custom_property_name == *root_custom_property_name
+ }
+}
+
+/// The keyframe values of the effects an element samples as they substituted against what the element held, which a
+/// later sample reuses while what they read stands.
+pub(crate) struct KeyframeConversions {
+ inputs: KeyframeConversionInputs,
+ conversions: Vec<KeyframeConversion>,
+}
+
+/// The conversions a sample reuses and those it makes.
+pub(crate) struct KeyframeConversionCache {
+ kept: Option<Arc<KeyframeConversions>>,
+ reused: Vec<bool>,
+ made: Vec<KeyframeConversion>,
+}
+
+impl KeyframeConversionCache {
+ /// The cache of a sample against `stores`, reusing what `kept` holds where it was made against the same inputs.
+ pub(crate) fn new(
+ kept: Option<&Arc<KeyframeConversions>>,
+ stores: KeyframeStores,
+ registration_generation: u64,
+ ) -> Self {
+ let kept = kept
+ .filter(|kept| kept.inputs.are(stores, registration_generation))
+ .cloned();
+ Self {
+ reused: vec![false; kept.as_ref().map_or(0, |kept| kept.conversions.len())],
+ kept,
+ made: Vec::new(),
+ }
+ }
+
+ /// What `written` substitutes to for `property`: what an earlier sample substituted it to where its substitution
+ /// reads only the element's custom-property stores, else what `substitute` makes of it.
+ fn convert(
+ &mut self,
+ property: u16,
+ root_custom_property_name: &[u16],
+ written: &RetainedStyleValueData,
+ substitute: impl FnOnce() -> RetainedStyleValueData,
+ ) -> RetainedStyleValueData {
+ if !crate::css::style::RetainedState::keyframe_substitution_reads_only_stores(written.data()) {
+ return substitute();
+ }
+ if let Some(kept) = &self.kept
+ && let Some(index) = kept
+ .conversions
+ .iter()
+ .position(|conversion| conversion.converts(property, root_custom_property_name, written))
+ {
+ self.reused[index] = true;
+ return kept.conversions[index].converted.clone();
+ }
+ if let Some(made) = self
+ .made
+ .iter()
+ .find(|conversion| conversion.converts(property, root_custom_property_name, written))
+ {
+ return made.converted.clone();
+ }
+ let converted = substitute();
+ self.made.push(KeyframeConversion {
+ written: written.clone(),
+ property,
+ root_custom_property_name: root_custom_property_name.into(),
+ converted: converted.clone(),
+ });
+ converted
+ }
+
+ /// The conversions the next sample may reuse: those this one reused and made.
+ ///
+ /// # Safety
+ /// Each store of `stores` must be null or a live custom-property store.
+ pub(crate) unsafe fn finish(
+ self,
+ stores: KeyframeStores,
+ registration_generation: u64,
+ ) -> Option<Arc<KeyframeConversions>> {
+ if self.made.is_empty() && self.reused.iter().all(|&reused| reused) {
+ return self.kept;
+ }
+ let mut conversions = self.made;
+ if let Some(kept) = &self.kept {
+ conversions.extend(
+ kept.conversions
+ .iter()
+ .zip(&self.reused)
+ .filter(|&(_, &reused)| reused)
+ .map(|(conversion, _)| KeyframeConversion {
+ written: conversion.written.clone(),
+ property: conversion.property,
+ root_custom_property_name: conversion.root_custom_property_name.clone(),
+ converted: conversion.converted.clone(),
+ }),
+ );
+ }
+ if conversions.is_empty() {
+ return None;
+ }
+ Some(Arc::new(KeyframeConversions {
+ // SAFETY: Guaranteed by the caller.
+ inputs: unsafe { KeyframeConversionInputs::retain(stores, registration_generation) },
+ conversions,
+ }))
+ }
+}
+
/// The custom properties the effects an element samples declare, each minted into the number the
/// animation core keys it by, with what the element's environment and the document's registry say
/// of it.
@@ -8405,8 +8681,10 @@ impl AnimatedCustomProperties {
let name_raw = self.name(name_id).raw();
self.stores.element_declares_custom_properties
&& unsafe { KeyframeStores::store(self.stores.base) }.is_some_and(|store| {
- store.declared_names.contains(&name_raw)
- && store.own_values.get(&name_raw).is_some_and(|entry| entry.important)
+ store
+ .own_values
+ .get(&name_raw)
+ .is_some_and(|entry| entry.declared.is_some() && entry.important)
})
}
@@ -8487,8 +8765,6 @@ pub(crate) struct PublishedAnimationDeclarations {
/// The `SUBSTITUTION_MARK_*` bits of what the values and easings substituted against the
/// element held.
pub(crate) substitution_marks: u8,
- /// The custom properties a substituted `style()` query read.
- pub(crate) style_query_dependencies: Option<Box<crate::css::custom_properties::StyleQueryDependencies>>,
}
/// Substitute a keyframe value written as a token stream against an element, for the compositor,
@@ -8505,12 +8781,13 @@ pub unsafe extern "C" fn rust_substitute_compositor_keyframe_value(
host: &crate::render_state::DocumentHost,
read: &crate::render_state::BegunRead,
style_node: u32,
- pseudo_kind: u8,
+ pseudo_kind: u32,
custom_property_store: *const std::ffi::c_void,
inheritance_custom_property_store: *const std::ffi::c_void,
property_id: u16,
value: *const StyleValueData,
) -> *const StyleValueData {
+ let pseudo_kind = pseudo_kind as u8;
// SAFETY: Guaranteed by the caller.
crate::css::style::engine_calls::with_engine(read, host, |engine| {
let Some(node) = crate::css::style::tree::StyleNodeID::from_raw(style_node) else {
@@ -8520,7 +8797,7 @@ pub unsafe extern "C" fn rust_substitute_compositor_keyframe_value(
let written = unsafe {
RetainedStyleValueData::from_retained_pointer(crate::css::style_value::retain_style_value(value))
};
- // What a `style()` query reads is recorded when the main thread samples the same value.
+ // Whether a `style()` query reads the sibling position is noted when the main thread samples the same value.
let style_query_references = std::cell::RefCell::new(None);
let substituted = engine.substitute_keyframe_value(
node,
@@ -8532,7 +8809,7 @@ pub unsafe extern "C" fn rust_substitute_compositor_keyframe_value(
&written,
&style_query_references,
);
- std::sync::Arc::into_raw(substituted.into_arc())
+ StyleValueArc::into_raw(substituted.into_arc())
})
}
@@ -8549,7 +8826,7 @@ fn build_custom_property_keyframe_lookups(
) -> BTreeMap<u32, Vec<CustomPropertyKeyframeLookup>> {
let mut property_lookups = BTreeMap::<_, Vec<_>>::new();
let mut declaration_index = 0;
- for (keyframe_index, keyframe) in effect.keyframes.iter().enumerate() {
+ for (keyframe_index, keyframe) in effect.keyframes().iter().enumerate() {
for declaration in effect.custom_declarations_of(keyframe) {
let name_id = custom_properties.mint(&declaration.name);
@@ -8573,12 +8850,12 @@ fn select_custom_property_interval_span(
current_key: f64,
) -> [CustomPropertyKeyframeLookup; 2] {
let first_lookup = keyframe_lookups[0];
- let first_composite = effect.keyframes[first_lookup.keyframe_index].composite;
+ let first_composite = effect.keyframes()[first_lookup.keyframe_index].composite;
let first_value = &effect.custom_declaration_at(first_lookup.declaration_index).value;
let can_use_constant_interpolation = !matches!(first_value, PublishedValue::ElementValue)
&& keyframe_lookups.iter().all(|lookup| {
- let composite = effect.keyframes[lookup.keyframe_index].composite;
+ let composite = effect.keyframes()[lookup.keyframe_index].composite;
let value = &effect.custom_declaration_at(lookup.declaration_index).value;
composite == first_composite && value == first_value
});
@@ -8589,7 +8866,7 @@ fn select_custom_property_interval_span(
(0, keyframe_lookups.len() - 1)
} else {
keyframe_interval(keyframe_lookups.len(), current_key, |index| {
- effect.keyframes[keyframe_lookups[index].keyframe_index].key
+ effect.keyframes()[keyframe_lookups[index].keyframe_index].key
})
};
@@ -8606,11 +8883,12 @@ pub(crate) fn resolve_published_animation_declarations(
node: crate::css::style::tree::StyleNodeID,
pseudo: Option<u8>,
selected: &[SelectedEffect<'_>],
- table: &crate::css::computed_longhand_table::ComputedLonghandTable,
+ longhands: crate::css::style::ViewLonghands<'_>,
stores: KeyframeStores,
writing_mode: u8,
direction: u8,
important_property_bitmap: &[u8],
+ conversions: &std::cell::RefCell<KeyframeConversionCache>,
) -> PublishedAnimationDeclarations {
use crate::css::style::effect_descriptions::{PublishedValue, easing_from_computed_timing_function};
let registry = engine.custom_property_registry();
@@ -8624,16 +8902,18 @@ pub(crate) fn resolve_published_animation_declarations(
let style_query_references = std::cell::RefCell::new(None);
let substitute = |property, root_name: &[u16], written: &RetainedStyleValueData| {
substitution_marks.set(substitution_marks.get() | substitution_marks_of(written.data()));
- engine.substitute_keyframe_value(
- node,
- pseudo,
- stores.substitution,
- stores.inheritance,
- property,
- root_name,
- written,
- &style_query_references,
- )
+ conversions.borrow_mut().convert(property, root_name, written, || {
+ engine.substitute_keyframe_value(
+ node,
+ pseudo,
+ stores.substitution,
+ stores.inheritance,
+ property,
+ root_name,
+ written,
+ &style_query_references,
+ )
+ })
};
let mut keyframes = Vec::new();
let mut easings = Vec::new();
@@ -8643,7 +8923,7 @@ pub(crate) fn resolve_published_animation_declarations(
for selection in selected {
let effect = selection.effect;
let is_transition = effect.is_transition;
- let style_sheet_resource_context = match &effect.resource_context {
+ let style_sheet_resource_context = match effect.resource_context() {
None => FfiAnimationStyleSheetResourceContext {
base_url: std::ptr::null(),
base_url_length: 0,
@@ -8661,7 +8941,7 @@ pub(crate) fn resolve_published_animation_declarations(
}
};
let first_keyframe_index = keyframes.len();
- for keyframe in &effect.keyframes {
+ for keyframe in effect.keyframes() {
let keyframe_index = keyframes.len();
keyframes.push((keyframe.key, keyframe.composite));
// A keyframe's own easing written as a value substitutes against the element; one that
@@ -8690,7 +8970,7 @@ pub(crate) fn resolve_published_animation_declarations(
for declaration in keyframe_declarations {
let (value, use_initial) = match &declaration.value {
PublishedValue::ElementValue => {
- let Some(value) = table.get(declaration.property_id) else {
+ let Some(value) = longhands.handle(declaration.property_id) else {
continue;
};
(value.clone_retained(), true)
@@ -8706,6 +8986,7 @@ pub(crate) fn resolve_published_animation_declarations(
match value.data() {
StyleValueData::PendingSubstitution {
original_shorthand_value,
+ ..
} => written_shorthand_value(original_shorthand_value),
_ => value,
}
@@ -8850,8 +9131,8 @@ pub(crate) fn resolve_published_animation_declarations(
direction,
important_property_bitmap,
);
- let style_query_dependencies = style_query_references.into_inner();
- resolved.uses_tree_counting_function |= style_query_dependencies
+ resolved.uses_tree_counting_function |= style_query_references
+ .into_inner()
.as_ref()
.is_some_and(|dependencies| dependencies.sibling_position);
resolved._base_urls = base_urls;
@@ -8859,7 +9140,6 @@ pub(crate) fn resolve_published_animation_declarations(
resolved: Box::new(resolved),
custom_properties,
substitution_marks: substitution_marks.get(),
- style_query_dependencies,
}
}
@@ -8868,15 +9148,7 @@ pub(crate) fn resolve_published_animation_declarations(
fn holds_arbitrary_substitution(value: &StyleValueData) -> bool {
matches!(
value,
- StyleValueData::Unresolved {
- presence_attr,
- presence_dashed_function,
- presence_env,
- presence_if,
- presence_inherit,
- presence_var,
- ..
- } if *presence_attr || *presence_dashed_function || *presence_env || *presence_if || *presence_inherit || *presence_var
+ StyleValueData::Unresolved(unresolved) if unresolved.presence().has_any()
)
}
@@ -8981,7 +9253,7 @@ pub(crate) fn evaluate_animations(batch: ComputedAnimationBatch<'_>) -> Vec<(u32
cache_preparation,
preparation_reads_custom_property_environments,
preparation_inputs,
- underlying_longhand_table,
+ underlying_longhands,
overlay,
custom_underlying_values,
custom_initial_values,
@@ -9059,8 +9331,8 @@ pub(crate) fn evaluate_animations(batch: ComputedAnimationBatch<'_>) -> Vec<(u32
custom_initial_values[custom_index].optional_data(),
)
} else {
- let underlying = underlying_longhand_table
- .get(plan.property_id)
+ let underlying = underlying_longhands
+ .handle(plan.property_id)
.expect("an animated longhand must have an underlying computed value");
(
underlying.optional_data(),
@@ -9146,7 +9418,7 @@ mod tests {
#[test]
fn resolves_keyframe_property_conflicts_as_one_batch() {
use crate::css::property_metadata::property_id;
- let value = || RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Number { value: 1.0 }));
+ let value = || RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Number { value: 1.0 }));
let candidates = [
AnimationPropertyConflictCandidate {
custom_name_id: 0,
@@ -9275,9 +9547,9 @@ mod tests {
use crate::css::property_metadata::property_id;
let values = [
- Arc::new(StyleValueData::Number { value: 0.0 }),
- Arc::new(StyleValueData::Number { value: 0.5 }),
- Arc::new(StyleValueData::Number { value: 1.0 }),
+ StyleValueArc::new(StyleValueData::Number { value: 0.0 }),
+ StyleValueArc::new(StyleValueData::Number { value: 0.5 }),
+ StyleValueArc::new(StyleValueData::Number { value: 1.0 }),
];
let declarations = [
AnimationDeclaration {
@@ -9339,8 +9611,9 @@ mod tests {
#[test]
fn retains_synthesized_pending_substitution_values() {
- let original = RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Number { value: 1.0 }));
- let pending = Arc::new(StyleValueData::PendingSubstitution {
+ let original = RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Number { value: 1.0 }));
+ let pending = StyleValueArc::new(StyleValueData::PendingSubstitution {
+ original_shorthand: crate::css::property_metadata::property_id::BORDER,
original_shorthand_value: original,
});
let declaration = AnimationDeclaration {
@@ -9361,6 +9634,7 @@ mod tests {
let value = property.value.data();
if let StyleValueData::PendingSubstitution {
original_shorthand_value,
+ ..
} = value
&& matches!(
original_shorthand_value.data(),
@@ -9414,7 +9688,7 @@ mod tests {
}
fn calculated_number(value: f64) -> StyleValueData {
- StyleValueData::Calculated {
+ StyleValueData::Calculated(StyleValueBox::new(CalculatedPayload {
rust_calculation: crate::css::calc::CalcNodeHandle::from_arc(Arc::new(
crate::css::calc::CalcNode::Numeric(crate::css::calc::CalcNumericValue::Number {
value,
@@ -9430,7 +9704,7 @@ mod tests {
percentages_resolve_as: 0,
resolve_numbers_as_integers: false,
accepted_ranges: RetainedNumericRangeList::empty(),
- }
+ }))
}
#[test]
@@ -9461,7 +9735,7 @@ mod tests {
interval_count: 4,
step_position: 1,
};
- let value = unsafe { Arc::from_raw(style_value_from_easing(&descriptor)) };
+ let value = unsafe { StyleValueArc::from_raw(style_value_from_easing(&descriptor)) };
assert_eq!(
crate::css::serialize::serialize_style_value_to_utf16(&value),
expected.encode_utf16().collect::<Vec<_>>()
@@ -9472,7 +9746,7 @@ mod tests {
#[test]
fn evaluates_composited_animation_value() {
let underlying = StyleValueData::Number { value: 2.0 };
- let number = |value| RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Number { value }));
+ let number = |value| RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Number { value }));
let linear_easing = || Easing::CubicBezier {
x1: 0.0,
y1: 0.0,
@@ -9525,7 +9799,7 @@ mod tests {
.enumerate()
.map(|(keyframe, value)| AnimationKeyframeValue {
keyframe,
- value: RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Number { value })),
+ value: RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Number { value })),
is_implicit: false,
})
.collect::<Vec<_>>();
@@ -9559,8 +9833,8 @@ mod tests {
fn evaluates_missing_keyframe_values() {
let underlying = StyleValueData::Number { value: 2.0 };
let initial = StyleValueData::Number { value: 1.0 };
- let start = || RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Number { value: 3.0 }));
- let end = || RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Number { value: 5.0 }));
+ let start = || RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Number { value: 3.0 }));
+ let end = || RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Number { value: 5.0 }));
let easing = || Easing::CubicBezier {
x1: 0.0,
y1: 0.0,
@@ -9615,8 +9889,8 @@ mod tests {
#[test]
fn evaluates_discrete_animation_values() {
- let from = Arc::new(StyleValueData::Keyword { keyword: 1 });
- let to = Arc::new(StyleValueData::Keyword { keyword: 2 });
+ let from = StyleValueArc::new(StyleValueData::Keyword { keyword: 1 });
+ let to = StyleValueArc::new(StyleValueData::Keyword { keyword: 2 });
let property_id = crate::css::property_metadata::property_id::ALIGN_CONTENT;
let result = interpolate_value(Some(&animation_context(true)), property_id, &from, &to, 0.25);
@@ -9637,21 +9911,21 @@ mod tests {
#[test]
fn evaluates_incompatible_by_computed_values_as_discrete() {
let property_id = crate::css::property_metadata::property_id::FLEX_GROW;
- let from = Arc::new(StyleValueData::Keyword { keyword: 1 });
- let to = Arc::new(StyleValueData::Keyword { keyword: 2 });
+ let from = StyleValueArc::new(StyleValueData::Keyword { keyword: 1 });
+ let to = StyleValueArc::new(StyleValueData::Keyword { keyword: 2 });
let result = interpolate_value(Some(&animation_context(true)), property_id, &from, &to, 0.25);
assert!(result.handled);
assert_eq!(
result.value.as_ref().map(RetainedStyleValueData::pointer),
- Some(Arc::as_ptr(&from))
+ Some(StyleValueArc::as_ptr(&from))
);
let result = interpolate_value(Some(&animation_context(true)), property_id, &from, &to, 0.75);
assert!(result.handled);
assert_eq!(
result.value.as_ref().map(RetainedStyleValueData::pointer),
- Some(Arc::as_ptr(&to))
+ Some(StyleValueArc::as_ptr(&to))
);
let result = interpolate_value(Some(&animation_context(false)), property_id, &from, &to, 0.75);
@@ -9661,8 +9935,8 @@ mod tests {
#[test]
fn preserves_not_animatable_endpoint_behavior() {
- let from = Arc::new(StyleValueData::Keyword { keyword: 1 });
- let to = Arc::new(StyleValueData::Keyword { keyword: 2 });
+ let from = StyleValueArc::new(StyleValueData::Keyword { keyword: 1 });
+ let to = StyleValueArc::new(StyleValueData::Keyword { keyword: 2 });
let result = interpolate_value(
Some(&animation_context(true)),
crate::css::property_metadata::property_id::ANIMATION_DURATION,
@@ -9677,8 +9951,8 @@ mod tests {
#[test]
fn evaluates_declined_custom_animation_values_as_discrete() {
- let from = Arc::new(StyleValueData::Keyword { keyword: 1 });
- let to = Arc::new(StyleValueData::Keyword { keyword: 2 });
+ let from = StyleValueArc::new(StyleValueData::Keyword { keyword: 1 });
+ let to = StyleValueArc::new(StyleValueData::Keyword { keyword: 2 });
let property_id = crate::css::property_metadata::property_id::SCALE;
let result = interpolate_value(Some(&animation_context(true)), property_id, &from, &to, 0.75);
@@ -9694,8 +9968,8 @@ mod tests {
#[test]
fn normalizes_repeatable_scalar_and_list_values() {
let property_id = crate::css::property_metadata::property_id::OBJECT_POSITION;
- let from = Arc::new(StyleValueData::Number { value: 10.0 });
- let to = Arc::new(StyleValueData::ValueList {
+ let from = StyleValueArc::new(StyleValueData::Number { value: 10.0 });
+ let to = StyleValueArc::new(StyleValueData::ValueList {
values: RetainedStyleValueDataList::from_retained_values(vec![
retained_number(20.0),
retained_number(30.0),
@@ -9716,8 +9990,8 @@ mod tests {
#[test]
fn interpolates_repeatable_scalar_values() {
- let from = Arc::new(StyleValueData::Number { value: 10.0 });
- let to = Arc::new(StyleValueData::Number { value: 20.0 });
+ let from = StyleValueArc::new(StyleValueData::Number { value: 10.0 });
+ let to = StyleValueArc::new(StyleValueData::Number { value: 20.0 });
let result = interpolate_value(
Some(&animation_context(true)),
crate::css::property_metadata::property_id::OBJECT_POSITION,
@@ -9732,8 +10006,8 @@ mod tests {
#[test]
fn interpolates_mixed_length_percentage_values() {
- let from = Arc::new(StyleValueData::Length { value: 10.0, unit: 0 });
- let to = Arc::new(StyleValueData::Percentage { value: 50.0 });
+ let from = StyleValueArc::new(StyleValueData::Length { value: 10.0, unit: 0 });
+ let to = StyleValueArc::new(StyleValueData::Percentage { value: 50.0 });
let result = interpolate_value(
Some(&animation_context(true)),
crate::css::property_metadata::property_id::WIDTH,
@@ -9748,8 +10022,8 @@ mod tests {
#[test]
fn combines_lengths_with_different_units_discretely() {
- let from = Arc::new(StyleValueData::Length { value: 10.0, unit: 0 });
- let to = Arc::new(StyleValueData::Length { value: 20.0, unit: 1 });
+ let from = StyleValueArc::new(StyleValueData::Length { value: 10.0, unit: 0 });
+ let to = StyleValueArc::new(StyleValueData::Length { value: 20.0, unit: 1 });
let result = interpolate_value(
Some(&animation_context(true)),
crate::css::property_metadata::property_id::WIDTH,
@@ -9765,7 +10039,7 @@ mod tests {
#[test]
fn interpolates_rotate_3d_with_a_zero_axis() {
let retained_angle =
- |value| RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Angle { value, unit: 0 }));
+ |value| RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Angle { value, unit: 0 }));
let from = RetainedStyleValueDataList::from_retained_values(vec![
retained_number(0.0),
retained_number(0.0),
@@ -9787,9 +10061,10 @@ mod tests {
0.5,
)
.expect("rotate3d values should interpolate");
- let StyleValueData::Transformation { values, .. } = result else {
+ let StyleValueData::Transformation(transformation_payload) = result else {
panic!("expected a transform function");
};
+ let TransformationPayload { values, .. } = &*transformation_payload;
assert!(values.as_slice().iter().all(|value| match value.data() {
StyleValueData::Number { value } | StyleValueData::Angle { value, .. } => value.is_finite(),
_ => false,
@@ -9798,8 +10073,8 @@ mod tests {
#[test]
fn composes_mixed_length_percentage_values() {
- let underlying = Arc::new(StyleValueData::Length { value: 10.0, unit: 0 });
- let animated = Arc::new(StyleValueData::Percentage { value: 50.0 });
+ let underlying = StyleValueArc::new(StyleValueData::Length { value: 10.0, unit: 0 });
+ let animated = StyleValueArc::new(StyleValueData::Percentage { value: 50.0 });
let result = composite_scalar_value(&underlying, &animated, FfiCompositeOperation::Add);
assert!(result.handled);
let value = result.value.unwrap().into_arc();
@@ -9808,10 +10083,10 @@ mod tests {
#[test]
fn owns_unsupported_composition_decisions() {
- let underlying = Arc::new(StyleValueData::Keyword {
+ let underlying = StyleValueArc::new(StyleValueData::Keyword {
keyword: crate::css::style_compute::none_keyword(),
});
- let animated = Arc::new(StyleValueData::Number { value: 4.0 });
+ let animated = StyleValueArc::new(StyleValueData::Number { value: 4.0 });
let result = composite_scalar_value(&underlying, &animated, FfiCompositeOperation::Add);
assert!(result.handled);
assert!(result.value.is_none());
@@ -9819,8 +10094,8 @@ mod tests {
#[test]
fn combines_general_calculated_numeric_values() {
- let from = Arc::new(calculated_number(2.0));
- let to = Arc::new(StyleValueData::Number { value: 4.0 });
+ let from = StyleValueArc::new(calculated_number(2.0));
+ let to = StyleValueArc::new(StyleValueData::Number { value: 4.0 });
let result = interpolate_value(
Some(&animation_context(true)),
crate::css::property_metadata::property_id::FLEX_GROW,
@@ -9838,7 +10113,7 @@ mod tests {
assert!(matches!(&*value, StyleValueData::Calculated { .. }));
}
- fn parsed(property: u16, source: &str) -> Arc<StyleValueData> {
+ fn parsed(property: u16, source: &str) -> StyleValueArc {
use crate::css::css_tokenizer::{TokenizerInput, tokenize_for_parser};
use crate::css::parser::component_value::consume_a_list_of_component_values;
use crate::css::parser::value_parser::{ParseContext, ParseOutcome, parse_css_value};
@@ -9872,7 +10147,7 @@ mod tests {
let values = if let StyleValueData::ValueList { values, .. } = value {
values.as_slice().to_vec()
} else {
- vec![RetainedStyleValueData::from_arc(Arc::new(value.clone()))]
+ vec![RetainedStyleValueData::from_arc(StyleValueArc::new(value.clone()))]
};
let matrix = post_multiply_transformations(None, &values).unwrap();
for (actual, expected) in matrix
@@ -10071,7 +10346,7 @@ mod tests {
}
// Corner radii, horizontal and vertical, from the top left corner clockwise.
- fn border_radius_rect(corners: [(f64, f64); 4]) -> Arc<StyleValueData> {
+ fn border_radius_rect(corners: [(f64, f64); 4]) -> StyleValueArc {
let px = |value| {
RetainedStyleValueData::from_owned(StyleValueData::Length {
value,
@@ -10079,18 +10354,20 @@ mod tests {
})
};
let [top_left, top_right, bottom_right, bottom_left] = corners.map(|(horizontal, vertical)| {
- RetainedStyleValueData::from_owned(StyleValueData::BorderRadius {
+ RetainedStyleValueData::from_owned(StyleValueData::BorderRadius(StyleValueBox::new(BorderRadiusPayload {
is_elliptical: horizontal != vertical,
horizontal_radius: px(horizontal),
vertical_radius: px(vertical),
- })
+ })))
});
- Arc::new(StyleValueData::BorderRadiusRect {
- top_left,
- top_right,
- bottom_right,
- bottom_left,
- })
+ StyleValueArc::new(StyleValueData::BorderRadiusRect(StyleValueBox::new(
+ BorderRadiusRectPayload {
+ top_left,
+ top_right,
+ bottom_right,
+ bottom_left,
+ },
+ )))
}
#[test]
@@ -10141,7 +10418,7 @@ mod tests {
#[test]
fn adds_opacities_up_to_one() {
let opacity = || {
- Arc::new(StyleValueData::OpacityValue {
+ StyleValueArc::new(StyleValueData::OpacityValue {
value: retained_number(0.75),
})
};
diff --git a/Libraries/LibWeb/Rust/src/css/calc.rs b/Libraries/LibWeb/Rust/src/css/calc.rs
index a57e86a882c..a3b339ace4d 100644
--- a/Libraries/LibWeb/Rust/src/css/calc.rs
+++ b/Libraries/LibWeb/Rust/src/css/calc.rs
@@ -14,6 +14,10 @@
//! the C++ staging.
use crate::css::ffi_support::{OwnedArc, OwnedBox};
+use crate::css::style_value::{
+ AnchorPayload, AnchorSizePayload, CalculatedPayload, RandomValueSharingPayload, StyleValueBox,
+};
+use crate::css::style_value_arc::StyleValueArc;
use std::sync::Arc;
use crate::css::style_value::{RetainedStyleValueData, StyleValueData};
@@ -368,7 +372,7 @@ pub(crate) fn serialize_context_free_calculation(
if !numeric_type.matches_dimension(expected_base_type, None) {
return None;
}
- let calculated = crate::css::style_value::StyleValueData::Calculated {
+ let calculated = crate::css::style_value::StyleValueData::Calculated(StyleValueBox::new(CalculatedPayload {
rust_calculation: CalcNodeHandle::from_arc(root),
resolve_as_is_number: false,
resolve_as_base: 0,
@@ -377,7 +381,7 @@ pub(crate) fn serialize_context_free_calculation(
percentages_resolve_as: 0,
resolve_numbers_as_integers: false,
accepted_ranges: crate::css::style_value::RetainedNumericRangeList::empty(),
- };
+ }));
Some(crate::css::serialize::serialize_style_value_to_utf16(&calculated))
}
@@ -2630,7 +2634,7 @@ pub(crate) fn length_percentage_calculated_style_value(
) -> crate::css::style_value::StyleValueData {
use crate::css::style_value::{RetainedNumericRangeList, StyleValueData};
- StyleValueData::Calculated {
+ StyleValueData::Calculated(StyleValueBox::new(CalculatedPayload {
rust_calculation: CalcNodeHandle::from_arc(calculation),
resolve_as_is_number: false,
resolve_as_base: BASE_TYPE_LENGTH as u8,
@@ -2639,7 +2643,7 @@ pub(crate) fn length_percentage_calculated_style_value(
percentages_resolve_as: value_type::LENGTH,
resolve_numbers_as_integers: false,
accepted_ranges: RetainedNumericRangeList::empty(),
- }
+ }))
}
/// Wraps a computed anchor() or anchor-size() value into the calculated style
@@ -2657,7 +2661,7 @@ pub(crate) fn length_percentage_calculated_style_value(
#[allow(clippy::arc_with_non_send_sync)]
pub(crate) unsafe fn create_anchor_function_calculated(
anchor: *const crate::css::style_value::StyleValueData,
-) -> Arc<crate::css::style_value::StyleValueData> {
+) -> StyleValueArc {
use crate::css::style_value::StyleValueData;
assert!(
@@ -2667,11 +2671,11 @@ pub(crate) unsafe fn create_anchor_function_calculated(
),
"anchor function handle holds a non-anchor style value"
);
- unsafe { Arc::increment_strong_count(anchor) };
+ unsafe { StyleValueArc::increment_strong_count(anchor) };
let anchor_value = unsafe { RetainedStyleValueData::from_retained_pointer(anchor) };
let mut length_type = CalcNumericType::default();
length_type.exponents[BASE_TYPE_LENGTH] = Some(1);
- Arc::new(length_percentage_calculated_style_value(
+ StyleValueArc::new(length_percentage_calculated_style_value(
shared(CalcNode::NonMathFunction {
value: anchor_value,
numeric_type: length_type,
@@ -2818,9 +2822,10 @@ fn prepare_external_resolutions(root: &CalcNode, context: &FfiCalcResolutionCont
} else {
continue;
};
- let StyleValueData::RandomValueSharing { fixed_value, .. } = sharing.data() else {
+ let StyleValueData::RandomValueSharing(random_value_sharing_payload) = sharing.data() else {
continue;
};
+ let RandomValueSharingPayload { fixed_value, .. } = &**random_value_sharing_payload;
let number = match fixed_value.optional_data() {
Some(StyleValueData::Number { value }) => Some(*value),
Some(calculated @ StyleValueData::Calculated { .. }) => {
@@ -2865,8 +2870,9 @@ fn prepare_external_resolutions(root: &CalcNode, context: &FfiCalcResolutionCont
pub(crate) fn collect_unfixed_random_sharings(node: &CalcNode, sharings: &mut Vec<*const StyleValueData>) {
if let CalcNode::Random { sharing, .. } = node
- && let StyleValueData::RandomValueSharing { fixed_value, .. } = sharing.data()
+ && let StyleValueData::RandomValueSharing(random_value_sharing_payload) = sharing.data()
{
+ let RandomValueSharingPayload { fixed_value, .. } = &**random_value_sharing_payload;
if let Some(fixed_value) = fixed_value.optional_data() {
crate::css::style_compute::collect_unfixed_random_sharings_in_value(fixed_value, sharings);
} else {
@@ -2881,9 +2887,10 @@ pub(crate) fn collect_unfixed_random_sharings(node: &CalcNode, sharings: &mut Ve
/// Returns the borrowed calculation-tree root stored in calculated style value data.
pub(crate) fn calc_root(calculated: &crate::css::style_value::StyleValueData) -> &CalcNode {
- let crate::css::style_value::StyleValueData::Calculated { rust_calculation, .. } = calculated else {
+ let crate::css::style_value::StyleValueData::Calculated(calculated_payload) = calculated else {
unreachable!("calc_root requires calculated value data");
};
+ let CalculatedPayload { rust_calculation, .. } = &**calculated_payload;
rust_calculation.node()
}
@@ -3122,7 +3129,10 @@ fn resolve_calculated_with_channels_options(
apply_censoring_and_clamping: bool,
) -> Option<(f64, CalcNumericType, Option<ResolveAs>)> {
use crate::css::style_value::StyleValueData;
- let StyleValueData::Calculated {
+ let StyleValueData::Calculated(calculated_payload) = calculated else {
+ return None;
+ };
+ let CalculatedPayload {
rust_calculation,
has_percentages_resolve_as,
resolve_as_is_number,
@@ -3130,17 +3140,15 @@ fn resolve_calculated_with_channels_options(
resolve_numbers_as_integers,
accepted_ranges,
..
- } = calculated
- else {
- return None;
- };
+ } = &**calculated_payload;
let root = rust_calculation.node_arc();
let resolve_as = resolve_as_from_fields(*has_percentages_resolve_as, *resolve_as_is_number, *resolve_as_base);
let percentage_leaf_type = percentage_leaf_type_for(resolve_as);
let fixed_random_base_value = |sharing: &RetainedStyleValueData| {
- let StyleValueData::RandomValueSharing { fixed_value, .. } = sharing.data() else {
+ let StyleValueData::RandomValueSharing(random_value_sharing_payload) = sharing.data() else {
return None;
};
+ let RandomValueSharingPayload { fixed_value, .. } = &**random_value_sharing_payload;
match fixed_value.optional_data() {
Some(StyleValueData::Number { value }) => Some(*value),
_ => None,
@@ -3625,7 +3633,10 @@ pub(crate) fn resolve_calculated(
apply_censoring_and_clamping: bool,
) -> FfiResolvedCalc {
use crate::css::style_value::StyleValueData;
- let StyleValueData::Calculated {
+ let StyleValueData::Calculated(calculated_payload) = calculated else {
+ unreachable!("resolve_calculated requires calculated value data");
+ };
+ let CalculatedPayload {
rust_calculation,
has_percentages_resolve_as,
resolve_as_is_number,
@@ -3633,10 +3644,7 @@ pub(crate) fn resolve_calculated(
resolve_numbers_as_integers,
accepted_ranges,
..
- } = calculated
- else {
- unreachable!("resolve_calculated requires calculated value data");
- };
+ } = &**calculated_payload;
let root = rust_calculation.node_arc();
// The percentage leaf type and resolve-as target from the creation-time fields.
@@ -3671,8 +3679,7 @@ pub(crate) fn resolve_calculated(
)
}
-#[repr(C)]
-pub struct FfiCalcSerializationPiece {
+pub struct CalcSerializationPiece {
/// 0 = literal, 1 = numeric leaf, 2 = style value, 3 = channel keyword,
/// 4 = literal conditioned on the preceding piece producing output.
pub kind: u8,
@@ -3713,15 +3720,15 @@ impl CalcNumericValue {
}
struct CalcSerializer<'a> {
- pieces: Vec<FfiCalcSerializationPiece>,
+ pieces: Vec<CalcSerializationPiece>,
resolved_mode: bool,
resolve_numbers_as_integers: bool,
accepted_ranges: &'a [crate::css::style_value::RetainedNumericRangeByType],
}
impl CalcSerializer<'_> {
- fn piece(kind: u8) -> FfiCalcSerializationPiece {
- FfiCalcSerializationPiece {
+ fn piece(kind: u8) -> CalcSerializationPiece {
+ CalcSerializationPiece {
kind,
numeric_kind: 0,
unit_or_channel: 0,
@@ -3733,7 +3740,7 @@ impl CalcSerializer<'_> {
}
fn literal(&mut self, text: &'static str) {
- self.pieces.push(FfiCalcSerializationPiece {
+ self.pieces.push(CalcSerializationPiece {
bytes: text.as_ptr(),
length: text.len(),
..Self::piece(0)
@@ -3741,7 +3748,7 @@ impl CalcSerializer<'_> {
}
fn conditional_literal(&mut self, text: &'static str) {
- self.pieces.push(FfiCalcSerializationPiece {
+ self.pieces.push(CalcSerializationPiece {
bytes: text.as_ptr(),
length: text.len(),
..Self::piece(4)
@@ -3750,7 +3757,7 @@ impl CalcSerializer<'_> {
fn leaf(&mut self, value: CalcNumericValue) {
let (kind, raw, unit) = value.leaf_parts();
- self.pieces.push(FfiCalcSerializationPiece {
+ self.pieces.push(CalcSerializationPiece {
numeric_kind: kind,
unit_or_channel: unit,
value: raw,
@@ -3759,14 +3766,14 @@ impl CalcSerializer<'_> {
}
fn style_value(&mut self, value: &RetainedStyleValueData) {
- self.pieces.push(FfiCalcSerializationPiece {
+ self.pieces.push(CalcSerializationPiece {
style_value: value.data() as *const _ as *const _,
..Self::piece(2)
});
}
fn channel(&mut self, channel: u8) {
- self.pieces.push(FfiCalcSerializationPiece {
+ self.pieces.push(CalcSerializationPiece {
unit_or_channel: channel,
..Self::piece(3)
});
@@ -4287,10 +4294,7 @@ pub(crate) fn absolutize_anchor_function(
random_base_values: &[crate::css::style_compute::FfiRandomBaseValue],
) -> Option<Option<crate::css::style_value::StyleValueData>> {
use crate::css::style_value::StyleValueData;
- let (StyleValueData::Anchor { fallback_value, .. } | StyleValueData::AnchorSize { fallback_value, .. }) = value
- else {
- return None;
- };
+ let (_, _, fallback_value) = value.anchor_name_and_fallback()?;
let absolutized_fallback = match fallback_value.optional_data() {
None => return Some(None),
Some(StyleValueData::Length { value, unit }) => {
@@ -4321,32 +4325,38 @@ pub(crate) fn absolutize_anchor_function(
}
Some(_) => return Some(None),
};
- let fallback_value = RetainedStyleValueData::from_arc(Arc::new(absolutized_fallback));
+ let fallback_value = RetainedStyleValueData::from_arc(StyleValueArc::new(absolutized_fallback));
Some(Some(match value {
- StyleValueData::Anchor {
- has_anchor_name,
- anchor_name,
- anchor_side,
- ..
- } => StyleValueData::Anchor {
- has_anchor_name: *has_anchor_name,
- anchor_name: anchor_name.clone(),
- anchor_side: anchor_side.clone_retained(),
- fallback_value,
- },
- StyleValueData::AnchorSize {
- has_anchor_name,
- anchor_name,
- has_anchor_size,
- anchor_size,
- ..
- } => StyleValueData::AnchorSize {
- has_anchor_name: *has_anchor_name,
- anchor_name: anchor_name.clone(),
- has_anchor_size: *has_anchor_size,
- anchor_size: *anchor_size,
- fallback_value,
- },
+ StyleValueData::Anchor(anchor_payload) => {
+ let AnchorPayload {
+ has_anchor_name,
+ anchor_name,
+ anchor_side,
+ ..
+ } = &**anchor_payload;
+ StyleValueData::Anchor(StyleValueBox::new(AnchorPayload {
+ has_anchor_name: *has_anchor_name,
+ anchor_name: anchor_name.clone(),
+ anchor_side: anchor_side.clone_retained(),
+ fallback_value,
+ }))
+ }
+ StyleValueData::AnchorSize(anchor_size_payload) => {
+ let AnchorSizePayload {
+ has_anchor_name,
+ anchor_name,
+ has_anchor_size,
+ anchor_size,
+ ..
+ } = &**anchor_size_payload;
+ StyleValueData::AnchorSize(StyleValueBox::new(AnchorSizePayload {
+ has_anchor_name: *has_anchor_name,
+ anchor_name: anchor_name.clone(),
+ has_anchor_size: *has_anchor_size,
+ anchor_size: *anchor_size,
+ fallback_value,
+ }))
+ }
_ => unreachable!("the value was matched as an anchor function above"),
}))
}
@@ -4364,16 +4374,16 @@ pub(crate) fn absolutize_calculation_value(
random_base_values: &[crate::css::style_compute::FfiRandomBaseValue],
) -> Option<AbsolutizedCalculation> {
use crate::css::style_value::StyleValueData;
- let StyleValueData::Calculated {
+ let StyleValueData::Calculated(calculated_payload) = value else {
+ return None;
+ };
+ let CalculatedPayload {
rust_calculation,
resolve_as_is_number,
resolve_as_base,
has_percentages_resolve_as,
..
- } = value
- else {
- return None;
- };
+ } = &**calculated_payload;
let root = rust_calculation.node_arc();
let mut externals = Vec::new();
collect_external_resolutions(&root, &mut externals);
@@ -4392,9 +4402,10 @@ pub(crate) fn absolutize_calculation_value(
continue;
}
if matches!(external.kind, CalcExternalResolutionKind::RandomSharing) {
- let StyleValueData::RandomValueSharing { fixed_value, .. } = external.source.data() else {
+ let StyleValueData::RandomValueSharing(random_value_sharing_payload) = external.source.data() else {
return None;
};
+ let RandomValueSharingPayload { fixed_value, .. } = &**random_value_sharing_payload;
let number = match fixed_value.optional_data() {
Some(StyleValueData::Number { value }) => *value,
Some(fixed_value @ StyleValueData::Calculated { .. }) => {
@@ -4416,14 +4427,17 @@ pub(crate) fn absolutize_calculation_value(
.find(|resolution| resolution.source == external.source.pointer().cast())
.map(|resolution| resolution.value)?,
};
- let fixed_number = RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Number { value: number }));
- let resolved = RetainedStyleValueData::from_arc(Arc::new(StyleValueData::RandomValueSharing {
- fixed_value: fixed_number,
- is_auto: false,
- has_name: false,
- name: crate::css::style_value::CssString::none(),
- element_shared: false,
- }));
+ let fixed_number =
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Number { value: number }));
+ let resolved = RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::RandomValueSharing(
+ StyleValueBox::new(RandomValueSharingPayload {
+ fixed_value: fixed_number,
+ is_auto: false,
+ has_name: false,
+ name: crate::css::style_value::CssString::none(),
+ element_shared: false,
+ }),
+ )));
external.has_number = true;
external.number = number;
external.resolved_style_value = Some(resolved);
@@ -4446,7 +4460,7 @@ pub(crate) fn absolutize_calculation_value(
let mut length_type = CalcNumericType::default();
length_type.exponents[BASE_TYPE_LENGTH] = Some(1);
external.resolved_node = Some(Arc::new(CalcNode::NonMathFunction {
- value: RetainedStyleValueData::from_arc(Arc::new(absolutized)),
+ value: RetainedStyleValueData::from_arc(StyleValueArc::new(absolutized)),
numeric_type: length_type,
}));
}
@@ -4496,7 +4510,10 @@ fn computed_calculation_from_simplified(
evaluation_context: &CalcEvaluationContext,
) -> AbsolutizedCalculation {
use crate::css::style_value::StyleValueData;
- let StyleValueData::Calculated {
+ let StyleValueData::Calculated(calculated_payload) = value else {
+ unreachable!("computed_calculation_from_simplified requires calculated value data");
+ };
+ let CalculatedPayload {
resolve_as_is_number,
resolve_as_base,
resolved_type,
@@ -4505,10 +4522,7 @@ fn computed_calculation_from_simplified(
resolve_numbers_as_integers,
accepted_ranges,
..
- } = value
- else {
- unreachable!("computed_calculation_from_simplified requires calculated value data");
- };
+ } = &**calculated_payload;
if let Some(percentage) = percentage_dimension_mix(&simplified, evaluation_context) {
return AbsolutizedCalculation::Percentage(percentage);
}
@@ -4540,7 +4554,7 @@ fn computed_calculation_from_simplified(
if Arc::ptr_eq(&simplified, root) {
return AbsolutizedCalculation::Unchanged;
}
- AbsolutizedCalculation::Value(StyleValueData::Calculated {
+ AbsolutizedCalculation::Value(StyleValueData::Calculated(StyleValueBox::new(CalculatedPayload {
rust_calculation: CalcNodeHandle::from_arc(simplified),
resolve_as_is_number: *resolve_as_is_number,
resolve_as_base: *resolve_as_base,
@@ -4549,7 +4563,7 @@ fn computed_calculation_from_simplified(
percentages_resolve_as: *percentages_resolve_as,
resolve_numbers_as_integers: *resolve_numbers_as_integers,
accepted_ranges: accepted_ranges.clone(),
- })
+ })))
}
/// Replaces the anchor() and anchor-size() functions of a computed `<length-percentage>` with their fallback values,
@@ -4563,19 +4577,21 @@ pub(crate) fn substitute_unresolvable_anchor_functions(
) -> Option<Option<RetainedStyleValueData>> {
use crate::css::style_value::StyleValueData;
match value {
- StyleValueData::Anchor { fallback_value, .. } | StyleValueData::AnchorSize { fallback_value, .. } => {
+ StyleValueData::Anchor(_) | StyleValueData::AnchorSize(_) => {
+ let (_, _, fallback_value) = value.anchor_name_and_fallback().unwrap();
let fallback = fallback_value.optional_data()?;
Some(Some(
substitute_unresolvable_anchor_functions(fallback)?.unwrap_or_else(|| fallback_value.clone()),
))
}
- StyleValueData::Calculated {
- rust_calculation,
- resolve_as_is_number,
- resolve_as_base,
- has_percentages_resolve_as,
- ..
- } if rust_calculation.node().contains_anchor_function() => {
+ StyleValueData::Calculated(calculated) if calculated.rust_calculation.node().contains_anchor_function() => {
+ let CalculatedPayload {
+ rust_calculation,
+ resolve_as_is_number,
+ resolve_as_base,
+ has_percentages_resolve_as,
+ ..
+ } = &**calculated;
let root = rust_calculation.node_arc();
let mut externals = Vec::new();
collect_external_resolutions(&root, &mut externals);
@@ -4612,9 +4628,9 @@ pub(crate) fn substitute_unresolvable_anchor_functions(
Some(Some(match computed {
AbsolutizedCalculation::Unchanged => unreachable!("substituting an anchor function changes the tree"),
AbsolutizedCalculation::Percentage(value) => {
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Percentage { value }))
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Percentage { value }))
}
- AbsolutizedCalculation::Value(value) => RetainedStyleValueData::from_arc(Arc::new(value)),
+ AbsolutizedCalculation::Value(value) => RetainedStyleValueData::from_arc(StyleValueArc::new(value)),
}))
}
_ => Some(None),
@@ -4627,7 +4643,10 @@ pub extern "C" fn rust_style_value_contains_anchor_function(value: &crate::css::
use crate::css::style_value::StyleValueData;
match value {
StyleValueData::Anchor { .. } | StyleValueData::AnchorSize { .. } => true,
- StyleValueData::Calculated { rust_calculation, .. } => rust_calculation.node().contains_anchor_function(),
+ StyleValueData::Calculated(calculated_payload) => {
+ let CalculatedPayload { rust_calculation, .. } = &**calculated_payload;
+ rust_calculation.node().contains_anchor_function()
+ }
_ => false,
}
}
@@ -4657,7 +4676,10 @@ fn length_percentage_calc_node(value: &crate::css::style_value::StyleValueData)
unit: *unit,
}))),
StyleValueData::Percentage { value } => Some(Arc::new(CalcNode::Numeric(CalcNumericValue::Percentage(*value)))),
- StyleValueData::Calculated { rust_calculation, .. } => Some(rust_calculation.node_arc()),
+ StyleValueData::Calculated(calculated_payload) => {
+ let CalculatedPayload { rust_calculation, .. } = &**calculated_payload;
+ Some(rust_calculation.node_arc())
+ }
_ => None,
}
}
@@ -4718,16 +4740,16 @@ pub(crate) fn flipped_edge_offset(
pub(crate) fn serialize_math_function_pieces(
calculated: &crate::css::style_value::StyleValueData,
resolved_mode: bool,
-) -> Vec<FfiCalcSerializationPiece> {
- let crate::css::style_value::StyleValueData::Calculated {
+) -> Vec<CalcSerializationPiece> {
+ let crate::css::style_value::StyleValueData::Calculated(calculated_payload) = calculated else {
+ unreachable!("calc serialization requires calculated value data");
+ };
+ let CalculatedPayload {
rust_calculation,
resolve_numbers_as_integers,
accepted_ranges,
..
- } = calculated
- else {
- unreachable!("calc serialization requires calculated value data");
- };
+ } = &**calculated_payload;
let root = rust_calculation.node_arc();
let mut serializer = CalcSerializer {
pieces: Vec::new(),
@@ -4744,16 +4766,16 @@ pub(crate) fn serialize_math_function_pieces(
pub(crate) fn serialize_bare_calculation_pieces(
calculated: &crate::css::style_value::StyleValueData,
resolved_mode: bool,
-) -> Vec<FfiCalcSerializationPiece> {
- let crate::css::style_value::StyleValueData::Calculated {
+) -> Vec<CalcSerializationPiece> {
+ let crate::css::style_value::StyleValueData::Calculated(calculated_payload) = calculated else {
+ unreachable!("calc serialization requires calculated value data");
+ };
+ let CalculatedPayload {
rust_calculation,
resolve_numbers_as_integers,
accepted_ranges,
..
- } = calculated
- else {
- unreachable!("calc serialization requires calculated value data");
- };
+ } = &**calculated_payload;
let root = rust_calculation.node_arc();
let mut serializer = CalcSerializer {
pieces: Vec::new(),
@@ -4945,9 +4967,10 @@ pub extern "C" fn rust_calc_equals(
) -> bool {
use crate::css::style_value::StyleValueData;
let tree_of = |data: &StyleValueData| {
- let StyleValueData::Calculated { rust_calculation, .. } = data else {
+ let StyleValueData::Calculated(calculated_payload) = data else {
unreachable!("rust_calc_equals requires calculated value data");
};
+ let CalculatedPayload { rust_calculation, .. } = &**calculated_payload;
rust_calculation.node_arc()
};
let first_tree = tree_of(first);
@@ -5079,16 +5102,16 @@ fn append_reification_node(
pub extern "C" fn rust_calc_describe_for_typed_om(
calculated: &crate::css::style_value::StyleValueData,
) -> FfiCalcReification {
- let crate::css::style_value::StyleValueData::Calculated {
+ let crate::css::style_value::StyleValueData::Calculated(calculated_payload) = calculated else {
+ unreachable!("rust_calc_describe_for_typed_om requires calculated value data");
+ };
+ let CalculatedPayload {
rust_calculation,
has_percentages_resolve_as,
resolve_as_is_number,
resolve_as_base,
..
- } = calculated
- else {
- unreachable!("rust_calc_describe_for_typed_om requires calculated value data");
- };
+ } = &**calculated_payload;
let percentage_leaf_type = percentage_leaf_type_for(resolve_as_from_fields(
*has_percentages_resolve_as,
*resolve_as_is_number,
diff --git a/Libraries/LibWeb/Rust/src/css/calc_size.rs b/Libraries/LibWeb/Rust/src/css/calc_size.rs
index e2e37c1c30e..3ad8c4b3685 100644
--- a/Libraries/LibWeb/Rust/src/css/calc_size.rs
+++ b/Libraries/LibWeb/Rust/src/css/calc_size.rs
@@ -15,7 +15,8 @@ use crate::css::parser::value_parser::{
};
use crate::css::property_metadata::{property_accepted_keywords, property_accepted_value_types};
use crate::css::serialize::{StringUnits, with_fly_string_units};
-use crate::css::style_value::{CssString, RetainedStyleValueData, StyleValueData};
+use crate::css::style_value::FunctionPayload;
+use crate::css::style_value::{CssString, RetainedStyleValueData, StyleValueBox, StyleValueData};
use crate::css::value_codes::{VALUE_TYPE_FIT_CONTENT, VALUE_TYPE_LENGTH};
const COMMA: u8 = 1;
@@ -49,10 +50,10 @@ pub(crate) fn parse_calc_size(context: &ParseContext, property: u16, value: &Com
/// The calc-size() function value with the given basis and calculation.
pub(crate) fn calc_size_function(basis: StyleValueData, calculation: StyleValueData) -> StyleValueData {
- StyleValueData::Function {
+ StyleValueData::Function(StyleValueBox::new(FunctionPayload {
name: CssString::from_utf16(&"calc-size".encode_utf16().collect::<Vec<_>>()),
value: RetainedStyleValueData::from_owned(value_list(vec![basis, calculation], COMMA, false)),
- }
+ }))
}
// <calc-size-basis> = [ <size-keyword> | <calc-sum> | <calc-size()> | any ]
@@ -103,9 +104,10 @@ fn parse_calc_sum(
/// The basis and calculation of a calc-size() function value.
pub(crate) fn calc_size_arguments(value: &StyleValueData) -> Option<(&StyleValueData, &StyleValueData)> {
- let StyleValueData::Function { name, value } = value else {
+ let StyleValueData::Function(function_payload) = value else {
return None;
};
+ let FunctionPayload { name, value } = &**function_payload;
if !is_calc_size_function_name(name) {
return None;
}
diff --git a/Libraries/LibWeb/Rust/src/css/cascaded_properties.rs b/Libraries/LibWeb/Rust/src/css/cascaded_properties.rs
index 621147f07e2..f3458aef4fb 100644
--- a/Libraries/LibWeb/Rust/src/css/cascaded_properties.rs
+++ b/Libraries/LibWeb/Rust/src/css/cascaded_properties.rs
@@ -381,9 +381,8 @@ pub(crate) struct CascadeResolutionContext<'a> {
}
/// Length, tree-counting and color inputs used when evaluating style queries.
-#[repr(C)]
#[derive(Clone, Copy)]
-pub struct FfiStyleQueryInputs {
+pub struct StyleQueryInputs {
pub length: crate::css::style_compute::FfiLengthResolutionContext,
pub tree_counting: Option<(u64, u64)>,
/// A PreferredColorScheme code.
@@ -392,7 +391,7 @@ pub struct FfiStyleQueryInputs {
pub current_color: u32,
}
-impl FfiStyleQueryInputs {
+impl StyleQueryInputs {
pub(crate) fn color_input(&self) -> crate::css::color_resolution::ColorResolutionInput<'_> {
crate::css::color_resolution::ColorResolutionInput {
scheme: Some(self.color_scheme),
@@ -418,7 +417,7 @@ pub(crate) fn resolve_declared_custom_properties(
Option<Arc<CustomPropertyStore>>,
crate::css::custom_properties::RegisteredValueReads,
) {
- let names = &store.declared_names;
+ let names = store.declared_names();
let mut environment = crate::css::custom_properties::prepare_var_resolution_environment(
resolution_context.attributes,
resolution_context.custom_functions,
@@ -447,4 +446,7 @@ pub(crate) fn resolve_declared_custom_properties(
}
/// Sentinel passed when cascading for an element rather than a pseudo-element.
+/// NB: An `extern "C"` function that can be handed this takes it as a `u32`. rustc assumes a narrower
+/// parameter arrives zero-extended, which x86-64 callers need not do: GCC 16 sign-extends one, so
+/// `u8::MAX` would arrive unequal to itself.
pub(crate) const NO_PSEUDO_ELEMENT: u8 = u8::MAX;
diff --git a/Libraries/LibWeb/Rust/src/css/color_interpolation.rs b/Libraries/LibWeb/Rust/src/css/color_interpolation.rs
index 5c004954023..771bccf63a9 100644
--- a/Libraries/LibWeb/Rust/src/css/color_interpolation.rs
+++ b/Libraries/LibWeb/Rust/src/css/color_interpolation.rs
@@ -7,13 +7,13 @@
//! CSS color interpolation over resolved color snapshots.
// Color values use the same thread-confined shared graph as the rest of the style core.
-#![allow(clippy::arc_with_non_send_sync)]
-use std::sync::Arc;
+use crate::css::style_value::ColorFunctionPayload;
+use crate::css::style_value_arc::StyleValueArc;
use crate::css::color_conversion;
use crate::css::color_resolution::make_powerless_hue_missing;
-use crate::css::style_value::{ColorBase, RetainedStyleValueData, StyleValueData};
+use crate::css::style_value::{ColorBase, RetainedStyleValueData, StyleValueBox, StyleValueData};
use crate::css::value_codes::*;
pub(crate) struct ResolvedColor {
@@ -197,11 +197,11 @@ fn substitute_missing_components(
}
fn retained_number(value: f32) -> RetainedStyleValueData {
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Number { value: value as f64 }))
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Number { value: value as f64 }))
}
fn retained_none() -> RetainedStyleValueData {
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Keyword {
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Keyword {
keyword: crate::css::style_compute::none_keyword(),
}))
}
@@ -239,7 +239,7 @@ fn make_result(color_type: u8, components: [f32; 4], missing: [bool; 4]) -> Styl
),
_ => (color_type, components, missing),
};
- StyleValueData::ColorFunction {
+ StyleValueData::ColorFunction(StyleValueBox::new(ColorFunctionPayload {
color_base: ColorBase {
has_color_type: true,
color_type,
@@ -252,7 +252,7 @@ fn make_result(color_type: u8, components: [f32; 4], missing: [bool; 4]) -> Styl
has_name: false,
name: unsafe { crate::css::style_value::CssString::from_leaked_raw(0) },
origin_color: RetainedStyleValueData::none(),
- }
+ }))
}
// https://drafts.csswg.org/css-color-4/#interpolation
diff --git a/Libraries/LibWeb/Rust/src/css/color_resolution.rs b/Libraries/LibWeb/Rust/src/css/color_resolution.rs
index bbe345b4aae..cf10a76a2d1 100644
--- a/Libraries/LibWeb/Rust/src/css/color_resolution.rs
+++ b/Libraries/LibWeb/Rust/src/css/color_resolution.rs
@@ -10,9 +10,11 @@
// The FFI consumer of to_color() lands with the FFI flip.
// Color values use the same thread-confined shared graph as the rest of the style core.
-#![allow(clippy::arc_with_non_send_sync)]
-use std::sync::Arc;
+use crate::css::style_value::{
+ CalculatedPayload, ColorFunctionPayload, ColorMixPayload, LightDarkPayload, StyleValueBox,
+};
+use crate::css::style_value_arc::StyleValueArc;
use crate::css::calc::{
ANGLE_UNIT_CANONICAL_RATIOS, ResolveAs, resolve_as_from_fields, resolve_calculated_angle_with_channels,
@@ -286,25 +288,6 @@ impl Rgba {
}
}
-pub(crate) fn resolved_srgb_style_value(color: Rgba) -> StyleValueData {
- StyleValueData::ColorFunction {
- color_base: ColorBase {
- has_color_type: true,
- color_type: color_conversion::RGB,
- color_syntax: 0,
- },
- channel_0: retained_value(StyleValueData::Number { value: color.r.into() }),
- channel_1: retained_value(StyleValueData::Number { value: color.g.into() }),
- channel_2: retained_value(StyleValueData::Number { value: color.b.into() }),
- alpha: retained_value(StyleValueData::Number {
- value: f64::from(color.a) / 255.0,
- }),
- has_name: false,
- name: CssString::none(),
- origin_color: retained_null(),
- }
-}
-
/// nth_digit(745, 1) is '5'; digit 3 is the hundreds place.
fn nth_digit(mut value: u32, mut digit: u8) -> u8 {
debug_assert!(value < 1000);
@@ -764,15 +747,15 @@ const BASE_TYPE_ANGLE: usize = 1;
/// The stored resolve-as target of a Calculated variant, or None for any other variant.
fn calculated_resolve_as(value: &StyleValueData) -> Option<ResolveAs> {
- let StyleValueData::Calculated {
+ let StyleValueData::Calculated(calculated_payload) = value else {
+ return None;
+ };
+ let CalculatedPayload {
has_percentages_resolve_as,
resolve_as_is_number,
resolve_as_base,
..
- } = value
- else {
- return None;
- };
+ } = &**calculated_payload;
resolve_as_from_fields(*has_percentages_resolve_as, *resolve_as_is_number, *resolve_as_base)
}
@@ -813,7 +796,8 @@ pub(crate) fn resolve_hue(style_value: &StyleValueData, input: &ColorResolutionI
}
Some(0.0)
}
- StyleValueData::Calculated { resolved_type, .. } => {
+ StyleValueData::Calculated(calculated_payload) => {
+ let CalculatedPayload { resolved_type, .. } = &**calculated_payload;
let resolve_as = calculated_resolve_as(style_value);
let numeric_type = resolved_type.to_calc();
if numeric_type.matches_number(resolve_as) {
@@ -849,7 +833,8 @@ pub(crate) fn resolve_with_reference_value(
}
Some(0.0)
}
- StyleValueData::Calculated { resolved_type, .. } => {
+ StyleValueData::Calculated(calculated_payload) => {
+ let CalculatedPayload { resolved_type, .. } = &**calculated_payload;
let resolve_as = calculated_resolve_as(style_value);
let numeric_type = resolved_type.to_calc();
if numeric_type.matches_number(resolve_as) {
@@ -887,7 +872,8 @@ pub(crate) fn resolve_alpha(style_value: &StyleValueData, input: &ColorResolutio
}
Some(1.0)
}
- StyleValueData::Calculated { resolved_type, .. } => {
+ StyleValueData::Calculated(calculated_payload) => {
+ let CalculatedPayload { resolved_type, .. } = &**calculated_payload;
let resolve_as = calculated_resolve_as(style_value);
let numeric_type = resolved_type.to_calc();
if numeric_type.matches_number(resolve_as) {
@@ -907,7 +893,7 @@ pub(crate) fn resolve_alpha(style_value: &StyleValueData, input: &ColorResolutio
// Shared-graph retained-value constructors, mirroring make_result() in color_interpolation.rs.
fn retained_value(value: StyleValueData) -> RetainedStyleValueData {
- RetainedStyleValueData::from_arc(Arc::new(value))
+ RetainedStyleValueData::from_arc(StyleValueArc::new(value))
}
fn retained_null() -> RetainedStyleValueData {
@@ -1039,7 +1025,10 @@ fn construct_color(color_type: u8, c1: f64, c2: f64, c3: f64, alpha: f64) -> Opt
}
fn color_function_to_color(value: &StyleValueData, input: &ColorResolutionInput) -> Option<Rgba> {
- let StyleValueData::ColorFunction {
+ let StyleValueData::ColorFunction(color_function_payload) = value else {
+ return None;
+ };
+ let ColorFunctionPayload {
color_base,
channel_0,
channel_1,
@@ -1047,10 +1036,7 @@ fn color_function_to_color(value: &StyleValueData, input: &ColorResolutionInput)
alpha,
origin_color,
..
- } = value
- else {
- return None;
- };
+ } = &**color_function_payload;
if !color_base.has_color_type {
return None;
}
@@ -1202,7 +1188,10 @@ fn set_channels_for_target(
/// color-function origin's channels without going through the u8 sRGB representation. The
/// C++ empty CalculationResolutionContext maps to no channels and no length context.
fn resolve_origin_native_channels(origin: &StyleValueData) -> Option<(u8, Components, [bool; 4])> {
- let StyleValueData::ColorFunction {
+ let StyleValueData::ColorFunction(color_function_payload) = origin else {
+ return None;
+ };
+ let ColorFunctionPayload {
color_base,
channel_0,
channel_1,
@@ -1210,10 +1199,7 @@ fn resolve_origin_native_channels(origin: &StyleValueData) -> Option<(u8, Compon
alpha,
origin_color,
..
- } = origin
- else {
- return None;
- };
+ } = &**color_function_payload;
if origin_color.optional_data().is_some() {
return None;
}
@@ -1363,7 +1349,10 @@ fn make_powerless_target_hue_missing(
/// function into an absolute one whose channels are plain numbers (or `none` keywords).
// https://drafts.csswg.org/css-color-5/#resolving-rcs
pub(crate) fn resolve_relative_form(value: &StyleValueData, input: &ColorResolutionInput) -> Option<StyleValueData> {
- let StyleValueData::ColorFunction {
+ let StyleValueData::ColorFunction(color_function_payload) = value else {
+ return None;
+ };
+ let ColorFunctionPayload {
color_base,
channel_0,
channel_1,
@@ -1371,10 +1360,7 @@ pub(crate) fn resolve_relative_form(value: &StyleValueData, input: &ColorResolut
alpha,
origin_color,
..
- } = value
- else {
- return None;
- };
+ } = &**color_function_payload;
// The C++ code VERIFYs both of these.
let origin = origin_color.optional_data()?;
if !color_base.has_color_type {
@@ -1438,16 +1424,18 @@ pub(crate) fn resolve_relative_form(value: &StyleValueData, input: &ColorResolut
}
};
- Some(StyleValueData::ColorFunction {
- color_base: *color_base,
- channel_0: retained_value(resolve_channel(channel_0, 0)),
- channel_1: retained_value(resolve_channel(channel_1, 1)),
- channel_2: retained_value(resolve_channel(channel_2, 2)),
- alpha: retained_value(resolved_alpha),
- has_name: false,
- name: CssString::none(),
- origin_color: retained_null(),
- })
+ Some(StyleValueData::ColorFunction(StyleValueBox::new(
+ ColorFunctionPayload {
+ color_base: *color_base,
+ channel_0: retained_value(resolve_channel(channel_0, 0)),
+ channel_1: retained_value(resolve_channel(channel_1, 1)),
+ channel_2: retained_value(resolve_channel(channel_2, 2)),
+ alpha: retained_value(resolved_alpha),
+ has_name: false,
+ name: CssString::none(),
+ origin_color: retained_null(),
+ },
+ )))
}
/// Resolves alpha(from <color> / <alpha>) to an absolute color in the color space of its origin color.
@@ -1466,11 +1454,8 @@ fn resolve_relative_alpha(
effective_origin = current_color_value;
}
let resolved_origin_storage;
- if let StyleValueData::ColorFunction {
- origin_color: nested_origin,
- ..
- } = effective_origin
- && nested_origin.optional_data().is_some()
+ if let StyleValueData::ColorFunction(color_function_payload) = effective_origin
+ && color_function_payload.origin_color.optional_data().is_some()
{
resolved_origin_storage = resolve_relative_form(effective_origin, input)?;
effective_origin = &resolved_origin_storage;
@@ -1521,20 +1506,22 @@ fn resolve_relative_alpha(
}
};
- Some(StyleValueData::ColorFunction {
- color_base: ColorBase {
- has_color_type: true,
- color_type,
- color_syntax: crate::css::value_codes::COLOR_SYNTAX_MODERN,
+ Some(StyleValueData::ColorFunction(StyleValueBox::new(
+ ColorFunctionPayload {
+ color_base: ColorBase {
+ has_color_type: true,
+ color_type,
+ color_syntax: crate::css::value_codes::COLOR_SYNTAX_MODERN,
+ },
+ channel_0: retained_value(component(0)),
+ channel_1: retained_value(component(1)),
+ channel_2: retained_value(component(2)),
+ alpha: retained_value(resolved_alpha),
+ has_name: false,
+ name: CssString::none(),
+ origin_color: retained_null(),
},
- channel_0: retained_value(component(0)),
- channel_1: retained_value(component(1)),
- channel_2: retained_value(component(2)),
- alpha: retained_value(resolved_alpha),
- has_name: false,
- name: CssString::none(),
- origin_color: retained_null(),
- })
+ )))
}
/// The computed value form of an absolute rgb(), hsl() or hwb() function: the same color as
@@ -1542,17 +1529,17 @@ fn resolve_relative_alpha(
// https://drafts.csswg.org/css-color-4/#resolving-sRGB-values
pub(crate) fn relative_color_computed_value_form(value: StyleValueData) -> StyleValueData {
use color_conversion as ct;
- let StyleValueData::ColorFunction {
+ let StyleValueData::ColorFunction(color_function_payload) = &value else {
+ return value;
+ };
+ let ColorFunctionPayload {
color_base,
channel_0,
channel_1,
channel_2,
alpha,
..
- } = &value
- else {
- return value;
- };
+ } = &**color_function_payload;
let color_type = color_base.color_type;
if !matches!(color_type, ct::RGB | ct::HSL | ct::HWB) {
return value;
@@ -1600,7 +1587,7 @@ pub(crate) fn relative_color_computed_value_form(value: StyleValueData) -> Style
})
};
let [channel_0, channel_1, channel_2] = channels;
- StyleValueData::ColorFunction {
+ StyleValueData::ColorFunction(StyleValueBox::new(ColorFunctionPayload {
color_base: ColorBase {
has_color_type: true,
color_type: ct::SRGB,
@@ -1613,7 +1600,7 @@ pub(crate) fn relative_color_computed_value_form(value: StyleValueData) -> Style
has_name: false,
name: CssString::none(),
origin_color: retained_null(),
- }
+ }))
}
/// The resolved value of a relative color function against a style: its relative form in its
@@ -1630,7 +1617,7 @@ pub unsafe extern "C" fn rust_relative_color_resolved_value(
// SAFETY: Guaranteed by the caller.
let resolution_input = unsafe { ColorResolutionInput::for_ffi_style(style) };
match resolve_relative_form(value, &resolution_input) {
- Some(resolved) => Arc::into_raw(Arc::new(relative_color_computed_value_form(resolved))),
+ Some(resolved) => StyleValueArc::into_raw(StyleValueArc::new(relative_color_computed_value_form(resolved))),
None => core::ptr::null(),
}
}
@@ -1652,7 +1639,7 @@ pub unsafe extern "C" fn rust_color_mix_resolved_value(
// SAFETY: Guaranteed by the caller.
let resolution_input = unsafe { ColorResolutionInput::for_ffi_style(style) };
match resolve_color_mix(value, &resolution_input) {
- Some(resolved) => Arc::into_raw(Arc::new(resolved)),
+ Some(resolved) => StyleValueArc::into_raw(StyleValueArc::new(resolved)),
None => core::ptr::null(),
}
}
@@ -1708,11 +1695,8 @@ fn extract_channels_and_missing_slots(
}
let resolved_origin_storage;
- if let StyleValueData::ColorFunction {
- origin_color: nested_origin,
- ..
- } = effective_origin
- && nested_origin.optional_data().is_some()
+ if let StyleValueData::ColorFunction(color_function_payload) = effective_origin
+ && color_function_payload.origin_color.optional_data().is_some()
{
resolved_origin_storage = resolve_relative_form(effective_origin, input)?;
effective_origin = &resolved_origin_storage;
@@ -1921,7 +1905,10 @@ fn resolve_native_color_components(
input: &ColorResolutionInput,
) -> Option<(u8, Components)> {
use color_conversion as ct;
- let StyleValueData::ColorFunction {
+ let StyleValueData::ColorFunction(color_function_payload) = style_value else {
+ return None;
+ };
+ let ColorFunctionPayload {
color_base,
channel_0,
channel_1,
@@ -1929,10 +1916,7 @@ fn resolve_native_color_components(
alpha,
origin_color,
..
- } = style_value
- else {
- return None;
- };
+ } = &**color_function_payload;
if !color_base.has_color_type || origin_color.optional_data().is_some() {
return None;
}
@@ -2018,8 +2002,8 @@ pub(crate) fn resolve_color_for_interpolation(
) -> Option<ResolvedColor> {
let resolved_relative_storage;
let mut style_value = input_value;
- if let StyleValueData::ColorFunction { origin_color, .. } = input_value
- && origin_color.optional_data().is_some()
+ if let StyleValueData::ColorFunction(color_function_payload) = input_value
+ && color_function_payload.origin_color.optional_data().is_some()
{
resolved_relative_storage = resolve_relative_form(input_value, input)?;
style_value = &resolved_relative_storage;
@@ -2040,17 +2024,17 @@ pub(crate) fn resolve_color_for_interpolation(
}
if let Some((color_type, components)) = resolve_native_color_components(style_value, input) {
- let StyleValueData::ColorFunction {
+ let StyleValueData::ColorFunction(color_function_payload) = style_value else {
+ // resolve_native_color_components() only accepts color functions.
+ return None;
+ };
+ let ColorFunctionPayload {
channel_0,
channel_1,
channel_2,
alpha,
..
- } = style_value
- else {
- // resolve_native_color_components() only accepts color functions.
- return None;
- };
+ } = &**color_function_payload;
return Some(ResolvedColor {
color_type,
components,
@@ -2081,15 +2065,15 @@ pub(crate) fn resolve_color_for_interpolation(
// https://drafts.csswg.org/css-color-5/#color-mix-result
pub(crate) fn resolve_color_mix(value: &StyleValueData, input: &ColorResolutionInput) -> Option<StyleValueData> {
- let StyleValueData::ColorMix {
+ let StyleValueData::ColorMix(color_mix_payload) = value else {
+ return None;
+ };
+ let ColorMixPayload {
color_interpolation_method,
colors,
percentages,
..
- } = value
- else {
- return None;
- };
+ } = &**color_mix_payload;
// An absent method interpolates in the rectangular Oklab space.
let default_method = StyleValueData::ColorInterpolationMethod {
@@ -2157,7 +2141,8 @@ pub(crate) fn to_color(value: &StyleValueData, input: &ColorResolutionInput) ->
}
// https://drafts.csswg.org/css-color-5/#funcdef-light-dark
// A missing scheme takes the light branch.
- StyleValueData::LightDark { light, dark, .. } => {
+ StyleValueData::LightDark(light_dark_payload) => {
+ let LightDarkPayload { light, dark, .. } = &**light_dark_payload;
if input.scheme == Some(PREFERRED_COLOR_SCHEME_DARK) {
to_color(dark.data(), input)
} else {
@@ -2327,7 +2312,7 @@ mod tests {
fn color_function(color_type: u8, channels: [StyleValueData; 3], alpha: Option<StyleValueData>) -> StyleValueData {
let [c0, c1, c2] = channels;
- StyleValueData::ColorFunction {
+ StyleValueData::ColorFunction(StyleValueBox::new(ColorFunctionPayload {
color_base: ColorBase {
has_color_type: true,
color_type,
@@ -2340,7 +2325,7 @@ mod tests {
has_name: false,
name: CssString::none(),
origin_color: retained_null(),
- }
+ }))
}
#[test]
@@ -2472,7 +2457,7 @@ mod tests {
);
assert_eq!(to_color(&keyword_value(keyword::AUTO), &EMPTY_INPUT), None);
- let light_dark = StyleValueData::LightDark {
+ let light_dark = StyleValueData::LightDark(StyleValueBox::new(LightDarkPayload {
color_base: ColorBase {
has_color_type: false,
color_type: 0,
@@ -2488,14 +2473,14 @@ mod tests {
[number(0.0), number(0.0), number(0.0)],
None,
)),
- };
+ }));
assert_eq!(to_color(&light_dark, &EMPTY_INPUT), Some(Rgba::WHITE));
assert_eq!(to_color(&light_dark, &dark_input), Some(Rgba::BLACK));
}
#[test]
fn to_color_mixes_srgb_endpoints() {
- let mix = StyleValueData::ColorMix {
+ let mix = StyleValueData::ColorMix(StyleValueBox::new(ColorMixPayload {
color_base: ColorBase {
has_color_type: false,
color_type: 0,
@@ -2520,7 +2505,7 @@ mod tests {
)),
]),
percentages: RetainedStyleValueDataList::from_retained_values(vec![retained_null(), retained_null()]),
- };
+ }));
// A 50/50 sRGB mix of black and white; 127.5 rounds half-to-even to 128 through the
// sRGB construction arm.
assert_eq!(to_color(&mix, &EMPTY_INPUT), Some(rgb(128, 128, 128)));
diff --git a/Libraries/LibWeb/Rust/src/css/computed_longhand_table.rs b/Libraries/LibWeb/Rust/src/css/computed_longhand_table.rs
index 5b22796b209..411ce79a402 100644
--- a/Libraries/LibWeb/Rust/src/css/computed_longhand_table.rs
+++ b/Libraries/LibWeb/Rust/src/css/computed_longhand_table.rs
@@ -4,109 +4,23 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-// Like the style values it retains, the table is shared across the FFI boundary but remains
-// confined to the thread owning the C++ style objects.
-#![allow(clippy::arc_with_non_send_sync)]
+//! What a style records beside its longhand values: whether each was important, inherited or
+//! evaluated, the dependency flags, the metadata the host settles beside them, and the recorded
+//! specified values helpers.
-//! The computed longhand table: the source of truth for one style drive's
-//! computed values, one slot per longhand.
-//!
-//! Every store a C++ `ComputedStyleWorkingSet` funnel performs lands
-//! here as a strong reference to the shared style value data; the C++ side
-//! keeps only a lazily filled wrapper cache over these slots, minting a
-//! wrapper when a caller asks for one. A sparse sidecar remembers which
-//! longhands took their value from a declaration that carries style sheet
-//! context, together with the declaration's cascade source slot. The C++
-//! The C++ `ComputedStyleWorkingSet` creates the table and freezes it when
-//! the drive completes; the frozen table is then shared
-//! by reference count with every `ComputedValues` built from those
-//! properties and with the style record publication that interns it.
-
-use smallvec::SmallVec;
use std::ffi::c_void;
-use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
-use std::sync::{Arc, OnceLock};
-use crate::css::animated_overlay::AnimatedOverlay;
-use crate::css::animated_overlay::overlay_wins;
-use crate::css::ffi_stats;
-use crate::css::host_shared::{HostShared, SharedPayload};
-use crate::css::property_metadata::{
- FIRST_LONGHAND_PROPERTY_ID, LAST_LONGHAND_PROPERTY_ID, property_id, property_is_inherited,
-};
-use crate::css::style_value::retained_value_depends_on_current_color;
+use crate::css::property_metadata::{FIRST_LONGHAND_PROPERTY_ID, LAST_LONGHAND_PROPERTY_ID, property_is_inherited};
use crate::css::style_value::{RetainedStyleValueData, StyleValueData};
pub(crate) const LONGHAND_COUNT: usize = (LAST_LONGHAND_PROPERTY_ID - FIRST_LONGHAND_PROPERTY_ID + 1) as usize;
-fn is_current_color_keyword(value: &StyleValueData) -> bool {
+pub(crate) fn is_current_color_keyword(value: &StyleValueData) -> bool {
matches!(value, StyleValueData::Keyword { keyword } if *keyword == crate::css::style_compute::keyword::CURRENTCOLOR)
}
pub(crate) const LONGHAND_BITMAP_BYTES: usize = LONGHAND_COUNT.div_ceil(8);
-/// Mixes one slot's value content hash with the slot index, so that a sum over the slots is
-/// order-sensitive while any one slot's share can still be subtracted and replaced.
-const fn mix_slot_hash(slot: usize, content: u64) -> u64 {
- (content ^ (slot as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15))
- .wrapping_mul(0x2545_F491_4F6C_DD1D)
- .rotate_left((slot as u32) & 63)
-}
-
-pub(crate) fn longhand_slot_hash(slot: usize, value: Option<&StyleValueData>) -> u64 {
- mix_slot_hash(slot, crate::css::style_value::style_value_content_hash(value))
-}
-
-/// The memoized sum of a table's per-slot hashes.
-///
-/// Every write but one goes through `&mut self` on an unfrozen table nobody else can see. The
-/// exception is `ComputedLonghandTable::slot_hash_sum`, which fills the memo through `&self` on a
-/// frozen table that every worker seeding a drive from it shares. That is not a race in value -
-/// the sum is a pure function of immutable slots, so two workers store the same number - but it
-/// has to be spelled with atomics for the compiler to agree, and it is cheaper than the `Cell`
-/// pair it replaces was: `adjust_slot_hash_sum` runs per slot write, and a relaxed store is one
-/// instruction.
-#[derive(Clone, Default)]
-struct MemoizedHashSum {
- sum: crate::fork::ForkCopied<AtomicU64>,
- known: crate::fork::ForkCopied<AtomicBool>,
-}
-
-impl MemoizedHashSum {
- fn get(&self) -> Option<u64> {
- // Acquire pairs with the release below: a reader that sees the memo filled sees the sum.
- self.known
- .load(Ordering::Acquire)
- .then(|| self.sum.load(Ordering::Relaxed))
- }
-
- fn set(&self, sum: Option<u64>) {
- match sum {
- Some(sum) => {
- self.sum.store(sum, Ordering::Relaxed);
- self.known.store(true, Ordering::Release);
- }
- None => self.known.store(false, Ordering::Release),
- }
- }
-}
-
-/// One sparse inheritance-dependent specified value, exposed to C++ as the
-/// borrowed span behind a style's inheritance-dependent value view.
-#[repr(C)]
-#[derive(Clone)]
-pub struct FfiTableInheritanceDependentValue {
- pub property: u16,
- pub value: *const c_void,
-}
-
-// SAFETY: `value` borrows the `StyleValueData` the neighboring
-// `inheritance_dependent` entry retains; `RetainedStyleValueData` is itself
-// `Send + Sync` because a style value is immutable and its count is an
-// `Arc`'s. This view owns nothing and is rebuilt, never mutated in place.
-unsafe impl Send for FfiTableInheritanceDependentValue {}
-unsafe impl Sync for FfiTableInheritanceDependentValue {}
-
/// The effective value of one longhand: the value data pointer together with
/// which source produced it, so the C++ side can preserve wrapper identity
/// for overlay values and stamp style sheet context only onto table mints.
@@ -120,6 +34,28 @@ pub const EFFECTIVE_LONGHAND_SOURCE_TABLE: u8 = 0;
pub const EFFECTIVE_LONGHAND_SOURCE_OVERLAY: u8 = 1;
pub const EFFECTIVE_LONGHAND_SOURCE_SPECIFIED: u8 = 2;
+/// The longhands that inherit by default, by slot.
+const INHERITED_LONGHAND_BITS: [u8; LONGHAND_BITMAP_BYTES] = {
+ use crate::css::property_metadata::{FIRST_INHERITED_PROPERTY_ID, LAST_INHERITED_PROPERTY_ID};
+ let mut bits = [0; LONGHAND_BITMAP_BYTES];
+ let mut property = FIRST_INHERITED_PROPERTY_ID;
+ while property <= LAST_INHERITED_PROPERTY_ID {
+ let index = (property - FIRST_LONGHAND_PROPERTY_ID) as usize;
+ bits[index / 8] |= 1 << (index % 8);
+ property += 1;
+ }
+ bits
+};
+
+/// The bit of `property_id` in a bitmap of longhands.
+fn slot_index(property_id: u16) -> usize {
+ assert!(
+ (FIRST_LONGHAND_PROPERTY_ID..=LAST_LONGHAND_PROPERTY_ID).contains(&property_id),
+ "longhand bitmap indices are longhand property identifiers"
+ );
+ (property_id - FIRST_LONGHAND_PROPERTY_ID) as usize
+}
+
fn bitmap_bit(bits: &[u8; LONGHAND_BITMAP_BYTES], index: usize) -> bool {
bits[index / 8] & (1 << (index % 8)) != 0
}
@@ -132,662 +68,88 @@ fn set_bitmap_bit(bits: &mut [u8; LONGHAND_BITMAP_BYTES], index: usize, value: b
}
}
-/// Where `index` sits in a change list kept in slot order: the number of changed slots below it.
-/// Locating a change this way keeps a drive's cost linear in the slots it writes.
-fn bitmap_rank(bits: &[u8; LONGHAND_BITMAP_BYTES], index: usize) -> usize {
- let byte = index / 8;
- let below: u32 = bits[..byte].iter().map(|bits| bits.count_ones()).sum();
- (below + (bits[byte] & ((1u8 << (index % 8)) - 1)).count_ones()) as usize
-}
-
-/// The per-slot arrays, kept on the heap so that a table moves as a handful of words rather than
-/// as the several kilobytes the slots occupy.
-struct DenseSlotStorage {
- // Empty slots use the handle's null pointer; the same storage supplies the borrowed FFI view.
- slots: [RetainedStyleValueData; LONGHAND_COUNT],
- /// Cascade source slot for each longhand, or `-1` when its value carries
- /// no style sheet context. Allocate the dense sidecar only when a declaration needs it;
- /// both reads and writes remain direct slot lookups.
- source_slots: Option<Box<[i32; LONGHAND_COUNT]>>,
-}
-
-impl Clone for DenseSlotStorage {
- fn clone(&self) -> Self {
- // NB: Only copying an unfrozen host working table can share mutable dense storage.
- ffi_stats::count_table_copy(|| {
- (
- LONGHAND_COUNT as u64,
- self.slots.iter().filter(|value| !value.pointer().is_null()).count() as u64,
- )
- });
- Self {
- slots: self.slots.clone(),
- source_slots: self.source_slots.clone(),
- }
- }
-}
-
-impl DenseSlotStorage {
- fn source_slot(&self, index: usize) -> i32 {
- self.source_slots.as_ref().map_or(-1, |slots| slots[index])
- }
-
- fn set_source_slot(&mut self, index: usize, source_slot: i32) {
- if let Some(slots) = &mut self.source_slots {
- slots[index] = source_slot;
- } else if source_slot != -1 {
- let mut slots = Box::new([-1; LONGHAND_COUNT]);
- slots[index] = source_slot;
- self.source_slots = Some(slots);
- }
- }
-
- /// Drop a source sidecar that carries no context; reads then answer `-1` for every slot.
- fn release_empty_sources(&mut self) {
- if self
- .source_slots
- .as_ref()
- .is_some_and(|slots| slots.iter().all(|&slot| slot == -1))
- {
- self.source_slots = None;
- }
- }
-
- fn new_shared() -> Arc<Self> {
- let mut storage = Arc::<Self>::new_uninit();
- let pointer = Arc::get_mut(&mut storage).unwrap().as_mut_ptr();
- // SAFETY: Every field is initialized in place below, so the allocation holds a complete value
- // when it is assumed initialized; nothing is moved through the stack.
- unsafe {
- let slots = std::ptr::addr_of_mut!((*pointer).slots).cast::<RetainedStyleValueData>();
- for index in 0..LONGHAND_COUNT {
- slots.add(index).write(RetainedStyleValueData::none());
- }
- std::ptr::addr_of_mut!((*pointer).source_slots).write(None);
- storage.assume_init()
- }
- }
-}
-
-/// A working table borrows unchanged slots through one owner of a flat base.
-/// The base is always dense, so even a seed made from another working delta
-/// cannot introduce a chain. Publication materializes only a unique result.
-#[derive(Clone)]
-struct ChangedSlot {
- index: u16,
- // None keeps the base value; Some(none()) represents an empty slot.
- value: Option<RetainedStyleValueData>,
- source_slot: i32,
-}
-
-/// The slot values of a table in slot order: a delta's changes, which are kept in slot order, are
-/// merged over its base as the walk reaches them.
-struct SlotValues<'a> {
- base: &'a [RetainedStyleValueData; LONGHAND_COUNT],
- changes: &'a [ChangedSlot],
- index: usize,
-}
-
-impl<'a> Iterator for SlotValues<'a> {
- type Item = &'a RetainedStyleValueData;
-
- fn next(&mut self) -> Option<Self::Item> {
- let index = self.index;
- let base = self.base.get(index)?;
- self.index += 1;
- match self.changes.split_first() {
- Some((change, rest)) if usize::from(change.index) == index => {
- self.changes = rest;
- Some(change.value.as_ref().unwrap_or(base))
- }
- _ => Some(base),
- }
- }
-}
-
-// NB: Inline changes avoid a separate allocation for each sparse drive.
-#[allow(clippy::large_enum_variant)]
-#[derive(Clone)]
-enum SlotStorage {
- Dense(Arc<DenseSlotStorage>),
- Delta {
- base: Arc<DenseSlotStorage>,
- changes: SmallVec<[ChangedSlot; 16]>,
- changed_bits: [u8; LONGHAND_BITMAP_BYTES],
- preserve_sources: bool,
- // Only consumers explicitly asking for the contiguous ABI span pay for it.
- view: OnceLock<Box<[SharedPayload; LONGHAND_COUNT]>>,
- },
-}
-
-impl SlotStorage {
- fn new() -> Self {
- Self::Dense(DenseSlotStorage::new_shared())
- }
-
- fn slot(&self, index: usize) -> (&RetainedStyleValueData, i32) {
- match self {
- Self::Dense(storage) => (&storage.slots[index], storage.source_slot(index)),
- Self::Delta {
- base,
- changes,
- changed_bits,
- preserve_sources,
- ..
- } => {
- if bitmap_bit(changed_bits, index) {
- let change = &changes[bitmap_rank(changed_bits, index)];
- return (change.value.as_ref().unwrap_or(&base.slots[index]), change.source_slot);
- }
- (
- &base.slots[index],
- if *preserve_sources { base.source_slot(index) } else { -1 },
- )
- }
- }
- }
-
- fn change(&mut self, index: usize) -> &mut ChangedSlot {
- let source_slot = self.slot(index).1;
- let Self::Delta {
- changes,
- changed_bits,
- view,
- ..
- } = self
- else {
- unreachable!()
- };
- view.take();
- // Changes stay in slot order, so a rank names an entry directly. A drive that writes
- // its slots in order only ever appends.
- let rank = bitmap_rank(changed_bits, index);
- if !bitmap_bit(changed_bits, index) {
- set_bitmap_bit(changed_bits, index, true);
- changes.insert(
- rank,
- ChangedSlot {
- index: index as u16,
- value: None,
- source_slot,
- },
- );
- }
- &mut changes[rank]
- }
-
- fn set_value(&mut self, index: usize, value: RetainedStyleValueData) {
- match self {
- Self::Dense(storage) => Arc::make_mut(storage).slots[index] = value,
- Self::Delta { .. } => self.change(index).value = Some(value),
- }
- }
-
- /// Release an all-empty source sidecar of a uniquely owned dense base; shared or delta
- /// storage keeps its sources, since a later materialization decides them.
- fn release_empty_sources(&mut self) {
- if let Self::Dense(storage) = self
- && let Some(storage) = Arc::get_mut(storage)
- {
- storage.release_empty_sources();
- }
- }
-
- #[cfg(test)]
- fn has_source_slots(&self) -> bool {
- match self {
- Self::Dense(storage) => storage.source_slots.is_some(),
- Self::Delta { base, changes, .. } => {
- base.source_slots.is_some() || changes.iter().any(|change| change.source_slot != -1)
- }
- }
- }
-
- fn set_source(&mut self, index: usize, source_slot: i32) {
- if self.slot(index).1 == source_slot {
- return;
- }
- match self {
- Self::Dense(storage) => Arc::make_mut(storage).set_source_slot(index, source_slot),
- Self::Delta { .. } => self.change(index).source_slot = source_slot,
- }
- }
-
- fn seeded(source: &Self, preserve_sources: bool) -> Self {
- // NB: One base owner replaces the former retain of every slot.
- ffi_stats::count_table_copy(|| (0, 1));
- let (base, changes, changed_bits, old_preserve_sources) = match source {
- Self::Dense(storage) => (storage.clone(), SmallVec::new(), [0; LONGHAND_BITMAP_BYTES], true),
- Self::Delta {
- base,
- changes,
- changed_bits,
- preserve_sources,
- ..
- } => {
- ffi_stats::count_table_copy(|| {
- let slots = changes.iter().filter_map(|change| change.value.as_ref());
- (
- slots.clone().count() as u64,
- slots.filter(|value| !value.pointer().is_null()).count() as u64,
- )
- });
- let changes = changes
- .iter()
- .map(|change| ChangedSlot {
- index: change.index,
- value: change.value.clone(),
- source_slot: change.source_slot,
- })
- .collect();
- (base.clone(), changes, *changed_bits, *preserve_sources)
- }
- };
- let mut result = Self::Delta {
- base,
- changes,
- changed_bits,
- preserve_sources: preserve_sources && old_preserve_sources,
- view: OnceLock::new(),
- };
- if !preserve_sources && let Self::Delta { changes, .. } = &mut result {
- for change in changes {
- change.source_slot = -1;
- }
- }
- result
- }
-
- /// Every slot's value, in slot order, without locating each change by rank.
- fn values(&self) -> SlotValues<'_> {
- let (base, changes) = match self {
- Self::Dense(storage) => (&storage.slots, &[][..]),
- Self::Delta { base, changes, .. } => (&base.slots, &changes[..]),
- };
- debug_assert!(changes.windows(2).all(|pair| pair[0].index < pair[1].index));
- SlotValues {
- base,
- changes,
- index: 0,
- }
- }
-
- /// Compare only the slot values, ignoring the cascade source slots that publication ignores.
- ///
- /// Two deltas over one base already agree on every slot neither of them changed, so a shared
- /// base reduces the comparison to the union of the two change lists, and a delta agrees with
- /// its own base everywhere but in its changes. Two tables sharing dense storage agree
- /// everywhere.
- fn values_are_equal(
- &self,
- other: &Self,
- equal: impl Fn(&RetainedStyleValueData, &RetainedStyleValueData) -> bool,
- ) -> bool {
- match (self, other) {
- (Self::Dense(dense), Self::Delta { base, changes, .. })
- | (Self::Delta { base, changes, .. }, Self::Dense(dense))
- if Arc::ptr_eq(dense, base) =>
- {
- changes.iter().all(|change| {
- change
- .value
- .as_ref()
- .is_none_or(|value| equal(value, &base.slots[usize::from(change.index)]))
- })
- }
- (Self::Dense(first), Self::Dense(second)) => {
- Arc::ptr_eq(first, second)
- || first
- .slots
- .iter()
- .zip(second.slots.iter())
- .all(|(first, second)| equal(first, second))
- }
- (
- Self::Delta {
- base: first_base,
- changes: first_changes,
- ..
- },
- Self::Delta {
- base: second_base,
- changes: second_changes,
- ..
- },
- ) if Arc::ptr_eq(first_base, second_base) => {
- let mut first = 0;
- let mut second = 0;
- while first < first_changes.len() || second < second_changes.len() {
- let first_index = first_changes.get(first).map_or(u16::MAX, |change| change.index);
- let second_index = second_changes.get(second).map_or(u16::MAX, |change| change.index);
- let index = usize::from(first_index.min(second_index));
- let base = &first_base.slots[index];
- let mut first_value = base;
- let mut second_value = base;
- if usize::from(first_index) == index {
- first_value = first_changes[first].value.as_ref().unwrap_or(base);
- first += 1;
- }
- if usize::from(second_index) == index {
- second_value = second_changes[second].value.as_ref().unwrap_or(base);
- second += 1;
- }
- if !equal(first_value, second_value) {
- return false;
- }
- }
- true
- }
- _ => self
- .values()
- .zip(other.values())
- .all(|(first, second)| equal(first, second)),
- }
- }
-
- fn value_pointers(&self) -> &[*const c_void] {
- match self {
- Self::Dense(storage) => RetainedStyleValueData::pointer_slice(&storage.slots),
- Self::Delta { view, .. } => HostShared::as_pointer_slice(
- view.get_or_init(|| {
- Box::new(std::array::from_fn(|index| {
- SharedPayload::new(self.slot(index).0.pointer().cast())
- }))
- })
- .as_slice(),
- ),
- }
- }
-
- fn materialize(&mut self) {
- if matches!(self, Self::Dense(_)) {
- return;
- }
- let dense = DenseSlotStorage::new_shared();
- let old = std::mem::replace(self, Self::Dense(dense));
- let Self::Delta {
- base,
- changes,
- preserve_sources,
- ..
- } = old
- else {
- unreachable!()
- };
- let Self::Dense(dense) = self else { unreachable!() };
- let storage = Arc::get_mut(dense).unwrap();
- let mut owned_bits = [0; LONGHAND_BITMAP_BYTES];
- storage.source_slots = if preserve_sources {
- base.source_slots.clone()
- } else {
- None
- };
- for change in changes {
- let index = usize::from(change.index);
- storage.set_source_slot(index, change.source_slot);
- if let Some(value) = change.value {
- storage.slots[index] = value;
- set_bitmap_bit(&mut owned_bits, index, true);
- }
- }
- ffi_stats::count_table_copy(|| {
- let mut slots = 0;
- let mut retains = 0;
- for index in 0..LONGHAND_COUNT {
- if !bitmap_bit(&owned_bits, index) {
- slots += 1;
- retains += u64::from(!base.slots[index].pointer().is_null());
- }
- }
- (slots, retains)
- });
- for index in 0..LONGHAND_COUNT {
- if !bitmap_bit(&owned_bits, index) {
- storage.slots[index] = base.slots[index].clone();
- }
- }
- }
-}
-
+/// What a longhand table publishes beside its values, its recorded specified values, its zoom,
+/// box display, color scheme and dependency flags: whether each longhand's value was important,
+/// inherited or evaluated by the computation, and what the box adjustments and monospace
+/// recascades read.
#[derive(Clone)]
-
-pub struct ComputedLonghandTable {
- storage: SlotStorage,
- /// Whether the longhand's winning declaration was `!important`, in the
- /// byte layout of the C++ `FixedBitmap` (bit `i` is byte `i / 8`, bit
- /// `i % 8`), so whole bitmaps copy across the FFI without translation.
+pub(crate) struct LonghandTableFlags {
important_bits: [u8; LONGHAND_BITMAP_BYTES],
- /// Whether the longhand's computed value was taken by inheritance.
inherited_bits: [u8; LONGHAND_BITMAP_BYTES],
- /// Which longhands a drive over this table (not the styles it was seeded
- /// from) has evaluated and stored; an evaluated longhand's value always
- /// comes from the table, while an unevaluated one keeps the recorded
- /// currentcolor-dependent specified value's preference.
evaluated_bits: [u8; LONGHAND_BITMAP_BYTES],
- /// The recorded inheritance-dependent specified values, sparse.
- inheritance_dependent: Vec<(u16, RetainedStyleValueData)>,
- /// Whether `inheritance_dependent` was seeded from another table, so that a drive over this
- /// one must replace or drop the record of every row it evaluates.
- inheritance_dependent_is_seeded: bool,
- /// Which longhands have a recorded inheritance-dependent specified value, so a lookup for
- /// one of the many that do not never walks the list.
- inheritance_dependent_bits: [u8; LONGHAND_BITMAP_BYTES],
- /// The winning cascaded font-size retained for monospace recascades.
- raw_cascaded_font_size: Option<RetainedStyleValueData>,
- /// The borrowed view over `inheritance_dependent` handed to C++.
- inheritance_dependent_view: Vec<FfiTableInheritanceDependentValue>,
- /// Viewport dependency flags accumulated by the longhand drive.
- metadata: FfiComputedStyleMetadata,
- /// Values before automatic post-compute adjustments, retained only while
- /// animation processing may need to restore them.
- /// The computed `overflow-x` and `overflow-y` keywords before the axes were adjusted against
- /// each other, which an animation of one axis is adjusted against again, once known.
overflow_before_adjustment: Option<[u16; 2]>,
- /// The sum of every slot's `longhand_slot_hash`, once known. A table seeded from a published
- /// table inherits its sum and adjusts it on each slot write, so publishing hashes only the
- /// values the drive changed; a table that starts empty computes the sum once, when it is
- /// first published.
- slot_hash_sum: MemoizedHashSum,
- /// The longhands the table's `transition-*` values make transitionable, resolved once per
- /// frozen table because every drive seeded from it asks for them.
- frozen_transition_longhands: OnceLock<Box<[u16]>>,
- /// https://drafts.csswg.org/css-viewport/#effective-zoom
- /// The product of the computed value of zoom and the computed values of zoom of all flat tree ancestors.
- effective_zoom: f32,
- frozen: bool,
-}
-
-/// The dependency-flag bit of a record holding a value resolved against the viewport, as a `vw`
-/// length is.
-pub(crate) const DEPENDS_ON_VIEWPORT_METRICS: u8 = 1;
-/// The dependency-flag bit of a record whose font metrics read the viewport, as a `vw` font size
-/// does: what `em` and the other font-relative units resolve against moves with the viewport.
-pub(crate) const FONT_METRICS_DEPEND_ON_VIEWPORT_METRICS: u8 = 1 << 1;
-/// The dependency-flag bit of a record whose element is `display: none` or inherits from one that is.
-pub(crate) const IN_DISPLAY_NONE_SUBTREE: u8 = 1 << 2;
-/// The dependency-flag bit of a highlight pseudo-element record whose `color` or `background-color`
-/// comes from the author origin, on itself or up its highlight chain, so the paired default colors
-/// do not apply. Bits 0 to 4 are the viewport, font-metric, display-none, swap-eligibility and image
-/// flags.
-/// https://drafts.csswg.org/css-pseudo-4/#paired-defaults
-pub(crate) const HIGHLIGHT_COLORS_AUTHORED: u8 = 1 << 5;
-/// The dependency-flag bit of a highlight pseudo-element record whose `color` is currentColor: the
-/// computed value is the originating element's color, but painting draws the layer below instead.
-/// https://drafts.csswg.org/css-pseudo-4/#highlight-text
-pub(crate) const HIGHLIGHT_COLOR_IS_CURRENT_COLOR: u8 = 1 << 6;
-/// The dependency-flag bit of a record with a cascaded value from the author origin for any property that disables
-/// native appearance for widgets.
-/// https://drafts.csswg.org/css-ui/#appearance-disabling-properties
-pub(crate) const NATIVE_APPEARANCE_DISABLED: u8 = 1 << 7;
-
-#[derive(Clone, Copy)]
-#[repr(C)]
-pub struct FfiComputedStyleMetadata {
- pub display_before_box_type_transformation: u32,
- pub pseudo_element_styles: u64,
- pub effective_color_scheme: i16,
- pub dependency_flags: u8,
- pub in_display_none_subtree: bool,
+ raw_cascaded_font_size: Option<RetainedStyleValueData>,
}
-impl ComputedLonghandTable {
- pub(crate) fn new() -> Self {
- Self::with_storage(SlotStorage::new())
- }
-
- fn with_storage(storage: SlotStorage) -> Self {
+impl LonghandTableFlags {
+ /// The flags of a copy of `initial` a drive starts from, before it computes anything.
+ pub(crate) fn of_drive_copy(initial: &LonghandTableFlags) -> Self {
Self {
- storage,
- important_bits: [0; LONGHAND_BITMAP_BYTES],
- inherited_bits: [0; LONGHAND_BITMAP_BYTES],
evaluated_bits: [0; LONGHAND_BITMAP_BYTES],
- inheritance_dependent: Vec::new(),
- inheritance_dependent_is_seeded: false,
- inheritance_dependent_bits: [0; LONGHAND_BITMAP_BYTES],
- inheritance_dependent_view: Vec::new(),
- raw_cascaded_font_size: None,
- metadata: FfiComputedStyleMetadata {
- display_before_box_type_transformation: 0,
- pseudo_element_styles: 0,
- effective_color_scheme: -1,
- dependency_flags: 0,
- in_display_none_subtree: false,
- },
- overflow_before_adjustment: None,
- slot_hash_sum: MemoizedHashSum::default(),
- frozen_transition_longhands: OnceLock::new(),
- effective_zoom: 1.0,
- frozen: false,
+ ..initial.clone()
}
}
- fn slot_index(property_id: u16) -> usize {
- assert!(
- (FIRST_LONGHAND_PROPERTY_ID..=LAST_LONGHAND_PROPERTY_ID).contains(&property_id),
- "computed longhand table indices are longhand property identifiers"
- );
- (property_id - FIRST_LONGHAND_PROPERTY_ID) as usize
- }
-
- pub(crate) fn set(&mut self, property_id: u16, value: RetainedStyleValueData, source_slot: i64) {
- assert!(
- !self.frozen,
- "the computed longhand table is immutable once its style is created"
- );
- let index = Self::slot_index(property_id);
- self.replace_slot_value(index, value);
- self.mark_evaluated(index, source_slot);
- }
-
- /// A slot that already holds an equal value keeps it, and so its identity: an unchanged longhand
- /// then costs no allocation, no hash and no deep comparison when the table is published.
- pub(crate) fn set_computed(&mut self, property_id: u16, value: StyleValueData, source_slot: i64) {
- assert!(
- !self.frozen,
- "the computed longhand table is immutable once its style is created"
- );
- let index = Self::slot_index(property_id);
- if self
- .storage
- .slot(index)
- .0
- .optional_data()
- .is_none_or(|existing| *existing != value)
- {
- self.replace_slot_value(index, RetainedStyleValueData::from_owned(value));
+ /// The flags of the table `initial` seeds for a child, before the child computes anything:
+ /// every longhand that inherits by default is inherited, and none is evaluated.
+ pub(crate) fn of_child_seed(initial: &LonghandTableFlags) -> Self {
+ Self {
+ important_bits: initial.important_bits,
+ inherited_bits: INHERITED_LONGHAND_BITS,
+ evaluated_bits: [0; LONGHAND_BITMAP_BYTES],
+ ..initial.clone()
}
- self.mark_evaluated(index, source_slot);
}
- pub(crate) fn set_or_keep_equal(&mut self, property_id: u16, value: RetainedStyleValueData, source_slot: i64) {
- assert!(
- !self.frozen,
- "the computed longhand table is immutable once its style is created"
- );
- let index = Self::slot_index(property_id);
- let existing = self.storage.slot(index).0;
- let equal_to_existing = !existing.pointer().is_null() && *existing == value;
- if !equal_to_existing {
- self.replace_slot_value(index, value);
- }
- self.mark_evaluated(index, source_slot);
+ pub(crate) fn is_important(&self, property_id: u16) -> bool {
+ bitmap_bit(&self.important_bits, slot_index(property_id))
}
- fn replace_slot_value(&mut self, index: usize, value: RetainedStyleValueData) {
- let previous = self.storage.slot(index).0;
- if previous.pointer() != value.pointer() {
- self.adjust_slot_hash_sum(index, previous.optional_data(), value.optional_data());
- }
- self.storage.set_value(index, value);
+ /// One bit per longhand: whether its value is important.
+ pub(crate) fn importance_bits(&self) -> &[u8] {
+ &self.important_bits
}
- fn mark_evaluated(&mut self, index: usize, source_slot: i64) {
- set_bitmap_bit(&mut self.evaluated_bits, index, true);
- self.storage.set_source(index, i32::try_from(source_slot).unwrap_or(-1));
+ pub(crate) fn is_inherited(&self, property_id: u16) -> bool {
+ bitmap_bit(&self.inherited_bits, slot_index(property_id))
}
- fn adjust_slot_hash_sum(
- &self,
- index: usize,
- previous: Option<&StyleValueData>,
- replacement: Option<&StyleValueData>,
- ) {
- if let Some(sum) = self.slot_hash_sum.get() {
- self.slot_hash_sum.set(Some(
- sum.wrapping_sub(longhand_slot_hash(index, previous))
- .wrapping_add(longhand_slot_hash(index, replacement)),
- ));
- }
+ pub(crate) fn is_evaluated(&self, property_id: u16) -> bool {
+ bitmap_bit(&self.evaluated_bits, slot_index(property_id))
}
- pub(crate) fn slot_hash_sum(&self) -> u64 {
- if let Some(sum) = self.slot_hash_sum.get() {
- return sum;
- }
- let sum = self.recomputed_slot_hash_sum();
- self.slot_hash_sum.set(Some(sum));
- sum
+ pub(crate) fn set_important(&mut self, property_id: u16, important: bool) {
+ set_bitmap_bit(&mut self.important_bits, slot_index(property_id), important);
}
- pub(crate) fn recomputed_slot_hash_sum(&self) -> u64 {
- (0..LONGHAND_COUNT).fold(0_u64, |sum, slot| {
- sum.wrapping_add(longhand_slot_hash(slot, self.storage.slot(slot).0.optional_data()))
- })
+ pub(crate) fn set_inherited(&mut self, property_id: u16, inherited: bool) {
+ set_bitmap_bit(&mut self.inherited_bits, slot_index(property_id), inherited);
}
- pub(crate) fn frozen_transition_longhands(&self, compute: impl FnOnce(&Self) -> Box<[u16]>) -> Option<&[u16]> {
- if !self.frozen {
- return None;
+ /// The flags of a computation that starts from nothing: no longhand is important, inherited
+ /// or evaluated.
+ pub(crate) fn empty() -> Self {
+ Self {
+ important_bits: [0; LONGHAND_BITMAP_BYTES],
+ inherited_bits: [0; LONGHAND_BITMAP_BYTES],
+ evaluated_bits: [0; LONGHAND_BITMAP_BYTES],
+ overflow_before_adjustment: None,
+ raw_cascaded_font_size: None,
}
- Some(self.frozen_transition_longhands.get_or_init(|| compute(self)))
- }
-
- pub(crate) fn set_important(&mut self, property_id: u16, important: bool) {
- assert!(
- !self.frozen,
- "the computed longhand table is immutable once its style is created"
- );
- set_bitmap_bit(&mut self.important_bits, Self::slot_index(property_id), important);
}
- pub(crate) fn set_inherited(&mut self, property_id: u16, inherited: bool) {
- assert!(
- !self.frozen,
- "the computed longhand table is immutable once its style is created"
- );
- set_bitmap_bit(&mut self.inherited_bits, Self::slot_index(property_id), inherited);
+ pub(crate) fn mark_evaluated(&mut self, property_id: u16) {
+ set_bitmap_bit(&mut self.evaluated_bits, slot_index(property_id), true);
}
+ /// Takes the importance and inheritance a drive found for each longhand it evaluated, one bit
+ /// per longhand index in each of the words.
pub(crate) fn merge_driver_flags(
&mut self,
important_words: &[u64],
inherited_words: &[u64],
evaluated_words: &[u64],
) {
- assert!(
- !self.frozen,
- "the computed longhand table is immutable once its style is created"
- );
assert!(important_words.len() * 64 >= LONGHAND_COUNT);
assert_eq!(inherited_words.len(), important_words.len());
assert_eq!(evaluated_words.len(), important_words.len());
@@ -814,522 +176,51 @@ impl ComputedLonghandTable {
}
}
- pub(crate) fn merge_dependency_flags(
- &mut self,
- depends_on_viewport_metrics: bool,
- font_metrics_depend_on_viewport_metrics: bool,
- highlight_colors_authored: bool,
- highlight_color_is_current_color: bool,
- ) {
- self.metadata.dependency_flags |= (u8::from(depends_on_viewport_metrics) * DEPENDS_ON_VIEWPORT_METRICS)
- | (u8::from(font_metrics_depend_on_viewport_metrics) * FONT_METRICS_DEPEND_ON_VIEWPORT_METRICS)
- | (u8::from(highlight_colors_authored) * HIGHLIGHT_COLORS_AUTHORED)
- | (u8::from(highlight_color_is_current_color) * HIGHLIGHT_COLOR_IS_CURRENT_COLOR);
- }
-
- pub(crate) fn dependency_flags(&self) -> u8 {
- self.metadata.dependency_flags
- }
-
- pub(crate) fn set_native_appearance_disabled(&mut self, disabled: bool) {
- if disabled {
- self.metadata.dependency_flags |= NATIVE_APPEARANCE_DISABLED;
- } else {
- self.metadata.dependency_flags &= !NATIVE_APPEARANCE_DISABLED;
- }
- }
-
- pub(crate) fn publication_dependency_flags(&self) -> u8 {
- if self.metadata.in_display_none_subtree {
- self.metadata.dependency_flags | IN_DISPLAY_NONE_SUBTREE
- } else {
- self.metadata.dependency_flags
- }
- }
-
- pub(crate) fn pseudo_element_styles(&self) -> u64 {
- self.metadata.pseudo_element_styles
- }
-
- pub(crate) fn set_effective_color_scheme(&mut self, color_scheme: i16) {
- self.metadata.effective_color_scheme = color_scheme;
- }
-
- pub(crate) fn set_display_before_box_type_transformation(&mut self, display: u32) {
- self.metadata.display_before_box_type_transformation = display;
- }
-
- pub(crate) fn set_in_display_none_subtree(&mut self, in_display_none_subtree: bool) {
- self.metadata.in_display_none_subtree = in_display_none_subtree;
- }
-
- pub(crate) fn display_before_box_type_transformation(&self) -> u32 {
- self.metadata.display_before_box_type_transformation
- }
-
pub(crate) fn set_overflow_before_adjustment(&mut self, overflow: [u16; 2]) {
- assert!(
- !self.frozen,
- "the computed longhand table is immutable once its style is created"
- );
self.overflow_before_adjustment = Some(overflow);
}
- /// The computed `overflow-x` and `overflow-y` keywords before the axes were adjusted against
- /// each other.
+ /// The overflow keywords before the box adjustments, where they adjusted them.
pub(crate) fn overflow_before_adjustment(&self) -> Option<[u16; 2]> {
self.overflow_before_adjustment
}
- pub(crate) fn inheritance_dependent_values(&self) -> impl Iterator<Item = (u16, *const c_void)> + '_ {
- self.inheritance_dependent
- .iter()
- .map(|(property, value)| (*property, value.pointer().cast()))
- }
-
- /// NB: Equal resolved colors can retain specified values that inherit differently.
- pub(crate) fn inheritance_dependent_value_changed(&self, other: &Self, property: u16) -> bool {
- let old = self.inheritance_dependent_value(property);
- let new = other.inheritance_dependent_value(property);
- old.map(RetainedStyleValueData::pointer) != new.map(RetainedStyleValueData::pointer)
- && old.map(RetainedStyleValueData::data) != new.map(RetainedStyleValueData::data)
- }
-
- /// NB: Report these source changes separately from resolved group payload changes.
- pub(crate) fn non_inherited_inheritance_changes(&self, other: &Self) -> u32 {
- if std::ptr::eq(self, other) {
- return 0;
- }
- // NB: A property both tables hold is visited once, through this table.
- self.inheritance_dependent_values()
- .chain(
- other
- .inheritance_dependent_values()
- .filter(|(property, _)| !bitmap_bit(&self.inheritance_dependent_bits, Self::slot_index(*property))),
- )
- .filter(|(property, _)| {
- !crate::css::property_metadata::property_is_inherited(*property)
- && self.inheritance_dependent_value_changed(other, *property)
- })
- .fold(0, |groups, (property, _)| {
- groups
- | match crate::css::computed_values::StyleGroupMasks::get().dependencies(property) {
- 0 => u32::MAX,
- mask => mask,
- }
- })
- }
-
- pub(crate) fn retained_inheritance_dependent_values(&self) -> impl Iterator<Item = (u16, &RetainedStyleValueData)> {
- self.inheritance_dependent
- .iter()
- .map(|(property, value)| (*property, value))
+ pub(crate) fn set_raw_cascaded_font_size(&mut self, value: Option<RetainedStyleValueData>) {
+ self.raw_cascaded_font_size = value;
}
+ /// The element's cascaded font size, where it declares one, which the monospace recascade of
+ /// a descendant reads.
pub(crate) fn raw_cascaded_font_size_value(&self) -> Option<&StyleValueData> {
self.raw_cascaded_font_size
.as_ref()
.and_then(RetainedStyleValueData::optional_data)
}
- pub(crate) fn set_raw_cascaded_font_size(&mut self, value: Option<RetainedStyleValueData>) {
- assert!(
- !self.frozen,
- "the computed longhand table is immutable once its style is created"
- );
- self.raw_cascaded_font_size = value;
- }
-
- fn copy_metadata_from(&mut self, source: &ComputedLonghandTable) {
- assert!(
- !self.frozen,
- "the computed longhand table is immutable once its style is created"
- );
- self.slot_hash_sum.set(source.slot_hash_sum.get());
- self.important_bits = source.important_bits;
- self.inherited_bits = source.inherited_bits;
- self.evaluated_bits = source.evaluated_bits;
- self.metadata = source.metadata;
- self.overflow_before_adjustment = source.overflow_before_adjustment;
- self.raw_cascaded_font_size.clone_from(&source.raw_cascaded_font_size);
- self.effective_zoom = source.effective_zoom;
- }
-
- /// https://drafts.csswg.org/css-viewport/#effective-zoom
- pub(crate) fn effective_zoom(&self) -> f32 {
- self.effective_zoom
- }
-
- pub(crate) fn set_effective_zoom(&mut self, effective_zoom: f32) {
- assert!(
- !self.frozen,
- "the computed longhand table is immutable once its style is created"
- );
- self.effective_zoom = effective_zoom;
- }
-
- fn copy_from(&mut self, source: &ComputedLonghandTable) {
- self.storage = SlotStorage::seeded(&source.storage, true);
- self.copy_metadata_from(source);
- self.inheritance_dependent.clone_from(&source.inheritance_dependent);
- self.inheritance_dependent_bits = source.inheritance_dependent_bits;
- self.rebuild_inheritance_dependent_view();
- }
-
- /// Take one slot back from `source`: its value, provenance and flags, exactly as stored there.
- pub(crate) fn copy_slot_from(&mut self, source: &ComputedLonghandTable, property_id: u16) {
- assert!(
- !self.frozen,
- "the computed longhand table is immutable once its style is created"
- );
- let slot = Self::slot_index(property_id);
- let previous = self.storage.slot(slot).0;
- let replacement = source.storage.slot(slot).0;
- if previous.pointer() != replacement.pointer() {
- self.adjust_slot_hash_sum(slot, previous.optional_data(), replacement.optional_data());
- }
- let replacement = replacement.pointer().cast::<c_void>();
- let source_slot = source.storage.slot(slot).1;
- if let SlotStorage::Delta {
- base,
- changes,
- changed_bits,
- view,
- ..
- } = &mut self.storage
- && base.slots[slot].pointer().cast::<c_void>() == replacement
- {
- view.take();
- if bitmap_bit(changed_bits, slot) {
- changes.remove(bitmap_rank(changed_bits, slot));
- set_bitmap_bit(changed_bits, slot, false);
- }
- if self.storage.slot(slot).1 != source_slot {
- self.storage.set_source(slot, source_slot);
- }
- } else {
- ffi_stats::count_table_copy(|| (1, u64::from(!replacement.is_null())));
- self.storage.set_value(slot, source.storage.slot(slot).0.clone());
- self.storage.set_source(slot, source_slot);
- }
- set_bitmap_bit(&mut self.important_bits, slot, bitmap_bit(&source.important_bits, slot));
- set_bitmap_bit(&mut self.inherited_bits, slot, bitmap_bit(&source.inherited_bits, slot));
- set_bitmap_bit(&mut self.evaluated_bits, slot, bitmap_bit(&source.evaluated_bits, slot));
- }
-
- pub(crate) fn effective_color_scheme(&self) -> i16 {
- self.metadata.effective_color_scheme
- }
-
- pub(crate) fn copied_for_drive(source: &ComputedLonghandTable) -> Self {
- let mut table = Self::with_storage(SlotStorage::seeded(&source.storage, true));
- table.copy_metadata_from(source);
- table.evaluated_bits = [0; LONGHAND_BITMAP_BYTES];
- table
- }
-
- pub(crate) fn copied_for_partial_drive(source: &ComputedLonghandTable) -> Self {
- let mut table = Self::with_storage(SlotStorage::seeded(&source.storage, true));
- table.copy_metadata_from(source);
- table.inheritance_dependent.clone_from(&source.inheritance_dependent);
- table.inheritance_dependent_bits = source.inheritance_dependent_bits;
- table.rebuild_inheritance_dependent_view();
- table.evaluated_bits = [0; LONGHAND_BITMAP_BYTES];
- table.inheritance_dependent_is_seeded = true;
- table.set_in_display_none_subtree(false);
- table
- }
-
- pub(crate) fn with_inherited_values_from(&self, inherited_source: &ComputedLonghandTable) -> Self {
- self.with_inherited_values_and_flags_from(inherited_source, &self.important_bits, &self.inherited_bits)
- }
-
- pub(crate) fn with_inherited_values_and_flags_from(
- &self,
- inherited_source: &ComputedLonghandTable,
- importance: &[u8],
- inheritance: &[u8],
- ) -> Self {
- assert!(self.frozen);
- assert!(inherited_source.frozen);
- let mut table = Self::with_storage(SlotStorage::seeded(&self.storage, true));
- table.copy_metadata_from(self);
- table.inheritance_dependent.clone_from(&self.inheritance_dependent);
- table.inheritance_dependent_bits = self.inheritance_dependent_bits;
- table.rebuild_inheritance_dependent_view();
- for property_id in FIRST_LONGHAND_PROPERTY_ID..=LAST_LONGHAND_PROPERTY_ID {
- if !property_is_inherited(property_id) {
- continue;
- }
- let Some(value) = inherited_source.get(property_id) else {
- continue;
- };
- // An inherited value equal to the one already held keeps that one, so a swap that
- // changes nothing leaves the table equal to its source slot for slot.
- table.set_or_keep_equal(property_id, value.clone(), -1);
- }
- table.metadata.effective_color_scheme = inherited_source.metadata.effective_color_scheme;
- // A value reading `currentcolor` - the keyword itself, or a color function of it - is
- // what a fresh computation leaves in the table too: the color resolves when the groups
- // are built, never in the computed value.
- for (property, value) in &table.inheritance_dependent {
- if retained_value_depends_on_current_color(value) {
- set_bitmap_bit(&mut table.evaluated_bits, Self::slot_index(*property), false);
- }
- }
- table.load_flag_bitmaps(importance, inheritance);
- table.frozen = true;
- table
- }
-
- pub(crate) fn into_raw_shared(mut self) -> *const Self {
- self.storage.materialize();
- Arc::into_raw(Arc::new(self))
- }
-
- fn copy_from_values(&mut self, values: &[*const c_void]) {
- assert!(
- !self.frozen,
- "the computed longhand table is immutable once its style is created"
- );
- assert_eq!(values.len(), LONGHAND_COUNT);
- ffi_stats::count_table_copy(|| {
- (
- values.len() as u64,
- values.iter().filter(|value| !value.is_null()).count() as u64,
- )
- });
- self.storage = SlotStorage::new();
- for (index, &value) in values.iter().enumerate() {
- let retained = unsafe {
- RetainedStyleValueData::from_retained_optional_pointer(crate::css::style_value::retain_style_value(
- value.cast(),
- ))
- };
- self.storage.set_value(index, retained);
- }
- self.slot_hash_sum.set(None);
- self.important_bits = [0; LONGHAND_BITMAP_BYTES];
- self.inherited_bits = [0; LONGHAND_BITMAP_BYTES];
- self.evaluated_bits = [0; LONGHAND_BITMAP_BYTES];
- self.metadata.dependency_flags = 0;
- self.inheritance_dependent.clear();
- self.inheritance_dependent_bits = [0; LONGHAND_BITMAP_BYTES];
- self.inheritance_dependent_view.clear();
- self.raw_cascaded_font_size = None;
- }
-
- fn rebuild_inheritance_dependent_view(&mut self) {
- self.inheritance_dependent_view.clear();
- self.inheritance_dependent_view
- .extend(
- self.inheritance_dependent
- .iter()
- .map(|(property, value)| FfiTableInheritanceDependentValue {
- property: *property,
- value: value.pointer().cast(),
- }),
- );
- }
-
- /// Reset the state a fresh drive must not inherit from the style its
- /// table was seeded from: the evaluated bits and the recorded
- /// inheritance-dependent specified values.
- fn clear_seeded_state(&mut self) {
- assert!(
- !self.frozen,
- "the computed longhand table is immutable once its style is created"
- );
- self.evaluated_bits = [0; LONGHAND_BITMAP_BYTES];
- self.inheritance_dependent.clear();
- self.inheritance_dependent_is_seeded = false;
- self.inheritance_dependent_bits = [0; LONGHAND_BITMAP_BYTES];
- self.inheritance_dependent_view.clear();
- }
-
- pub(crate) fn add_inheritance_dependent_value(&mut self, property_id: u16, value: RetainedStyleValueData) {
- assert!(
- !self.frozen,
- "the computed longhand table is immutable once its style is created"
- );
- match self
- .inheritance_dependent
- .iter_mut()
- .find(|(property, _)| *property == property_id)
- {
- Some((_, existing)) => *existing = value,
- None => self.inheritance_dependent.push((property_id, value)),
- }
- set_bitmap_bit(
- &mut self.inheritance_dependent_bits,
- Self::slot_index(property_id),
- true,
- );
- self.rebuild_inheritance_dependent_view();
- }
-
- #[cfg(test)]
- pub(crate) fn append_drive_inheritance_dependent_value(&mut self, property_id: u16, value: RetainedStyleValueData) {
- self.set_drive_inheritance_dependent_value(property_id, Some(value));
- }
-
- /// Record what a drive found for one row: its inheritance-dependent specified value, or that
- /// it has none. A table seeded with another table's records replaces or drops the row's old
- /// record, so a row the drive leaves alone keeps its record and an evaluated row keeps no
- /// stale one.
- pub(crate) fn set_drive_inheritance_dependent_value(
- &mut self,
- property_id: u16,
- value: Option<RetainedStyleValueData>,
- ) {
- assert!(
- !self.frozen,
- "the computed longhand table is immutable once its style is created"
- );
- if self.inheritance_dependent_is_seeded {
- let slot = Self::slot_index(property_id);
- let existing = bitmap_bit(&self.inheritance_dependent_bits, slot).then(|| {
- self.inheritance_dependent
- .iter()
- .position(|(property, _)| *property == property_id)
- .expect("a longhand with a recorded inheritance-dependent value must be listed")
- });
- match (existing, value) {
- (Some(index), Some(value)) => self.inheritance_dependent[index].1 = value,
- (Some(index), None) => {
- self.inheritance_dependent.swap_remove(index);
- set_bitmap_bit(&mut self.inheritance_dependent_bits, slot, false);
- }
- (None, Some(value)) => {
- self.inheritance_dependent.push((property_id, value));
- set_bitmap_bit(&mut self.inheritance_dependent_bits, slot, true);
- }
- (None, None) => {}
- }
- return;
- }
- debug_assert!(
- self.inheritance_dependent
- .iter()
- .all(|(property, _)| *property != property_id),
- "a longhand drive must visit each property once"
- );
- if let Some(value) = value {
- self.inheritance_dependent.push((property_id, value));
- set_bitmap_bit(
- &mut self.inheritance_dependent_bits,
- Self::slot_index(property_id),
- true,
- );
- }
- }
-
- pub(crate) fn finish_drive_inheritance_dependent_values(&mut self) {
- self.rebuild_inheritance_dependent_view();
- }
-
- fn inheritance_dependent_value(&self, property_id: u16) -> Option<&RetainedStyleValueData> {
- if !bitmap_bit(&self.inheritance_dependent_bits, Self::slot_index(property_id)) {
- return None;
- }
- self.inheritance_dependent
- .iter()
- .find(|(property, _)| *property == property_id)
- .map(|(_, value)| value)
- }
-
- /// Whether the longhand was specified as the `currentcolor` keyword itself.
- pub(crate) fn specified_value_is_current_color(&self, property_id: u16) -> bool {
- self.specified_value(property_id)
- .is_some_and(|value| 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> {
- let Some(StyleValueData::ValueList { values, .. }) = self
- .specified_value(property_id::TEXT_SHADOW)
- .map(RetainedStyleValueData::data)
- else {
- return Vec::new();
- };
- values
- .as_slice()
- .iter()
- .map(|layer| match layer.optional_data() {
- Some(StyleValueData::Shadow { color, .. }) => {
- color.optional_data().is_none_or(is_current_color_keyword)
- }
- _ => false,
- })
- .collect()
- }
-
- /// The longhand's value as specified: an unevaluated longhand's recorded specified value, else
- /// the table slot's.
- fn specified_value(&self, property_id: u16) -> Option<&RetainedStyleValueData> {
- if !self.is_evaluated(property_id)
- && let Some(value) = self.inheritance_dependent_value(property_id)
- {
- return Some(value);
- }
- self.get(property_id)
- }
-
- pub(crate) fn is_important(&self, property_id: u16) -> bool {
- bitmap_bit(&self.important_bits, Self::slot_index(property_id))
- }
-
- pub(crate) fn is_inherited(&self, property_id: u16) -> bool {
- bitmap_bit(&self.inherited_bits, Self::slot_index(property_id))
- }
-
- pub(crate) fn importance_bits(&self) -> &[u8] {
- &self.important_bits
- }
-
- pub(crate) fn publication_sidecars(&self) -> (&[u8; LONGHAND_BITMAP_BYTES], u32, Option<[u16; 2]>, i16) {
- (
- &self.evaluated_bits,
- self.metadata.display_before_box_type_transformation,
- self.overflow_before_adjustment,
- self.metadata.effective_color_scheme,
- )
- }
-
- pub(crate) fn inheritance_bits(&self) -> &[u8] {
- &self.inherited_bits
- }
-
- pub(crate) fn evaluated_bits(&self) -> &[u8] {
- &self.evaluated_bits
- }
-
- pub(crate) fn load_flag_bitmaps(&mut self, importance: &[u8], inheritance: &[u8]) {
- assert!(!self.frozen);
- assert_eq!(importance.len(), LONGHAND_BITMAP_BYTES);
- assert_eq!(inheritance.len(), LONGHAND_BITMAP_BYTES);
- self.important_bits.copy_from_slice(importance);
- self.inherited_bits.copy_from_slice(inheritance);
- }
-
- pub(crate) fn property_inheritance_is_standard(&self) -> bool {
- (FIRST_LONGHAND_PROPERTY_ID..=LAST_LONGHAND_PROPERTY_ID)
- .all(|property_id| self.is_inherited(property_id) == property_is_inherited(property_id))
+ /// Whether these are the very flags `other` are: the same bits, and the same cascaded font size
+ /// value, not only an equal one.
+ pub(crate) fn same_as(&self, other: &Self) -> bool {
+ self.important_bits == other.important_bits
+ && self.inherited_bits == other.inherited_bits
+ && self.evaluated_bits == other.evaluated_bits
+ && self.overflow_before_adjustment == other.overflow_before_adjustment
+ && self
+ .raw_cascaded_font_size
+ .as_ref()
+ .map(RetainedStyleValueData::pointer)
+ == other
+ .raw_cascaded_font_size
+ .as_ref()
+ .map(RetainedStyleValueData::pointer)
}
+ /// Whether these are the flags `other` are, as a publication compares them.
pub(crate) fn publication_equals(&self, other: &Self) -> bool {
- use crate::css::style_value::{optional_style_values_equal, retained_style_values_equal};
+ use crate::css::style_value::optional_style_values_equal;
self.important_bits == other.important_bits
&& self.inherited_bits == other.inherited_bits
- && self.effective_zoom.to_bits() == other.effective_zoom.to_bits()
- && self.publication_sidecars() == other.publication_sidecars()
- && self.publication_dependency_flags() == other.publication_dependency_flags()
- && self.pseudo_element_styles() == other.pseudo_element_styles()
- && self.inheritance_dependent.len() == other.inheritance_dependent.len()
- && self
- .storage
- .values_are_equal(&other.storage, retained_style_values_equal)
+ && self.evaluated_bits == other.evaluated_bits
+ && self.overflow_before_adjustment == other.overflow_before_adjustment
&& optional_style_values_equal(
self.raw_cascaded_font_size
.as_ref()
@@ -1339,648 +230,188 @@ impl ComputedLonghandTable {
.as_ref()
.and_then(RetainedStyleValueData::optional_data),
)
- && self.inheritance_dependent.iter().all(|(property, value)| {
- other
- .inheritance_dependent
- .iter()
- .find(|(other_property, _)| other_property == property)
- .is_some_and(|(_, other_value)| retained_style_values_equal(value, other_value))
- })
}
- pub(crate) fn display_is_list_item(&self) -> bool {
- let Some(StyleValueData::Display { raw }) = self.get(property_id::DISPLAY).map(RetainedStyleValueData::data)
- else {
- return false;
+ /// What these flags hold differently from `other`, by name, for a diagnostic to show.
+ pub(crate) fn publication_differences(&self, other: &Self) -> Vec<String> {
+ let bits_differ = |name: &str, first: &[u8; LONGHAND_BITMAP_BYTES], second: &[u8; LONGHAND_BITMAP_BYTES]| {
+ let longhands: Vec<_> = (FIRST_LONGHAND_PROPERTY_ID..=LAST_LONGHAND_PROPERTY_ID)
+ .filter(|&property| {
+ let slot = slot_index(property);
+ bitmap_bit(first, slot) != bitmap_bit(second, slot)
+ })
+ .map(crate::css::property_metadata::property_name)
+ .collect();
+ (!longhands.is_empty()).then(|| format!("{name} of {}", longhands.join(", ")))
};
- crate::css::display::FfiDisplay::from_raw(*raw).is_list_item()
- }
-
- fn is_evaluated(&self, property_id: u16) -> bool {
- bitmap_bit(&self.evaluated_bits, Self::slot_index(property_id))
- }
-
- /// The effective value property() returns for one longhand: the animated
- /// overlay under the overlay read rule, then an unevaluated longhand's
- /// recorded currentcolor-dependent specified value, then the table slot.
- pub(crate) fn effective_value(
- &self,
- overlay: Option<&AnimatedOverlay>,
- property_id: u16,
- with_animations: bool,
- ) -> FfiEffectiveLonghandValue {
- let (value, source) = self.effective_value_handle(overlay, property_id, with_animations);
- FfiEffectiveLonghandValue {
- value: value.pointer().cast(),
- source,
- }
- }
-
- /// The handle `effective_value` reads the longhand's value from, and which source it is.
- pub(crate) fn effective_value_handle<'a>(
- &'a self,
- overlay: Option<&'a AnimatedOverlay>,
- property_id: u16,
- with_animations: bool,
- ) -> (&'a RetainedStyleValueData, u8) {
- if with_animations
- && let Some(overlay) = overlay
- && let Some(entry) = overlay.get(property_id)
- && overlay_wins(entry, self.is_important(property_id))
- {
- return (entry.value_handle(), EFFECTIVE_LONGHAND_SOURCE_OVERLAY);
- }
- if !self.is_evaluated(property_id)
- && let Some(value) = self.inheritance_dependent_value(property_id)
- && retained_value_depends_on_current_color(value)
- {
- return (value, EFFECTIVE_LONGHAND_SOURCE_SPECIFIED);
- }
- (
- self.storage.slot(Self::slot_index(property_id)).0,
- EFFECTIVE_LONGHAND_SOURCE_TABLE,
+ let mut differences: Vec<String> = [
+ bits_differ("important bits", &self.important_bits, &other.important_bits),
+ bits_differ("inherited bits", &self.inherited_bits, &other.inherited_bits),
+ bits_differ("evaluated bits", &self.evaluated_bits, &other.evaluated_bits),
+ ]
+ .into_iter()
+ .flatten()
+ .collect();
+ let mut note = |name: &str, first: String, second: String| {
+ if first != second {
+ differences.push(format!("{name} {first} != {second}"));
+ }
+ };
+ note(
+ "overflow before adjustment",
+ format!("{:?}", self.overflow_before_adjustment),
+ format!("{:?}", other.overflow_before_adjustment),
+ );
+ if !crate::css::style_value::optional_style_values_equal(
+ self.raw_cascaded_font_size_value(),
+ other.raw_cascaded_font_size_value(),
+ ) {
+ differences.push("cascaded font size".into());
+ }
+ differences
+ }
+}
+
+/// The recorded specified value of `property` among `values`, where it has one.
+fn inheritance_dependent_value_among<'a>(
+ mut values: impl Iterator<Item = (u16, &'a RetainedStyleValueData)>,
+ property: u16,
+) -> Option<&'a RetainedStyleValueData> {
+ values.find(|(held, _)| *held == property).map(|(_, value)| value)
+}
+
+/// Whether the recorded specified value of `property` moved from `old` to `new`, the recorded
+/// specified values of two longhand tables or of the group values they are made from.
+/// NB: Equal resolved colors can retain specified values that inherit differently.
+fn inheritance_dependent_value_changed<'a, Values>(old: Values, new: Values, property: u16) -> bool
+where
+ Values: Iterator<Item = (u16, &'a RetainedStyleValueData)>,
+{
+ let old = inheritance_dependent_value_among(old, property);
+ let new = inheritance_dependent_value_among(new, property);
+ old.map(RetainedStyleValueData::pointer) != new.map(RetainedStyleValueData::pointer)
+ && old.map(RetainedStyleValueData::data) != new.map(RetainedStyleValueData::data)
+}
+
+/// Whether a property that inherits by default retains another specified value among `new` than
+/// among `old`, the recorded specified values of two longhand tables or of the group values they
+/// are made from, which the children inheriting it resolve differently though the resolved colors
+/// are equal.
+pub(crate) fn inherited_inheritance_dependent_value_moved<'a, Values>(old: Values, new: Values) -> bool
+where
+ Values: Iterator<Item = (u16, &'a RetainedStyleValueData)> + Clone,
+{
+ old.clone().chain(new.clone()).any(|(property, _)| {
+ property_is_inherited(property) && inheritance_dependent_value_changed(old.clone(), new.clone(), property)
+ })
+}
+
+/// The non-inherited groups whose recorded specified values moved from `old` to `new`, the recorded
+/// specified values of two longhand tables or of the group values they are made from.
+/// NB: Report these source changes separately from resolved group payload changes.
+pub(crate) fn non_inherited_inheritance_changes<'a, Values>(old: Values, new: Values) -> u32
+where
+ Values: Iterator<Item = (u16, &'a RetainedStyleValueData)> + Clone,
+{
+ // NB: A property both hold is visited once, through `old`.
+ old.clone()
+ .chain(
+ new.clone()
+ .filter(|(property, _)| inheritance_dependent_value_among(old.clone(), *property).is_none()),
)
- }
-
- pub(crate) fn freeze(&mut self) {
- self.storage.materialize();
- self.finish_delta();
- }
-
- pub(crate) fn finish_delta(&mut self) {
- if !self.frozen {
- self.storage.release_empty_sources();
- }
- self.frozen = true;
- }
-
- /// The stored value for a longhand, when the drive stored one.
- pub(crate) fn get(&self, property_id: u16) -> Option<&RetainedStyleValueData> {
- let value = self.storage.slot(Self::slot_index(property_id)).0;
- (!value.pointer().is_null()).then_some(value)
- }
-
- /// The cascade source slot of the declaration a longhand's value came
- /// from, recorded only when that declaration carries style sheet context.
- pub(crate) fn source_slot(&self, property_id: u16) -> Option<u32> {
- u32::try_from(self.storage.slot(Self::slot_index(property_id)).1).ok()
- }
-
- /// One raw data pointer per longhand slot, null where the drive stored no
- /// value. The span is stable for the table's lifetime once frozen.
- pub(crate) fn value_pointers(&self) -> &[*const c_void] {
- self.storage.value_pointers()
- }
-
- pub(crate) fn is_frozen(&self) -> bool {
- self.frozen
- }
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_computed_longhand_table_create() -> *mut ComputedLonghandTable {
- Arc::into_raw(Arc::new(ComputedLonghandTable::new())).cast_mut()
-}
-
-/// Takes one additional strong reference to a frozen table.
-///
-/// # Safety
-/// `table` must be a live strong reference; a table may only be shared once
-/// it is frozen, because the mutating calls require unique ownership.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_computed_longhand_table_retain(
- table: *const ComputedLonghandTable,
-) -> *const ComputedLonghandTable {
- debug_assert!(unsafe { &*table }.frozen, "only frozen tables are shared");
- unsafe { Arc::increment_strong_count(table) };
- table
-}
-
-/// Releases one strong reference.
-///
-/// # Safety
-/// `table` must be a live strong reference that is not used after this call;
-/// no references into the table may outlive the final release.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_computed_longhand_table_release(table: *mut ComputedLonghandTable) {
- unsafe { Arc::decrement_strong_count(table.cast_const()) };
-}
-
-/// Creates a frozen copy of `table` with every inherited longhand value taken
-/// from `inherited_source`.
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_computed_longhand_table_create_with_inherited_values(
- table: &ComputedLonghandTable,
- inherited_source: &ComputedLonghandTable,
-) -> *mut ComputedLonghandTable {
- table
- .with_inherited_values_from(inherited_source)
- .into_raw_shared()
- .cast_mut()
-}
-
-/// Stores one computed longhand, retaining `data`. `source_slot` is the
-/// winning declaration's cascade source slot when its value carries style
-/// sheet context, and -1 otherwise; storing without a slot clears any slot a
-/// previous store recorded for the longhand.
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_computed_longhand_table_set(
- table: &mut ComputedLonghandTable,
- property_id: u16,
- data: crate::css::ffi_support::ArcRef<'_, StyleValueData>,
- source_slot: i64,
-) {
- table.set(
- property_id,
- RetainedStyleValueData::from_arc(data.to_arc()),
- source_slot,
- );
-}
-
-/// Replaces the table's contents with `source`'s, for the C++ builder that
-/// starts from an existing style's property array.
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_computed_longhand_table_copy_from(
- table: &mut ComputedLonghandTable,
- source: &ComputedLonghandTable,
-) {
- table.copy_from(source);
-}
-
-/// Replaces the table's values with a complete borrowed value span, retaining
-/// every non-null entry. The style-sheet-context sidecar is cleared: a span
-/// borrowed from a published style record carries no usable cascade slots.
-///
-/// # Safety
-/// `table` must be a valid, unfrozen, uniquely owned table and `values` must
-/// have exactly one readable entry per longhand, each null or pointing at
-/// live `StyleValueData`.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_computed_longhand_table_copy_from_values(
- table: &mut ComputedLonghandTable,
- values: *const *const c_void,
- count: usize,
-) {
- let values = unsafe { ak::slice_from_raw_parts(values, count) };
- table.copy_from_values(values);
-}
-
-/// Returns the table's value span: one borrowed data pointer per longhand,
-/// null where the drive stored no value. The span stays valid while the
-/// caller's table reference is live and the table stays frozen.
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_computed_longhand_table_values(table: &ComputedLonghandTable) -> *const *const c_void {
- debug_assert!(table.frozen, "only frozen tables hand out their value span");
- table.value_pointers().as_ptr()
-}
-
-/// Whether two frozen tables have equal values and publication metadata.
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_computed_longhand_tables_equal_for_publication(
- first: &ComputedLonghandTable,
- second: &ComputedLonghandTable,
-) -> bool {
- first.publication_equals(second)
-}
-
-/// Makes the table immutable; every later store aborts. Only a frozen table
-/// may be shared through `rust_computed_longhand_table_retain`.
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_computed_longhand_table_freeze(table: &mut ComputedLonghandTable) {
- table.freeze();
-}
-
-/// The importance bitmap, in the C++ `FixedBitmap` byte layout. The pointer
-/// stays valid while the caller's table reference is live.
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_computed_longhand_table_importance_bits(table: &ComputedLonghandTable) -> *const u8 {
- table.important_bits.as_ptr()
-}
-
-/// The inheritance bitmap, in the C++ `FixedBitmap` byte layout.
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_computed_longhand_table_inheritance_bits(table: &ComputedLonghandTable) -> *const u8 {
- table.inherited_bits.as_ptr()
-}
-
-/// Replaces the whole importance and inheritance bitmaps, for the builder
-/// seeding a fresh table from an existing style's published bitmaps.
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_computed_longhand_table_load_flag_bitmaps(
- table: &mut ComputedLonghandTable,
- importance: ak::Span<'_, u8>,
- inheritance: ak::Span<'_, u8>,
-) {
- table.load_flag_bitmaps(importance.as_slice(), inheritance.as_slice());
-}
-
-/// Resets the state a fresh drive must not inherit from the style its table
-/// was seeded from: the evaluated bits and the recorded inheritance-dependent
-/// specified values.
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_computed_longhand_table_clear_seeded_state(table: &mut ComputedLonghandTable) {
- table.clear_seeded_state();
-}
-
-/// Records (or replaces) a longhand's inheritance-dependent specified value,
-/// retaining `value`.
-///
-/// # Safety
-/// `table` must be a valid, unfrozen, uniquely owned table and `value` must
-/// point at live style value data.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_computed_longhand_table_add_inheritance_dependent_value(
- table: &mut ComputedLonghandTable,
- property_id: u16,
- value: *const c_void,
-) {
- let value = unsafe {
- RetainedStyleValueData::from_retained_pointer(crate::css::style_value::retain_style_value(value.cast()))
- };
- table.add_inheritance_dependent_value(property_id, value);
-}
-
-/// Returns the non-longhand computation state stored alongside the table.
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_computed_longhand_table_metadata(
- table: &mut ComputedLonghandTable,
-) -> *mut FfiComputedStyleMetadata {
- &raw mut table.metadata
-}
-
-/// The recorded inheritance-dependent specified values as a borrowed span.
-/// The span stays valid while the caller's table reference is live and no
-/// further add or remove mutates the table.
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_computed_longhand_table_inheritance_dependent_values(
- table: &ComputedLonghandTable,
- out_count: &mut usize,
-) -> *const FfiTableInheritanceDependentValue {
- *out_count = table.inheritance_dependent_view.len();
- table.inheritance_dependent_view.as_ptr()
+ .filter(|(property, _)| {
+ !property_is_inherited(*property)
+ && inheritance_dependent_value_changed(old.clone(), new.clone(), *property)
+ })
+ .fold(0, |groups, (property, _)| {
+ groups
+ | match crate::css::computed_values::StyleGroupMasks::get().dependencies(property) {
+ 0 => u32::MAX,
+ mask => mask,
+ }
+ })
}
-/// The non-inherited groups whose inheritance-dependent source values changed.
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_computed_longhand_table_non_inherited_inheritance_changes(
- old: &ComputedLonghandTable,
- new: &ComputedLonghandTable,
-) -> u32 {
- old.non_inherited_inheritance_changes(new)
-}
+/// The dependency-flag bit of a record holding a value resolved against the viewport, as a `vw`
+/// length is.
+pub(crate) const DEPENDS_ON_VIEWPORT_METRICS: u8 = 1;
+/// The dependency-flag bit of a record whose font metrics read the viewport, as a `vw` font size
+/// does: what `em` and the other font-relative units resolve against moves with the viewport.
+pub(crate) const FONT_METRICS_DEPEND_ON_VIEWPORT_METRICS: u8 = 1 << 1;
+/// The dependency-flag bit of a record whose element is `display: none` or inherits from one that is.
+pub(crate) const IN_DISPLAY_NONE_SUBTREE: u8 = 1 << 2;
+/// The dependency-flag bit of a highlight pseudo-element record whose `color` or `background-color`
+/// comes from the author origin, on itself or up its highlight chain, so the paired default colors
+/// do not apply. Bits 0 to 4 are the viewport, font-metric, display-none, swap-eligibility and image
+/// flags.
+/// https://drafts.csswg.org/css-pseudo-4/#paired-defaults
+pub(crate) const HIGHLIGHT_COLORS_AUTHORED: u8 = 1 << 5;
+/// The dependency-flag bit of a highlight pseudo-element record whose `color` is currentColor: the
+/// computed value is the originating element's color, but painting draws the layer below instead.
+/// https://drafts.csswg.org/css-pseudo-4/#highlight-text
+pub(crate) const HIGHLIGHT_COLOR_IS_CURRENT_COLOR: u8 = 1 << 6;
+/// The dependency-flag bit of a record with a cascaded value from the author origin for any property that disables
+/// native appearance for widgets.
+/// https://drafts.csswg.org/css-ui/#appearance-disabling-properties
+pub(crate) const NATIVE_APPEARANCE_DISABLED: u8 = 1 << 7;
-/// The effective value for one longhand: the animated overlay under the
-/// overlay read rule (important base values override animated but not
-/// transitioned properties), then an unevaluated longhand's recorded
-/// currentcolor-dependent specified value, then the stored table slot.
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_computed_longhand_table_effective_value(
- table: &ComputedLonghandTable,
- overlay: Option<&AnimatedOverlay>,
- property_id: u16,
- with_animations: bool,
-) -> FfiEffectiveLonghandValue {
- table.effective_value(overlay, property_id, with_animations)
+#[derive(Clone, Copy)]
+#[repr(C)]
+pub struct FfiComputedStyleMetadata {
+ pub display_before_box_type_transformation: u32,
+ pub effective_color_scheme: i16,
+ pub dependency_flags: u8,
+ pub in_display_none_subtree: bool,
}
#[cfg(test)]
mod tests {
- use std::sync::Arc;
+ use crate::css::style_value_arc::StyleValueArc;
use super::*;
+ use crate::css::property_metadata::property_id;
use crate::css::style_value::StyleValueData;
- fn retained_number(value: f64) -> RetainedStyleValueData {
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Number { value }))
+ type Recorded = Vec<(u16, RetainedStyleValueData)>;
+
+ fn entry((property, value): &(u16, RetainedStyleValueData)) -> (u16, &RetainedStyleValueData) {
+ (*property, value)
+ }
+
+ fn table_inheritance_changes(old: &Recorded, new: &Recorded) -> u32 {
+ non_inherited_inheritance_changes(old.iter().map(entry), new.iter().map(entry))
}
#[test]
fn inheritance_source_changes_keep_their_exact_non_inherited_group() {
- let mut current_color = ComputedLonghandTable::new();
- current_color.add_inheritance_dependent_value(
+ let current_color: Recorded = vec![(
property_id::TEXT_DECORATION_COLOR,
RetainedStyleValueData::from_owned(StyleValueData::Keyword {
keyword: crate::css::style_compute::keyword::CURRENTCOLOR,
}),
- );
- let mut equal = ComputedLonghandTable::new();
- equal.add_inheritance_dependent_value(
+ )];
+ let equal: Recorded = vec![(
property_id::TEXT_DECORATION_COLOR,
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Keyword {
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Keyword {
keyword: crate::css::style_compute::keyword::CURRENTCOLOR,
})),
- );
- assert_eq!(current_color.non_inherited_inheritance_changes(&equal), 0);
- let resolved = ComputedLonghandTable::new();
- let expected = 1 << crate::css::computed_value_types::STYLE_GROUP_INDEX_TEXT_RESET;
- assert_eq!(current_color.non_inherited_inheritance_changes(&resolved), expected);
- assert_eq!(resolved.non_inherited_inheritance_changes(&current_color), expected);
- assert_eq!(
- current_color.non_inherited_inheritance_changes(&current_color.clone()),
- 0
- );
+ )];
+ assert_eq!(table_inheritance_changes(&current_color, &equal), 0);
+ let resolved = Recorded::new();
+ let expected = 1 << crate::css::table_group_builder::group_index::TEXT_RESET;
+ assert_eq!(table_inheritance_changes(&current_color, &resolved), expected);
+ assert_eq!(table_inheritance_changes(&resolved, &current_color), expected);
+ assert_eq!(table_inheritance_changes(&current_color, &current_color.clone()), 0);
}
#[test]
fn inherited_source_changes_do_not_mark_non_inherited_groups() {
- let mut current_color = ComputedLonghandTable::new();
- current_color.add_inheritance_dependent_value(
+ let current_color: Recorded = vec![(
property_id::COLOR,
RetainedStyleValueData::from_owned(StyleValueData::Keyword {
keyword: crate::css::style_compute::keyword::CURRENTCOLOR,
}),
- );
- assert_eq!(
- current_color.non_inherited_inheritance_changes(&ComputedLonghandTable::new()),
- 0
- );
- }
-
- #[test]
- fn partial_delta_borrows_base_values_and_preserves_sidecars() {
- let mut source = ComputedLonghandTable::new();
- source.set(property_id::OPACITY, retained_number(0.5), 9);
- source.set(property_id::Z_INDEX, retained_number(7.0), 4);
- source.set_important(property_id::Z_INDEX, true);
- source.set_inherited(property_id::Z_INDEX, true);
- source.freeze();
- let value = source.get(property_id::Z_INDEX).unwrap().clone().into_arc();
- let owners = Arc::strong_count(&value);
- let mut delta = ComputedLonghandTable::copied_for_partial_drive(&source);
- assert_eq!(Arc::strong_count(&value), owners);
- assert!(delta.evaluated_bits().iter().all(|&bits| bits == 0));
- assert_eq!(delta.source_slot(property_id::Z_INDEX), Some(4));
- assert!(delta.is_important(property_id::Z_INDEX));
- assert!(delta.is_inherited(property_id::Z_INDEX));
- delta.set(property_id::OPACITY, retained_number(0.75), -1);
- delta.set(property_id::Z_INDEX, retained_number(8.0), -1);
- delta.copy_slot_from(&source, property_id::Z_INDEX);
- assert_eq!(Arc::strong_count(&value), owners);
- assert_eq!(delta.source_slot(property_id::Z_INDEX), Some(4));
- assert!(source.get(property_id::OPACITY).unwrap().data() == &StyleValueData::Number { value: 0.5 });
- assert_eq!(delta.slot_hash_sum(), delta.recomputed_slot_hash_sum());
- drop(source);
- assert_eq!(Arc::strong_count(&value), owners);
- delta.freeze();
- assert!(matches!(delta.storage, SlotStorage::Dense(_)));
- assert!(delta.get(property_id::Z_INDEX).unwrap().data() == value.as_ref());
- assert_eq!(Arc::strong_count(&value), owners);
- drop(delta);
- assert_eq!(Arc::strong_count(&value), owners - 1);
- }
-
- #[test]
- fn slot_values_compare_over_a_shared_base_and_across_bases() {
- let equal = crate::css::style_value::retained_style_values_equal;
- let mut base = ComputedLonghandTable::new();
- base.set(property_id::OPACITY, retained_number(0.5), -1);
- base.set(property_id::Z_INDEX, retained_number(7.0), -1);
- base.freeze();
-
- let mut kept = ComputedLonghandTable::copied_for_drive(&base);
- kept.set_or_keep_equal(property_id::Z_INDEX, retained_number(7.0), -1);
- kept.set(property_id::OPACITY, retained_number(0.5), -1);
- kept.finish_delta();
- assert!(matches!(kept.storage, SlotStorage::Delta { .. }));
- assert!(base.storage.values_are_equal(&kept.storage, equal));
- assert!(kept.storage.values_are_equal(&base.storage, equal));
-
- let mut moved = ComputedLonghandTable::copied_for_drive(&base);
- moved.set(property_id::Z_INDEX, retained_number(8.0), -1);
- moved.finish_delta();
- assert!(!base.storage.values_are_equal(&moved.storage, equal));
- assert!(!moved.storage.values_are_equal(&base.storage, equal));
-
- // Tables over separate storage compare slot by slot, a delta's changes merged in order.
- let mut other_base = ComputedLonghandTable::new();
- other_base.set(property_id::OPACITY, retained_number(0.5), -1);
- other_base.set(property_id::Z_INDEX, retained_number(8.0), -1);
- other_base.freeze();
- assert!(other_base.storage.values_are_equal(&moved.storage, equal));
- assert!(moved.storage.values_are_equal(&other_base.storage, equal));
- assert!(!other_base.storage.values_are_equal(&kept.storage, equal));
- let mut other_moved = ComputedLonghandTable::copied_for_drive(&other_base);
- other_moved.set(property_id::OPACITY, retained_number(0.25), -1);
- other_moved.finish_delta();
- assert!(!other_moved.storage.values_are_equal(&moved.storage, equal));
- let mut moved_again = ComputedLonghandTable::copied_for_drive(&base);
- moved_again.set(property_id::Z_INDEX, retained_number(8.0), -1);
- moved_again.set(property_id::OPACITY, retained_number(0.25), -1);
- moved_again.finish_delta();
- assert!(other_moved.storage.values_are_equal(&moved_again.storage, equal));
- assert_eq!(moved_again.storage.values().count(), LONGHAND_COUNT);
- }
-
- #[test]
- fn set_retains_and_release_drops() {
- let value = Arc::new(StyleValueData::Number { value: 42.0 });
- let weak_value = Arc::downgrade(&value);
- let retained_value = RetainedStyleValueData::from_arc(value);
-
- let mut table = ComputedLonghandTable::new();
- table.set(FIRST_LONGHAND_PROPERTY_ID, retained_value, -1);
- assert!(table.get(FIRST_LONGHAND_PROPERTY_ID).is_some());
- assert_eq!(table.source_slot(FIRST_LONGHAND_PROPERTY_ID), None);
- assert!(weak_value.upgrade().is_some());
-
- drop(table);
- assert!(weak_value.upgrade().is_none());
- }
-
- #[test]
- fn copying_empty_slots_releases_values_and_updates_the_pointer_view() {
- let value = Arc::new(StyleValueData::Number { value: 42.0 });
- let weak_value = Arc::downgrade(&value);
- let retained_value = RetainedStyleValueData::from_arc(value);
- let mut source = ComputedLonghandTable::new();
- source.set(FIRST_LONGHAND_PROPERTY_ID, retained_value, 3);
- let mut copy = ComputedLonghandTable::new();
- copy.copy_from(&source);
- assert_eq!(copy.value_pointers(), source.value_pointers());
- assert!(copy.get(LAST_LONGHAND_PROPERTY_ID).is_none());
-
- let empty_values = [std::ptr::null(); LONGHAND_COUNT];
- source.copy_from_values(&empty_values);
- assert!(source.get(FIRST_LONGHAND_PROPERTY_ID).is_none());
- assert_eq!(source.value_pointers(), empty_values);
- assert!(weak_value.upgrade().is_some());
-
- copy.copy_from(&source);
- assert!(copy.get(FIRST_LONGHAND_PROPERTY_ID).is_none());
- assert_eq!(copy.value_pointers(), empty_values);
- assert!(weak_value.upgrade().is_none());
- }
-
- #[test]
- fn source_slot_storage_is_absent_when_no_value_needs_sheet_context() {
- let mut table = ComputedLonghandTable::new();
- table.set(FIRST_LONGHAND_PROPERTY_ID, retained_number(42.0), -1);
- assert!(!table.storage.has_source_slots());
- table.set(FIRST_LONGHAND_PROPERTY_ID, retained_number(42.0), 7);
- assert!(table.storage.has_source_slots());
- assert_eq!(table.source_slot(FIRST_LONGHAND_PROPERTY_ID), Some(7));
- table.set(FIRST_LONGHAND_PROPERTY_ID, retained_number(42.0), -1);
- let pointers = table.value_pointers().as_ptr();
- table.freeze();
- assert!(!table.storage.has_source_slots());
- assert_eq!(table.value_pointers().as_ptr(), pointers);
- assert_eq!(table.source_slot(FIRST_LONGHAND_PROPERTY_ID), None);
- }
-
- #[test]
- fn source_slot_sidecar_follows_overwrites() {
- let mut table = ComputedLonghandTable::new();
- table.set(FIRST_LONGHAND_PROPERTY_ID, retained_number(1.0), 7);
- assert_eq!(table.source_slot(FIRST_LONGHAND_PROPERTY_ID), Some(7));
-
- table.set(FIRST_LONGHAND_PROPERTY_ID, retained_number(2.0), 9);
- assert_eq!(table.source_slot(FIRST_LONGHAND_PROPERTY_ID), Some(9));
-
- table.set(FIRST_LONGHAND_PROPERTY_ID, retained_number(3.0), -1);
- assert_eq!(table.source_slot(FIRST_LONGHAND_PROPERTY_ID), None);
- }
-
- #[test]
- fn copy_from_values_retains_entries_and_clears_sidecar() {
- let mut source = ComputedLonghandTable::new();
- source.set(FIRST_LONGHAND_PROPERTY_ID, retained_number(1.0), 3);
- let source_pointer = source.get(FIRST_LONGHAND_PROPERTY_ID).unwrap().pointer();
-
- let mut copy = ComputedLonghandTable::new();
- let source_values = source.value_pointers().to_vec();
- copy.copy_from_values(&source_values);
- drop(source);
-
- assert_eq!(copy.get(FIRST_LONGHAND_PROPERTY_ID).unwrap().pointer(), source_pointer);
- assert_eq!(copy.value_pointers()[0], source_pointer.cast());
- assert_eq!(copy.source_slot(FIRST_LONGHAND_PROPERTY_ID), None);
- }
-
- #[test]
- fn copy_from_replicates_slots_and_sidecar() {
- let mut source = ComputedLonghandTable::new();
- source.set(FIRST_LONGHAND_PROPERTY_ID, retained_number(1.0), 3);
- let source_pointer = source.get(FIRST_LONGHAND_PROPERTY_ID).unwrap().pointer();
-
- let mut copy = ComputedLonghandTable::new();
- copy.copy_from(&source);
- drop(source);
-
- assert_eq!(copy.get(FIRST_LONGHAND_PROPERTY_ID).unwrap().pointer(), source_pointer);
- assert_eq!(copy.source_slot(FIRST_LONGHAND_PROPERTY_ID), Some(3));
- }
-
- #[test]
- fn dependency_flags_follow_the_table() {
- let mut source = ComputedLonghandTable::new();
- source.merge_dependency_flags(true, false, false, false);
-
- let mut copy = ComputedLonghandTable::new();
- copy.copy_from(&source);
- assert_eq!(copy.dependency_flags(), 1);
-
- copy.merge_dependency_flags(false, true, false, false);
- assert_eq!(copy.dependency_flags(), 3);
- }
-
- #[test]
- fn slot_hash_sum_follows_every_slot_write() {
- let mut source = ComputedLonghandTable::new();
- source.set(property_id::OPACITY, retained_number(1.0), -1);
- assert_eq!(source.slot_hash_sum(), source.recomputed_slot_hash_sum());
- source.set(property_id::OPACITY, retained_number(0.5), -1);
- source.set(property_id::Z_INDEX, retained_number(3.0), -1);
- source.set(property_id::OPACITY, retained_number(0.25), -1);
- assert_eq!(source.slot_hash_sum(), source.recomputed_slot_hash_sum());
-
- let mut seeded = ComputedLonghandTable::copied_for_partial_drive(&source);
- assert_eq!(seeded.slot_hash_sum(), source.slot_hash_sum());
- seeded.set(property_id::Z_INDEX, retained_number(4.0), -1);
- assert_ne!(seeded.slot_hash_sum(), source.slot_hash_sum());
- assert_eq!(seeded.slot_hash_sum(), seeded.recomputed_slot_hash_sum());
- seeded.copy_slot_from(&source, property_id::Z_INDEX);
- assert_eq!(seeded.slot_hash_sum(), source.slot_hash_sum());
-
- let mut copied = ComputedLonghandTable::new();
- copied.copy_from_values(source.value_pointers());
- assert_eq!(copied.slot_hash_sum(), source.slot_hash_sum());
- }
-
- #[test]
- fn set_computed_keeps_an_equal_value_and_replaces_a_different_one() {
- let mut table = ComputedLonghandTable::new();
- table.set(property_id::OPACITY, retained_number(0.5), 7);
- let original = table.get(property_id::OPACITY).unwrap().pointer();
-
- table.set_computed(property_id::OPACITY, StyleValueData::Number { value: 0.5 }, -1);
- assert_eq!(table.get(property_id::OPACITY).unwrap().pointer(), original);
- assert_eq!(table.source_slot(property_id::OPACITY), None);
-
- table.set_computed(property_id::OPACITY, StyleValueData::Number { value: 0.75 }, -1);
- assert_ne!(table.get(property_id::OPACITY).unwrap().pointer(), original);
- assert_eq!(table.slot_hash_sum(), table.recomputed_slot_hash_sum());
- }
-
- #[test]
- fn set_or_keep_equal_keeps_the_existing_allocation() {
- let mut table = ComputedLonghandTable::new();
- table.set(property_id::OPACITY, retained_number(0.5), -1);
- let original = table.get(property_id::OPACITY).unwrap().pointer();
- let equal = retained_number(0.5);
- assert_ne!(equal.pointer(), original);
- table.set_or_keep_equal(property_id::OPACITY, equal, -1);
- assert_eq!(table.get(property_id::OPACITY).unwrap().pointer(), original);
- let different = retained_number(1.0);
- let different_pointer = different.pointer();
- table.set_or_keep_equal(property_id::OPACITY, different, -1);
- assert_eq!(table.get(property_id::OPACITY).unwrap().pointer(), different_pointer);
- }
-
- #[test]
- fn merge_driver_flags_touches_only_evaluated_slots() {
- let mut table = ComputedLonghandTable::new();
- let words = LONGHAND_COUNT.div_ceil(64);
- let mut important = vec![u64::MAX; words];
- let inherited = vec![u64::MAX; words];
- let mut evaluated = vec![0_u64; words];
- let z_index = ComputedLonghandTable::slot_index(property_id::Z_INDEX);
- evaluated[z_index / 64] |= 1 << (z_index % 64);
- important[z_index / 64] &= !(1 << (z_index % 64));
- table.merge_driver_flags(&important, &inherited, &evaluated);
- assert!(!table.is_important(property_id::Z_INDEX));
- assert!(table.is_inherited(property_id::Z_INDEX));
- assert!(!table.is_important(property_id::OPACITY));
- assert!(!table.is_inherited(property_id::OPACITY));
- }
-
- #[test]
- fn frozen_transition_longhands_resolve_once() {
- let mut table = ComputedLonghandTable::new();
- let mut resolutions = 0;
- let mut resolve = |_: &ComputedLonghandTable| {
- resolutions += 1;
- Box::from([property_id::OPACITY])
- };
- assert!(table.frozen_transition_longhands(&mut resolve).is_none());
- table.freeze();
- assert_eq!(
- table.frozen_transition_longhands(&mut resolve),
- Some(&[property_id::OPACITY][..])
- );
- assert_eq!(
- table.frozen_transition_longhands(&mut resolve),
- Some(&[property_id::OPACITY][..])
- );
- assert_eq!(resolutions, 1);
+ )];
+ assert_eq!(table_inheritance_changes(&current_color, &Recorded::new()), 0);
}
}
-
-/// A frozen table is read by every worker that seeds a drive from it, and travels to one inside a
-/// produced record's scratch, so it has to be both. Its lazily-filled memos are the only writes a
-/// shared table sees, and both are atomic (see `MemoizedHashSum` and the `OnceLock`s above).
-const _: () = {
- const fn assert_sync<T: Sync>() {}
- const fn assert_send<T: Send>() {}
- assert_sync::<ComputedLonghandTable>();
- assert_send::<ComputedLonghandTable>();
-};
diff --git a/Libraries/LibWeb/Rust/src/css/computed_value_types.rs b/Libraries/LibWeb/Rust/src/css/computed_value_types.rs
index b28386a4cc1..463aabd7171 100644
--- a/Libraries/LibWeb/Rust/src/css/computed_value_types.rs
+++ b/Libraries/LibWeb/Rust/src/css/computed_value_types.rs
@@ -190,18 +190,10 @@ impl ComputedContainIntrinsicSize {
pub struct BoxValues {
pub display: crate::css::display::FfiDisplay,
pub display_before_box_type_transformation: crate::css::display::FfiDisplay,
- pub float_: u8,
- pub clear: u8,
- pub position: u8,
- pub overflow_x: u8,
- pub overflow_y: u8,
- pub box_sizing: u8,
pub field_sizing: u8,
pub baseline_source: u8,
pub resize: u8,
pub text_overflow: u8,
- pub unicode_bidi: u8,
- pub table_layout: u8,
pub grid_auto_flow_row: bool,
pub grid_auto_flow_dense: bool,
pub column_width: ComputedSize,
@@ -226,13 +218,134 @@ pub struct BoxValues {
pub container_name: crate::css::retained_fly_string::RetainedUtf16FlyStringList,
}
+/// The first group index of the rare group set a style shares; the inherited set's groups come
+/// before it, from index zero.
+pub const STYLE_GROUP_RARE_SET_START: usize = 5;
+/// The first group index of the visual group set a style shares.
+pub const STYLE_GROUP_VISUAL_SET_START: usize = 13;
+/// The first group index of the groups a style keeps in its root, which run to the last group.
+pub const STYLE_GROUP_ROOT_START: usize = 19;
+
+/// The inherited longhands of few keywords a style holds as bits beside its inherited groups, in
+/// place of a field of a group: each the code of its keyword in the CSS enum of the property, at
+/// the field's shift.
+#[repr(transparent)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
+pub struct InheritedBits(pub u32);
+
+pub const INHERITED_BITS_WRITING_MODE_SHIFT: u32 = 0;
+pub const INHERITED_BITS_WRITING_MODE_WIDTH: u32 = 3;
+pub const INHERITED_BITS_DIRECTION_SHIFT: u32 = 3;
+pub const INHERITED_BITS_DIRECTION_WIDTH: u32 = 1;
+pub const INHERITED_BITS_VISIBILITY_SHIFT: u32 = 4;
+pub const INHERITED_BITS_VISIBILITY_WIDTH: u32 = 2;
+pub const INHERITED_BITS_TEXT_ORIENTATION_SHIFT: u32 = 6;
+pub const INHERITED_BITS_TEXT_ORIENTATION_WIDTH: u32 = 2;
+pub const INHERITED_BITS_POINTER_EVENTS_SHIFT: u32 = 8;
+pub const INHERITED_BITS_POINTER_EVENTS_WIDTH: u32 = 4;
+pub const INHERITED_BITS_LIST_STYLE_POSITION_SHIFT: u32 = 12;
+pub const INHERITED_BITS_LIST_STYLE_POSITION_WIDTH: u32 = 1;
+pub const INHERITED_BITS_BORDER_COLLAPSE_SHIFT: u32 = 13;
+pub const INHERITED_BITS_BORDER_COLLAPSE_WIDTH: u32 = 1;
+pub const INHERITED_BITS_CAPTION_SIDE_SHIFT: u32 = 14;
+pub const INHERITED_BITS_CAPTION_SIDE_WIDTH: u32 = 1;
+pub const INHERITED_BITS_EMPTY_CELLS_SHIFT: u32 = 15;
+pub const INHERITED_BITS_EMPTY_CELLS_WIDTH: u32 = 1;
+pub const INHERITED_BITS_TEXT_ALIGN_SHIFT: u32 = 16;
+pub const INHERITED_BITS_TEXT_ALIGN_WIDTH: u32 = 4;
+pub const INHERITED_BITS_WHITE_SPACE_COLLAPSE_SHIFT: u32 = 20;
+pub const INHERITED_BITS_WHITE_SPACE_COLLAPSE_WIDTH: u32 = 3;
+pub const INHERITED_BITS_TEXT_WRAP_MODE_SHIFT: u32 = 23;
+pub const INHERITED_BITS_TEXT_WRAP_MODE_WIDTH: u32 = 1;
+pub const INHERITED_BITS_WORD_BREAK_SHIFT: u32 = 24;
+pub const INHERITED_BITS_WORD_BREAK_WIDTH: u32 = 2;
+
+/// The keywords of few values of properties that do not inherit a style holds as bits in its
+/// root beside its own groups, in place of fields of its box group: each the code of its keyword
+/// in the CSS enum of the property, at the field's shift.
+#[repr(transparent)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
+pub struct ResetBits(pub u32);
+
+pub const RESET_BITS_POSITION_SHIFT: u32 = 0;
+pub const RESET_BITS_POSITION_WIDTH: u32 = 3;
+pub const RESET_BITS_FLOAT_SHIFT: u32 = 3;
+pub const RESET_BITS_FLOAT_WIDTH: u32 = 3;
+pub const RESET_BITS_CLEAR_SHIFT: u32 = 6;
+pub const RESET_BITS_CLEAR_WIDTH: u32 = 3;
+pub const RESET_BITS_OVERFLOW_X_SHIFT: u32 = 9;
+pub const RESET_BITS_OVERFLOW_X_WIDTH: u32 = 3;
+pub const RESET_BITS_OVERFLOW_Y_SHIFT: u32 = 12;
+pub const RESET_BITS_OVERFLOW_Y_WIDTH: u32 = 3;
+pub const RESET_BITS_BOX_SIZING_SHIFT: u32 = 15;
+pub const RESET_BITS_BOX_SIZING_WIDTH: u32 = 1;
+pub const RESET_BITS_UNICODE_BIDI_SHIFT: u32 = 16;
+pub const RESET_BITS_UNICODE_BIDI_WIDTH: u32 = 3;
+pub const RESET_BITS_TABLE_LAYOUT_SHIFT: u32 = 19;
+pub const RESET_BITS_TABLE_LAYOUT_WIDTH: u32 = 1;
+
+/// What a style's inherited set holds beside its groups for its readers to read directly: the
+/// inherited longhands held as bits, and the effective zoom.
+#[repr(C)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
+pub struct InheritedSetValues {
+ pub bits: InheritedBits,
+ /// https://drafts.csswg.org/css-viewport/#effective-zoom
+ /// The bits of the effective zoom, as an `f32`.
+ pub effective_zoom_bits: u32,
+}
+
+/// What a style holds as bits beside its groups: the inherited bits and zoom beside its inherited
+/// set's groups, and the reset bits in its root.
+#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
+pub struct StyleBits {
+ pub inherited: InheritedSetValues,
+ pub reset: ResetBits,
+}
+
+/// A computed color as a group holds it: a color, or `currentcolor`, which its reader resolves
+/// against the element's color, so that the group does not depend on the element's color.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+#[repr(C)]
+pub struct StyleColor {
+ /// The color, in the C++ Color::value() bit layout; unused for `currentcolor`.
+ pub rgba: u32,
+ pub is_current_color: bool,
+}
+
+const _: () = assert!(size_of::<StyleColor>() == 8);
+
+impl StyleColor {
+ pub const CURRENT_COLOR: Self = Self {
+ rgba: 0,
+ is_current_color: true,
+ };
+
+ pub const fn rgba(rgba: u32) -> Self {
+ Self {
+ rgba,
+ is_current_color: false,
+ }
+ }
+
+ /// The color, with `currentcolor` resolved to `current_color`.
+ #[inline]
+ pub const fn resolve(self, current_color: u32) -> u32 {
+ if self.is_current_color {
+ current_color
+ } else {
+ self.rgba
+ }
+ }
+}
+
/// One computed border side, mirroring the C++ BorderData member layout:
/// color, line style, used width. Layout reads the line style and width
/// everywhere, and table border conflict resolution also reads the color.
#[repr(C)]
#[derive(Clone, PartialEq)]
pub struct ComputedBorderSide {
- pub color: u32,
+ pub color: StyleColor,
pub line_style: u8,
pub width: crate::css::css_pixels::CssPixels,
}
@@ -291,14 +404,16 @@ pub struct ContentValues {
pub counter_set: ComputedStyleValueHandle,
}
-/// Canonical inherited list values. Counter-style and image presentation
-/// objects are resolved lazily by consumers with their current style scope.
+/// Canonical inherited list and table values. Counter-style and image presentation objects are
+/// resolved lazily by consumers with their current style scope. The table enum fields follow the
+/// opaque-byte convention; the border spacings are raw CSSPixels fixed-point values.
#[repr(C)]
-pub struct InheritedListValues {
+pub struct InheritedListTableValues {
pub list_style_type: ComputedStyleValueHandle,
- pub list_style_position: u8,
pub list_style_image: ComputedStyleValueHandle,
pub quotes: ComputedStyleValueHandle,
+ pub border_spacing_horizontal: i32,
+ pub border_spacing_vertical: i32,
}
/// One physical overflow-clip-margin side.
@@ -325,12 +440,12 @@ pub struct RetainedWillChangePropertyList {
pub length: usize,
}
-/// Canonical non-inherited values which do not form a more specific group.
+/// The non-inherited values of how a box lays out and outlines that no more specific group holds:
+/// appearance, fragmentation breaks, columns, object fitting, outlines, overflow clip margins and
+/// float shapes.
#[repr(C)]
-pub struct MiscResetValues {
+pub struct MiscLayoutValues {
pub outline_offset_style_value: ComputedStyleValueHandle,
- pub scroll_margin: ComputedLengthBox,
- pub scroll_padding: ComputedLengthBox,
pub overflow_clip_margin: ComputedOverflowClipMargin,
pub column_span: u8,
pub break_before: u8,
@@ -346,15 +461,30 @@ pub struct MiscResetValues {
pub outline_style: u8,
pub object_fit: u8,
pub column_height: ComputedSize,
- pub outline_color: u32,
+ pub outline_color: StyleColor,
pub outline_width: crate::css::css_pixels::CssPixels,
- pub column_rule_color: u32,
+ pub column_rule_color: StyleColor,
pub column_rule_width: crate::css::css_pixels::CssPixels,
pub outline_offset: crate::css::css_pixels::CssPixels,
- pub user_select: u8,
pub object_position_x: ComputedStyleValueHandle,
pub object_position_y: ComputedStyleValueHandle,
+ pub shape_image_threshold: f64,
+ pub shape_margin: ComputedStyleValueHandle,
+ pub shape_outside: ComputedStyleValueHandle,
+ pub content_visibility: u8,
+}
+
+/// The non-inherited values of how a box scrolls and responds to the user that no more specific
+/// group holds: scrolling, scroll snapping, scrollbars, overscroll, user selection, view
+/// transitions and will-change.
+#[repr(C)]
+pub struct MiscInteractionValues {
+ pub scroll_margin: ComputedLengthBox,
+ pub scroll_padding: ComputedLengthBox,
pub view_transition_name: ComputedStyleValueHandle,
+ pub will_change: ComputedStyleValueHandle,
+ pub implicit_will_change: RetainedWillChangePropertyList,
+ pub user_select: u8,
pub scroll_behavior: u8,
pub scroll_snap_align_block: u8,
pub scroll_snap_align_inline: u8,
@@ -365,11 +495,6 @@ pub struct MiscResetValues {
pub scrollbar_width: u8,
pub overscroll_behavior_x: u8,
pub overscroll_behavior_y: u8,
- pub shape_image_threshold: f64,
- pub shape_margin: ComputedStyleValueHandle,
- pub shape_outside: ComputedStyleValueHandle,
- pub will_change: ComputedStyleValueHandle,
- pub implicit_will_change: RetainedWillChangePropertyList,
}
/// A computed text-indent value, mirroring the C++ TextIndentData layout:
@@ -387,11 +512,7 @@ pub struct ComputedTextIndent {
/// C++ Variant it replaced has no FFI-stable layout.
#[repr(C)]
pub struct InheritedTextLayoutFacts {
- pub text_align: u8,
pub text_justify: u8,
- pub white_space_collapse: u8,
- pub text_wrap_mode: u8,
- pub word_break: u8,
pub line_break: u8,
pub tab_size_is_number: bool,
pub letter_spacing: crate::css::css_pixels::CssPixels,
@@ -420,11 +541,7 @@ pub struct ComputedTextUnderlineOffset {
/// Layout of the inherited text computed values.
#[repr(C)]
pub struct InheritedTextValues {
- pub text_align: u8,
pub text_justify: u8,
- pub white_space_collapse: u8,
- pub text_wrap_mode: u8,
- pub word_break: u8,
pub line_break: u8,
pub tab_size_is_number: bool,
pub letter_spacing: crate::css::css_pixels::CssPixels,
@@ -502,7 +619,7 @@ pub struct MaskValues {
/// C++ coordinates the repeatable lists only when painting consumes them.
#[repr(C)]
pub struct BackgroundValues {
- pub background_color: u32,
+ pub background_color: StyleColor,
pub background_color_style_value: ComputedStyleValueHandle,
pub background_color_clip: u8,
pub background_image: ComputedStyleValueHandle,
@@ -520,13 +637,19 @@ pub struct BackgroundValues {
#[repr(C)]
pub struct FontValues {
pub font_size: crate::css::css_pixels::CssPixels,
- pub line_height_used: crate::css::css_pixels::CssPixels,
+ /// The used line height as the style was computed, which a `normal` one of a cascade the font
+ /// computer published moves past once a load fills one of its faces in: read
+ /// [`FontValues::line_height_used`].
+ pub resolved_line_height_used: crate::css::css_pixels::CssPixels,
pub font_variant_emoji: u8,
- pub font_ascent: f32,
- pub font_descent: f32,
- pub font_x_height: f32,
- pub font_zero_advance: f32,
- pub first_available_font: *const std::ffi::c_void,
+ /// The first available font and its metrics as the cascade was resolved, which a cascade the
+ /// font computer published moves past once a load fills one of its faces in: read
+ /// [`FontValues::first_available_font_metrics`] and [`FontValues::first_available_font`].
+ pub resolved_font_ascent: f32,
+ pub resolved_font_descent: f32,
+ pub resolved_font_x_height: f32,
+ pub resolved_font_zero_advance: f32,
+ pub resolved_first_available_font: *const std::ffi::c_void,
pub font_cascade_list: libgfx_rust::font::FontCascadeListHandle,
/// The same cascade, frozen at publication: what the render pipeline reads. The live
/// list beside it is the document's, and only the document thread may look a code point
@@ -558,6 +681,65 @@ pub struct FontValues {
pub font_size_value: ComputedStyleValueHandle,
}
+/// The metrics of a style's first available font that lengths and line layout read.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct FirstAvailableFontMetrics {
+ pub ascent: f32,
+ pub descent: f32,
+ pub x_height: f32,
+ pub zero_advance: f32,
+}
+
+impl FontValues {
+ /// https://drafts.csswg.org/css-fonts/#first-available-font
+ /// The frozen cascade answers where the font computer published one: a load filling one of its
+ /// faces in moves the answer without a new style. A cascade nobody published (a unit test's)
+ /// answers what it was resolved with.
+ pub fn first_available_font(&self) -> Option<&libgfx_rust::font::FontHandle> {
+ Some(self.frozen_font_list.list()?.first_available_font())
+ }
+
+ /// https://drafts.csswg.org/css-inline-3/#line-height-property
+ /// The used line height. A `normal` one is decided by the metrics of the first available font,
+ /// read through the frozen cascade, so a load filling one of its faces in moves it without a
+ /// new style.
+ pub fn line_height_used(&self) -> crate::css::css_pixels::CssPixels {
+ let is_normal = matches!(
+ self.line_height.style_value(),
+ Some(crate::css::style_value::StyleValueData::Keyword { keyword })
+ if *keyword == crate::css::style_compute::keyword::NORMAL
+ );
+ if is_normal && let Some(font) = self.first_available_font() {
+ let facts = font.facts();
+ return crate::css::css_pixels::CssPixels::from_integer(
+ i64::from(facts.ascent.round() as i32) + i64::from(facts.descent.round() as i32),
+ );
+ }
+ self.resolved_line_height_used
+ }
+
+ /// The metrics of [`FontValues::first_available_font`].
+ pub fn first_available_font_metrics(&self) -> FirstAvailableFontMetrics {
+ match self.first_available_font() {
+ Some(font) => {
+ let facts = font.facts();
+ FirstAvailableFontMetrics {
+ ascent: facts.ascent,
+ descent: facts.descent,
+ x_height: facts.x_height,
+ zero_advance: facts.zero_advance,
+ }
+ }
+ None => FirstAvailableFontMetrics {
+ ascent: self.resolved_font_ascent,
+ descent: self.resolved_font_descent,
+ x_height: self.resolved_font_x_height,
+ zero_advance: self.resolved_font_zero_advance,
+ },
+ }
+ }
+}
+
pub const GRID_NO_INDEX: u32 = u32::MAX;
#[repr(C)]
@@ -685,9 +867,9 @@ pub struct SVGResetValues {
pub ry: ComputedLengthPercentageOrAuto,
pub x: ComputedStyleValueHandle,
pub y: ComputedStyleValueHandle,
- pub stop_color: u32,
+ pub stop_color: StyleColor,
pub stop_opacity: f32,
- pub flood_color: u32,
+ pub flood_color: StyleColor,
pub flood_opacity: f32,
pub vector_effect: u8,
}
@@ -707,7 +889,7 @@ pub struct TextResetValues {
pub text_decoration_thickness_kind: u8,
pub text_decoration_thickness: ComputedStyleValueHandle,
pub text_decoration_style: u8,
- pub text_decoration_color: u32,
+ pub text_decoration_color: StyleColor,
pub white_space_trim_discard_before: bool,
pub white_space_trim_discard_after: bool,
pub white_space_trim_discard_inner: bool,
@@ -799,7 +981,7 @@ pub struct ComputedShadow {
pub offset_y: i32,
pub blur_radius: i32,
pub spread_distance: i32,
- pub color: u32,
+ pub color: StyleColor,
pub color_syntax: u8,
pub placement: u32,
}
@@ -885,14 +1067,14 @@ pub struct AnchorValues {
pub position_visibility_no_overflow: bool,
}
-/// A computed caret-color or accent-color, keeping both the computed auto
-/// distinction and the resolved used color.
+/// A computed caret-color or accent-color, keeping the computed auto
+/// distinction beside the used color: `currentcolor` for an auto caret-color,
+/// the system accent color for an auto accent-color.
#[repr(C)]
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct ComputedColorOrAuto {
pub is_auto: bool,
- pub computed_color: u32,
- pub used_color: u32,
+ pub color: StyleColor,
}
/// One cursor list item: either a retained cursor() value or a predefined
@@ -924,13 +1106,13 @@ pub struct InheritedUIValues {
pub caret_color: ComputedColorOrAuto,
pub accent_color: ComputedColorOrAuto,
pub cursor: RetainedComputedCursorList,
- pub pointer_events: u8,
pub forced_color_adjust: u8,
pub interpolate_size: u8,
pub scrollbar_color: ComputedScrollbarColor,
pub color_scheme: u8,
pub color_schemes: crate::css::retained_fly_string::RetainedUtf16FlyStringList,
pub color_scheme_only: bool,
+ pub image_rendering: u8,
}
pub const SVG_PAINT_NONE: u8 = 0;
@@ -945,8 +1127,7 @@ pub struct ComputedSvgPaint {
pub kind: u8,
pub url: ComputedStyleValueHandle,
pub has_color: bool,
- pub color: u32,
- pub color_is_currentcolor: bool,
+ pub color: StyleColor,
}
/// One computed stroke-dasharray item: either a plain SVG number or a
@@ -993,25 +1174,24 @@ pub struct InheritedSVGValues {
// Registered indices of the style groups the computed-values view reads,
// pinned to the C++ StyleGroupIndex enum by static_asserts in
// LayoutRustBridge.cpp.
-pub const STYLE_GROUP_INDEX_INHERITED_TABLE: usize = 0;
-pub const STYLE_GROUP_INDEX_INHERITED_LIST: usize = 1;
-pub const STYLE_GROUP_INDEX_INHERITED_UI: usize = 2;
-pub const STYLE_GROUP_INDEX_INHERITED_SVG: usize = 3;
-pub const STYLE_GROUP_INDEX_INHERITED_TEXT: usize = 4;
-pub const STYLE_GROUP_INDEX_INHERITED_BOX: usize = 5;
-pub const STYLE_GROUP_INDEX_FONT: usize = 6;
-pub const STYLE_GROUP_INDEX_SVG_RESET: usize = 8;
-pub const STYLE_GROUP_INDEX_GRID: usize = 9;
-pub const STYLE_GROUP_INDEX_ANCHOR: usize = 10;
-pub const STYLE_GROUP_INDEX_EFFECTS: usize = 11;
-pub const STYLE_GROUP_INDEX_MASK: usize = 12;
-pub const STYLE_GROUP_INDEX_TEXT_RESET: usize = 13;
-pub const STYLE_GROUP_INDEX_CONTENT: usize = 14;
-pub const STYLE_GROUP_INDEX_TRANSFORM: usize = 15;
-pub const STYLE_GROUP_INDEX_BACKGROUND: usize = 16;
-pub const STYLE_GROUP_INDEX_BORDER: usize = 17;
-pub const STYLE_GROUP_INDEX_ALIGNMENT: usize = 18;
-pub const STYLE_GROUP_INDEX_MISC_RESET: usize = 19;
-pub const STYLE_GROUP_INDEX_SIZING: usize = 20;
-pub const STYLE_GROUP_INDEX_SURROUND: usize = 21;
-pub const STYLE_GROUP_INDEX_BOX: usize = 22;
+pub const STYLE_GROUP_INDEX_INHERITED_LIST_TABLE: usize = 0;
+pub const STYLE_GROUP_INDEX_INHERITED_UI: usize = 1;
+pub const STYLE_GROUP_INDEX_INHERITED_SVG: usize = 2;
+pub const STYLE_GROUP_INDEX_INHERITED_TEXT: usize = 3;
+pub const STYLE_GROUP_INDEX_FONT: usize = 4;
+pub const STYLE_GROUP_INDEX_SVG_RESET: usize = 6;
+pub const STYLE_GROUP_INDEX_GRID: usize = 7;
+pub const STYLE_GROUP_INDEX_ANCHOR: usize = 8;
+pub const STYLE_GROUP_INDEX_CONTENT: usize = 9;
+pub const STYLE_GROUP_INDEX_ALIGNMENT: usize = 10;
+pub const STYLE_GROUP_INDEX_MISC_LAYOUT: usize = 11;
+pub const STYLE_GROUP_INDEX_MISC_INTERACTION: usize = 12;
+pub const STYLE_GROUP_INDEX_EFFECTS: usize = 13;
+pub const STYLE_GROUP_INDEX_MASK: usize = 14;
+pub const STYLE_GROUP_INDEX_TEXT_RESET: usize = 15;
+pub const STYLE_GROUP_INDEX_TRANSFORM: usize = 16;
+pub const STYLE_GROUP_INDEX_BACKGROUND: usize = 17;
+pub const STYLE_GROUP_INDEX_BORDER: usize = 18;
+pub const STYLE_GROUP_INDEX_SIZING: usize = 19;
+pub const STYLE_GROUP_INDEX_SURROUND: usize = 20;
+pub const STYLE_GROUP_INDEX_BOX: usize = 21;
diff --git a/Libraries/LibWeb/Rust/src/css/computed_value_views.rs b/Libraries/LibWeb/Rust/src/css/computed_value_views.rs
index 04c782babed..eba21b21182 100644
--- a/Libraries/LibWeb/Rust/src/css/computed_value_views.rs
+++ b/Libraries/LibWeb/Rust/src/css/computed_value_views.rs
@@ -13,21 +13,17 @@ use crate::css::calc;
use crate::css::computed_value_types::{
AlignmentValues, AnchorValues, BackgroundValues, BorderLayoutFacts, BorderValues, BoxValues, ComputedAspectRatio,
ComputedGap, ComputedLengthPercentageOrAuto, ComputedSize, ComputedSizeKind, ComputedStyleValueHandle,
- ContentValues, EffectsValues, FontValues, GridValues, InheritedListValues, InheritedSVGValues,
- InheritedTextLayoutFacts, InheritedTextValues, InheritedUIValues, MaskValues, MiscResetValues,
- STYLE_GROUP_INDEX_ALIGNMENT, STYLE_GROUP_INDEX_ANCHOR, STYLE_GROUP_INDEX_BACKGROUND, STYLE_GROUP_INDEX_BORDER,
- STYLE_GROUP_INDEX_BOX, STYLE_GROUP_INDEX_CONTENT, STYLE_GROUP_INDEX_EFFECTS, STYLE_GROUP_INDEX_FONT,
- STYLE_GROUP_INDEX_GRID, STYLE_GROUP_INDEX_INHERITED_BOX, STYLE_GROUP_INDEX_INHERITED_LIST,
- STYLE_GROUP_INDEX_INHERITED_SVG, STYLE_GROUP_INDEX_INHERITED_TABLE, STYLE_GROUP_INDEX_INHERITED_TEXT,
- STYLE_GROUP_INDEX_INHERITED_UI, STYLE_GROUP_INDEX_MASK, STYLE_GROUP_INDEX_MISC_RESET, STYLE_GROUP_INDEX_SIZING,
- STYLE_GROUP_INDEX_SURROUND, STYLE_GROUP_INDEX_SVG_RESET, STYLE_GROUP_INDEX_TEXT_RESET, STYLE_GROUP_INDEX_TRANSFORM,
- SVGResetValues, SizingValues, SurroundValues, TextResetValues, TransformValues,
+ ContentValues, EffectsValues, FontValues, GridValues, InheritedListTableValues, InheritedSVGValues,
+ InheritedTextLayoutFacts, InheritedTextValues, InheritedUIValues, MaskValues, MiscInteractionValues,
+ MiscLayoutValues, SVGResetValues, SizingValues, SurroundValues, TextResetValues, TransformValues,
};
-use crate::css::computed_values::{InheritedBoxValues, InheritedTableValues};
+use crate::css::computed_values::StyleBitField;
use crate::css::css_enums::{direction, writing_mode};
use crate::css::css_pixels::CssPixels;
use crate::css::display::FfiDisplay;
use crate::css::style_value::StyleValueData;
+use crate::css::style_value::{CalculatedPayload, ContentPayload, CounterDefinitionsPayload};
+use crate::css::table_group_builder::group_index;
use std::ffi::c_void;
pub(crate) fn px_calc_resolution_context(percentage_basis: CssPixels) -> calc::FfiCalcResolutionContext {
@@ -46,7 +42,7 @@ pub(crate) fn resolve_calc_to_px_without_rounding(calculated: *const c_void, per
let value = unsafe { &*calculated.cast::<StyleValueData>() };
crate::css::calc::resolve_calculated_length_without_context(value, percentage_basis.to_double()).unwrap_or_else(|| {
assert!(
- matches!(value, StyleValueData::Calculated { rust_calculation, .. } if rust_calculation.node().contains_anchor_function()),
+ matches!(value, StyleValueData::Calculated(calculated) if calculated.rust_calculation.node().contains_anchor_function()),
"computed length-percentage calc failed to resolve"
);
// NB: The abspos engine resolves the anchor functions it can itself, so these are unresolvable.
@@ -105,7 +101,10 @@ impl LengthPercentageRef<'_> {
match self.value {
StyleValueData::Length { .. } => false,
StyleValueData::Percentage { .. } => true,
- StyleValueData::Calculated { rust_calculation, .. } => rust_calculation.node().contains_percentage(),
+ StyleValueData::Calculated(calculated_payload) => {
+ let CalculatedPayload { rust_calculation, .. } = &**calculated_payload;
+ rust_calculation.node().contains_percentage()
+ }
// A calc-size() whose basis is any or a calculation acts like a calculation.
value @ StyleValueData::Function { .. } => {
crate::css::calc_size::calc_size_arguments(value).is_some_and(|(basis, calculation)| {
@@ -120,7 +119,7 @@ impl LengthPercentageRef<'_> {
}
pub(crate) fn contains_anchor_function(self) -> bool {
- matches!(self.value, StyleValueData::Calculated { rust_calculation, .. } if rust_calculation.node().contains_anchor_function())
+ matches!(self.value, StyleValueData::Calculated(calculated) if calculated.rust_calculation.node().contains_anchor_function())
}
pub(crate) fn to_px(self, reference: CssPixels) -> CssPixels {
@@ -353,7 +352,10 @@ pub(crate) fn none_computed_size() -> &'static ComputedSize {
fn counter_definitions(handle: &ComputedStyleValueHandle) -> &[crate::css::style_value::RetainedCounterDefinition] {
match handle.data() {
- Some(StyleValueData::CounterDefinitions { counter_definitions }) => counter_definitions.as_slice(),
+ Some(StyleValueData::CounterDefinitions(counter_definitions_payload)) => {
+ let CounterDefinitionsPayload { counter_definitions } = &**counter_definitions_payload;
+ counter_definitions.as_slice()
+ }
_ => &[],
}
}
@@ -442,15 +444,29 @@ impl QuoteTransfer {
}
}
-/// A borrowed view over one node's computed style group payloads: the Rust
-/// twin of the C++ ComputedValues accessor surface. Every read hands out
-/// payload references or lazy views; the payloads must stay alive and
-/// unchanged while the view or anything borrowed from it is in use.
-#[derive(Clone, Copy)]
-pub(crate) struct ComputedValuesView<'a> {
- groups: &'a [*const c_void],
+/// The groups of a computed style, at the front of what holds them: a style record, an anonymous
+/// box's style or an animation overlay. Readers reach a group only through
+/// [`ComputedValuesView`], whose `native_group` alone knows how one is found.
+#[repr(transparent)]
+pub(crate) struct StyleRecordGroups(pub(in crate::css) crate::css::computed_values::StyleGroups);
+
+impl StyleRecordGroups {
+ #[inline]
+ pub(crate) fn of(groups: &crate::css::computed_values::StyleGroups) -> &Self {
+ // SAFETY: The type is a transparent wrapper of the groups.
+ unsafe { &*std::ptr::from_ref(groups).cast::<Self>() }
+ }
}
+/// A borrowed view over one node's computed style groups: the Rust twin of the C++
+/// ComputedValues accessor surface, one thin pointer to the style. Every read hands out payload
+/// references or lazy views; the groups must stay alive and unchanged while the view or anything
+/// borrowed from it is in use.
+#[derive(Clone, Copy)]
+pub(crate) struct ComputedValuesView<'a>(&'a StyleRecordGroups);
+
+const _: () = assert!(size_of::<ComputedValuesView<'static>>() == 8);
+
macro_rules! scalar_accessors {
($($group:ident: { $($name:ident: $ty:ty => $($field:ident).+,)+ })+) => {
impl ComputedValuesView<'_> {
@@ -468,17 +484,9 @@ scalar_accessors! {
box_values: {
display: FfiDisplay => display,
display_before_box_type_transformation: FfiDisplay => display_before_box_type_transformation,
- position: u8 => position,
- float_: u8 => float_,
- clear: u8 => clear,
- box_sizing: u8 => box_sizing,
field_sizing: u8 => field_sizing,
baseline_source: u8 => baseline_source,
- overflow_x: u8 => overflow_x,
- overflow_y: u8 => overflow_y,
text_overflow: u8 => text_overflow,
- table_layout: u8 => table_layout,
- unicode_bidi: u8 => unicode_bidi,
grid_auto_flow_row: bool => grid_auto_flow_row,
grid_auto_flow_dense: bool => grid_auto_flow_dense,
continue_: u8 => continue_,
@@ -495,14 +503,13 @@ scalar_accessors! {
has_column_count: bool => column_count_has_value,
column_count: i32 => column_count,
}
- misc_reset: {
+ misc_layout: {
appearance: u8 => appearance,
native_appearance_disabled: bool => native_appearance_disabled,
column_fill: u8 => column_fill,
column_span: u8 => column_span,
column_rule_style: u8 => column_rule_style,
column_rule_width: CssPixels => column_rule_width,
- column_rule_color: u32 => column_rule_color,
break_before: u8 => break_before,
break_after: u8 => break_after,
break_inside: u8 => break_inside,
@@ -516,31 +523,13 @@ scalar_accessors! {
border_right_style: u8 => border_right.line_style,
border_bottom_style: u8 => border_bottom.line_style,
border_left_style: u8 => border_left.line_style,
- border_top_color: u32 => border_top.color,
- border_right_color: u32 => border_right.color,
- border_bottom_color: u32 => border_bottom.color,
- border_left_color: u32 => border_left.color,
}
inherited_text: {
orphans: u64 => orphans,
widows: u64 => widows,
}
- inherited_box: {
- writing_mode: u8 => writing_mode,
- text_orientation: u8 => text_orientation,
- direction: u8 => direction,
- visibility: u8 => visibility,
- }
- inherited_table: {
- border_collapse: u8 => border_collapse,
- caption_side: u8 => caption_side,
- }
inherited_text_facts: {
- text_align: u8 => text_align,
text_justify: u8 => text_justify,
- white_space_collapse: u8 => white_space_collapse,
- text_wrap_mode: u8 => text_wrap_mode,
- word_break: u8 => word_break,
line_break: u8 => line_break,
letter_spacing: CssPixels => letter_spacing,
word_spacing: CssPixels => word_spacing,
@@ -552,12 +541,7 @@ scalar_accessors! {
}
font: {
font_variant_emoji: u8 => font_variant_emoji,
- line_height: CssPixels => line_height_used,
font_size: CssPixels => font_size,
- font_ascent: f32 => font_ascent,
- font_descent: f32 => font_descent,
- font_x_height: f32 => font_x_height,
- font_zero_advance: f32 => font_zero_advance,
math_style: u8 => math_style,
math_shift: u8 => math_shift,
}
@@ -636,33 +620,84 @@ impl<'a> ComputedValuesView<'a> {
}
#[inline]
- pub(crate) fn new(groups: &'a [*const c_void]) -> Self {
- Self { groups }
+ pub(crate) fn of(groups: &'a crate::css::computed_values::StyleGroups) -> Self {
+ Self(StyleRecordGroups::of(groups))
+ }
+
+ #[inline]
+ pub(crate) fn of_record_groups(groups: &'a StyleRecordGroups) -> Self {
+ Self(groups)
+ }
+
+ /// The groups the view reads.
+ #[inline]
+ pub(crate) fn record_groups(self) -> &'a StyleRecordGroups {
+ self.0
}
#[inline]
fn native_group<T>(self, group_index: usize) -> &'a T {
- let payload = self.groups[group_index];
- debug_assert!(!payload.is_null());
+ let payload = self.0.0[group_index].as_ptr();
// SAFETY: The payload is the Rust-defined group struct itself; C++
// derives its mirror from the cbindgen twin of the same type, and the
// node's ComputedValues keep it alive while readers exist.
unsafe { &*payload.cast::<T>() }
}
+ /// The element's color, which `currentcolor` in its groups resolves to.
+ #[inline]
+ pub(crate) fn current_color(self) -> u32 {
+ self.inherited_text().color
+ }
+
+ pub(crate) fn border_top_color(self) -> u32 {
+ self.border().border_top.color.resolve(self.current_color())
+ }
+
+ pub(crate) fn border_right_color(self) -> u32 {
+ self.border().border_right.color.resolve(self.current_color())
+ }
+
+ pub(crate) fn border_bottom_color(self) -> u32 {
+ self.border().border_bottom.color.resolve(self.current_color())
+ }
+
+ pub(crate) fn border_left_color(self) -> u32 {
+ self.border().border_left.color.resolve(self.current_color())
+ }
+
+ pub(crate) fn text_decoration_color(self) -> u32 {
+ self.text_reset().text_decoration_color.resolve(self.current_color())
+ }
+
+ pub(crate) fn outline_color(self) -> u32 {
+ self.misc_layout().outline_color.resolve(self.current_color())
+ }
+
+ pub(crate) fn column_rule_color(self) -> u32 {
+ self.misc_layout().column_rule_color.resolve(self.current_color())
+ }
+
+ pub(crate) fn background_color(self) -> u32 {
+ self.background().background_color.resolve(self.current_color())
+ }
+
#[inline]
fn content(self) -> &'a ContentValues {
- self.native_group(STYLE_GROUP_INDEX_CONTENT)
+ self.native_group(group_index::CONTENT)
}
/// Whether `counter-reset` names a counter counting down from its own last item, which the
/// layout tree build cannot renumber without visiting every item again.
pub(crate) fn counter_reset_has_reversed_counter(self) -> bool {
match self.content().counter_reset.data() {
- Some(StyleValueData::CounterDefinitions { counter_definitions }) => counter_definitions
- .as_slice()
- .iter()
- .any(crate::css::style_value::RetainedCounterDefinition::is_reversed),
+ Some(StyleValueData::CounterDefinitions(counter_definitions_payload)) => {
+ let CounterDefinitionsPayload { counter_definitions } = &**counter_definitions_payload;
+ counter_definitions
+ .as_slice()
+ .iter()
+ .any(crate::css::style_value::RetainedCounterDefinition::is_reversed)
+ }
_ => false,
}
}
@@ -712,9 +747,10 @@ impl<'a> ComputedValuesView<'a> {
/// Whether `content` is a list of nothing but strings: content a box can be regenerated with
/// in place, because no counter, quote or `attr()` in it depends on where the box ends up.
pub(crate) fn content_is_strings_only(self) -> bool {
- let Some(StyleValueData::Content { content, .. }) = self.content().content.data() else {
+ let Some(StyleValueData::Content(content_payload)) = self.content().content.data() else {
return false;
};
+ let ContentPayload { content, .. } = &**content_payload;
let Some(StyleValueData::ValueList { values, .. }) = content.optional_data() else {
return false;
};
@@ -746,10 +782,13 @@ impl<'a> ComputedValuesView<'a> {
fn content_quote_keywords(self) -> impl Iterator<Item = u16> + 'a {
use crate::css::style_compute::keyword;
let values = match self.content().content.data() {
- Some(StyleValueData::Content { content, .. }) => match content.optional_data() {
- Some(StyleValueData::ValueList { values, .. }) => values.as_slice(),
- _ => &[],
- },
+ Some(StyleValueData::Content(content_payload)) => {
+ let ContentPayload { content, .. } = &**content_payload;
+ match content.optional_data() {
+ Some(StyleValueData::ValueList { values, .. }) => values.as_slice(),
+ _ => &[],
+ }
+ }
_ => &[],
};
values.iter().filter_map(|item| match item.optional_data() {
@@ -768,9 +807,10 @@ impl<'a> ComputedValuesView<'a> {
/// Whether `content` is a single image, which is what makes the element a replaced element
/// whose box renders that image instead of its children.
pub(crate) fn content_is_single_image(self) -> bool {
- let Some(StyleValueData::Content { content, .. }) = self.content().content.data() else {
+ let Some(StyleValueData::Content(content_payload)) = self.content().content.data() else {
return false;
};
+ let ContentPayload { content, .. } = &**content_payload;
let Some(StyleValueData::ValueList { values, .. }) = content.optional_data() else {
return false;
};
@@ -790,83 +830,178 @@ impl<'a> ComputedValuesView<'a> {
#[inline]
fn sizing(self) -> &'a SizingValues {
- self.native_group(STYLE_GROUP_INDEX_SIZING)
+ self.native_group(group_index::SIZING)
}
#[inline]
pub(crate) fn surround(self) -> &'a SurroundValues {
- self.native_group(STYLE_GROUP_INDEX_SURROUND)
+ self.native_group(group_index::SURROUND)
}
#[inline]
fn alignment(self) -> &'a AlignmentValues {
- self.native_group(STYLE_GROUP_INDEX_ALIGNMENT)
+ self.native_group(group_index::ALIGNMENT)
}
#[inline]
pub(crate) fn svg_reset(self) -> &'a SVGResetValues {
- self.native_group(STYLE_GROUP_INDEX_SVG_RESET)
+ self.native_group(group_index::SVG_RESET)
}
+ /// https://drafts.csswg.org/css-viewport/#effective-zoom
#[inline]
- fn inherited_box(self) -> &'a InheritedBoxValues {
- self.native_group(STYLE_GROUP_INDEX_INHERITED_BOX)
+ pub(crate) fn effective_zoom(self) -> f32 {
+ self.0.0.inherited_values().effective_zoom()
}
- /// https://drafts.csswg.org/css-viewport/#effective-zoom
#[inline]
- pub(crate) fn effective_zoom(self) -> f32 {
- self.inherited_box().effective_zoom()
+ pub(crate) fn writing_mode(self) -> u8 {
+ self.bit(StyleBitField::WritingMode)
+ }
+
+ #[inline]
+ pub(crate) fn direction(self) -> u8 {
+ self.bit(StyleBitField::Direction)
}
#[inline]
- fn inherited_table(self) -> &'a InheritedTableValues {
- self.native_group(STYLE_GROUP_INDEX_INHERITED_TABLE)
+ pub(crate) fn visibility(self) -> u8 {
+ self.bit(StyleBitField::Visibility)
+ }
+
+ #[inline]
+ fn inherited_table(self) -> &'a InheritedListTableValues {
+ self.native_group(group_index::INHERITED_LIST_TABLE)
}
#[inline]
pub(crate) fn box_values(self) -> &'a BoxValues {
- self.native_group(STYLE_GROUP_INDEX_BOX)
+ self.native_group(group_index::BOX)
}
#[inline]
pub(crate) fn grid_values(self) -> &'a GridValues {
- self.native_group(STYLE_GROUP_INDEX_GRID)
+ self.native_group(group_index::GRID)
}
#[inline]
pub(crate) fn anchor(self) -> &'a AnchorValues {
- self.native_group(STYLE_GROUP_INDEX_ANCHOR)
+ self.native_group(group_index::ANCHOR)
}
#[inline]
fn border_facts(self) -> &'a BorderLayoutFacts {
- self.native_group(STYLE_GROUP_INDEX_BORDER)
+ self.native_group(group_index::BORDER)
}
#[inline]
pub(crate) fn content_visibility(self) -> u8 {
- self.inherited_box().content_visibility
+ self.misc_layout().content_visibility
}
#[inline]
pub(crate) fn image_rendering(self) -> u8 {
- self.inherited_box().image_rendering
+ self.inherited_ui().image_rendering
}
#[inline]
pub(crate) fn empty_cells(self) -> u8 {
- self.inherited_table().empty_cells
+ self.bit(StyleBitField::EmptyCells)
+ }
+
+ #[inline]
+ pub(crate) fn text_orientation(self) -> u8 {
+ self.bit(StyleBitField::TextOrientation)
+ }
+
+ #[inline]
+ pub(crate) fn pointer_events(self) -> u8 {
+ self.bit(StyleBitField::PointerEvents)
+ }
+
+ #[inline]
+ pub(crate) fn border_collapse(self) -> u8 {
+ self.bit(StyleBitField::BorderCollapse)
+ }
+
+ #[inline]
+ pub(crate) fn caption_side(self) -> u8 {
+ self.bit(StyleBitField::CaptionSide)
+ }
+
+ #[inline]
+ pub(crate) fn text_align(self) -> u8 {
+ self.bit(StyleBitField::TextAlign)
+ }
+
+ #[inline]
+ pub(crate) fn white_space_collapse(self) -> u8 {
+ self.bit(StyleBitField::WhiteSpaceCollapse)
+ }
+
+ #[inline]
+ pub(crate) fn text_wrap_mode(self) -> u8 {
+ self.bit(StyleBitField::TextWrapMode)
+ }
+
+ #[inline]
+ pub(crate) fn word_break(self) -> u8 {
+ self.bit(StyleBitField::WordBreak)
+ }
+
+ #[inline]
+ fn bit(self, field: StyleBitField) -> u8 {
+ self.0.0.style_bits().get(field)
+ }
+
+ #[inline]
+ pub(crate) fn position(self) -> u8 {
+ self.bit(StyleBitField::Position)
+ }
+
+ #[inline]
+ pub(crate) fn float_(self) -> u8 {
+ self.bit(StyleBitField::Float)
+ }
+
+ #[inline]
+ pub(crate) fn clear(self) -> u8 {
+ self.bit(StyleBitField::Clear)
+ }
+
+ #[inline]
+ pub(crate) fn box_sizing(self) -> u8 {
+ self.bit(StyleBitField::BoxSizing)
+ }
+
+ #[inline]
+ pub(crate) fn overflow_x(self) -> u8 {
+ self.bit(StyleBitField::OverflowX)
+ }
+
+ #[inline]
+ pub(crate) fn overflow_y(self) -> u8 {
+ self.bit(StyleBitField::OverflowY)
+ }
+
+ #[inline]
+ pub(crate) fn table_layout(self) -> u8 {
+ self.bit(StyleBitField::TableLayout)
+ }
+
+ #[inline]
+ pub(crate) fn unicode_bidi(self) -> u8 {
+ self.bit(StyleBitField::UnicodeBidi)
}
#[inline]
pub(crate) fn border(self) -> &'a BorderValues {
- self.native_group(STYLE_GROUP_INDEX_BORDER)
+ self.native_group(group_index::BORDER)
}
#[inline]
- pub(crate) fn inherited_list(self) -> &'a InheritedListValues {
- self.native_group(STYLE_GROUP_INDEX_INHERITED_LIST)
+ pub(crate) fn inherited_list(self) -> &'a InheritedListTableValues {
+ self.native_group(group_index::INHERITED_LIST_TABLE)
}
/// Whether `content` computes to the keyword `none`. The property takes exactly two keywords,
@@ -898,7 +1033,7 @@ impl<'a> ComputedValuesView<'a> {
/// Whether `list-style-position` computes to `inside`, which puts the marker box inside the
/// principal block box rather than outside it.
pub(crate) fn list_style_position_is_inside(self) -> bool {
- self.inherited_list().list_style_position == crate::css::css_enums::list_style_position::INSIDE
+ self.bit(StyleBitField::ListStylePosition) == crate::css::css_enums::list_style_position::INSIDE
}
/// Whether the style names an image its box paints only once the host loads it: one in its background, mask, border
@@ -947,61 +1082,66 @@ impl<'a> ComputedValuesView<'a> {
#[inline]
pub(crate) fn inherited_ui(self) -> &'a InheritedUIValues {
- self.native_group(STYLE_GROUP_INDEX_INHERITED_UI)
+ self.native_group(group_index::INHERITED_UI)
}
#[inline]
pub(crate) fn inherited_svg(self) -> &'a InheritedSVGValues {
- self.native_group(STYLE_GROUP_INDEX_INHERITED_SVG)
+ self.native_group(group_index::INHERITED_SVG)
}
#[inline]
pub(crate) fn inherited_text(self) -> &'a InheritedTextValues {
- self.native_group(STYLE_GROUP_INDEX_INHERITED_TEXT)
+ self.native_group(group_index::INHERITED_TEXT)
}
#[inline]
pub(crate) fn font(self) -> &'a FontValues {
- self.native_group(STYLE_GROUP_INDEX_FONT)
+ self.native_group(group_index::FONT)
}
#[inline]
pub(crate) fn effects(self) -> &'a EffectsValues {
- self.native_group(STYLE_GROUP_INDEX_EFFECTS)
+ self.native_group(group_index::EFFECTS)
}
#[inline]
pub(crate) fn mask(self) -> &'a MaskValues {
- self.native_group(STYLE_GROUP_INDEX_MASK)
+ self.native_group(group_index::MASK)
}
#[inline]
pub(crate) fn text_reset(self) -> &'a TextResetValues {
- self.native_group(STYLE_GROUP_INDEX_TEXT_RESET)
+ self.native_group(group_index::TEXT_RESET)
}
#[inline]
pub(crate) fn transform(self) -> &'a TransformValues {
- self.native_group(STYLE_GROUP_INDEX_TRANSFORM)
+ self.native_group(group_index::TRANSFORM)
}
#[inline]
pub(crate) fn background(self) -> &'a BackgroundValues {
- self.native_group(STYLE_GROUP_INDEX_BACKGROUND)
+ self.native_group(group_index::BACKGROUND)
}
#[inline]
- pub(crate) fn misc_reset(self) -> &'a MiscResetValues {
- self.native_group(STYLE_GROUP_INDEX_MISC_RESET)
+ pub(crate) fn misc_layout(self) -> &'a MiscLayoutValues {
+ self.native_group(group_index::MISC_LAYOUT)
+ }
+
+ #[inline]
+ pub(crate) fn misc_interaction(self) -> &'a MiscInteractionValues {
+ self.native_group(group_index::MISC_INTERACTION)
}
#[inline]
fn inherited_text_facts(self) -> &'a InheritedTextLayoutFacts {
- self.native_group(STYLE_GROUP_INDEX_INHERITED_TEXT)
+ self.native_group(group_index::INHERITED_TEXT)
}
pub(crate) fn is_floating(self) -> bool {
- self.box_values().float_ != crate::css::css_enums::float::NONE
+ self.float_() != crate::css::css_enums::float::NONE
}
pub(crate) fn effective_flex_direction(self) -> u8 {
@@ -1016,7 +1156,7 @@ impl<'a> ComputedValuesView<'a> {
/// Whether the box is a scroll snap area.
pub(crate) fn has_scroll_snap_alignment(self) -> bool {
- let misc = self.misc_reset();
+ let misc = self.misc_interaction();
misc.scroll_snap_align_block != crate::css::css_enums::scroll_snap_align::NONE
|| misc.scroll_snap_align_inline != crate::css::css_enums::scroll_snap_align::NONE
}
@@ -1041,7 +1181,7 @@ impl<'a> ComputedValuesView<'a> {
pub(crate) fn is_absolutely_positioned(self) -> bool {
matches!(
- self.box_values().position,
+ self.position(),
crate::css::css_enums::positioning::ABSOLUTE | crate::css::css_enums::positioning::FIXED
)
}
@@ -1071,7 +1211,7 @@ impl<'a> ComputedValuesView<'a> {
let overflow_establishes_context = |overflow: u8| {
overflow != crate::css::css_enums::overflow::VISIBLE && overflow != crate::css::css_enums::overflow::CLIP
};
- if overflow_establishes_context(box_values.overflow_x) || overflow_establishes_context(box_values.overflow_y) {
+ if overflow_establishes_context(self.overflow_x()) || overflow_establishes_context(self.overflow_y()) {
return true;
}
@@ -1094,7 +1234,7 @@ impl<'a> ComputedValuesView<'a> {
// 1. The layout containment box establishes an independent formatting context.
// 4. The paint containment box establishes an independent formatting context.
let content_visibility_forces_containment =
- self.inherited_box().content_visibility == crate::css::css_enums::content_visibility::AUTO;
+ self.misc_layout().content_visibility == crate::css::css_enums::content_visibility::AUTO;
if (box_values.layout_containment || box_values.paint_containment || content_visibility_forces_containment)
&& containment_applies_to_principal_box(display)
{
@@ -1189,14 +1329,30 @@ impl<'a> ComputedValuesView<'a> {
}
pub(crate) fn first_available_font(self) -> libgfx_rust::font::FontHandle {
- let font = self.font();
- debug_assert!(
- !font.first_available_font.is_null() && !font.font_cascade_list.is_null(),
- "layout read a font group that never received a font list"
- );
- // SAFETY: The payload's cascade list handle owns the list, and the list
- // owns its first available font.
- unsafe { libgfx_rust::font::FontHandle::intern(font.first_available_font) }
+ self.font()
+ .first_available_font()
+ .expect("layout read a font group that never received a frozen font list")
+ .clone()
+ }
+
+ pub(crate) fn line_height(self) -> CssPixels {
+ self.font().line_height_used()
+ }
+
+ pub(crate) fn font_ascent(self) -> f32 {
+ self.font().first_available_font_metrics().ascent
+ }
+
+ pub(crate) fn font_descent(self) -> f32 {
+ self.font().first_available_font_metrics().descent
+ }
+
+ pub(crate) fn font_x_height(self) -> f32 {
+ self.font().first_available_font_metrics().x_height
+ }
+
+ pub(crate) fn font_zero_advance(self) -> f32 {
+ self.font().first_available_font_metrics().zero_advance
}
/// The frozen cascade a render pass reads.
@@ -1220,7 +1376,7 @@ impl<'a> ComputedValuesView<'a> {
if values.aspect_ratio.use_natural_aspect_ratio_if_available {
crate::css::css_enums::box_sizing::CONTENT_BOX
} else {
- values.box_sizing
+ self.box_sizing()
}
}
diff --git a/Libraries/LibWeb/Rust/src/css/computed_values.rs b/Libraries/LibWeb/Rust/src/css/computed_values.rs
index 246e7d7e699..87992a37378 100644
--- a/Libraries/LibWeb/Rust/src/css/computed_values.rs
+++ b/Libraries/LibWeb/Rust/src/css/computed_values.rs
@@ -18,14 +18,12 @@
//!
//! The header occupies max(size_of::<usize>(), payload alignment) bytes so the
//! payload stays properly aligned; the reference count lives in the first
-//! usize of the header. A reference count of STYLE_GROUP_STATIC_REFCOUNT marks
-//! an intentionally leaked payload (the per-group defaults) that must never be
-//! reference counted or freed.
+//! usize of the header.
+use crate::css::style_value::{ContentPayload, CounterDefinitionsPayload, FunctionPayload};
+use crate::css::style_value_arc::StyleValueArc;
use std::alloc::{Layout, alloc, dealloc};
use std::ffi::c_void;
-use std::hash::Hasher;
-use std::sync::OnceLock;
use std::sync::atomic::{AtomicUsize, Ordering};
use crate::abort_on_panic;
@@ -38,42 +36,19 @@ pub use crate::css::computed_value_types::{
ComputedOverflowClipMarginSide, ComputedPositionTryFallback, ComputedResolvedTransform, ComputedSize,
ComputedSizeKind, ComputedStyleValueHandle, ComputedSvgDash, ComputedSvgPaint, ComputedTextIndent,
ComputedTextUnderlineOffset, ComputedTextUnderlinePosition, ComputedVerticalAlign, ContentValues, EffectsValues,
- FontValues, GRID_NO_INDEX, GridValues, InheritedListValues, InheritedSVGValues, InheritedTextValues,
- InheritedUIValues, MaskValues, MiscResetValues, RetainedComputedCursorList, RetainedComputedFilterOperationList,
- RetainedComputedResolvedTransformList, RetainedComputedShadowList, RetainedComputedSvgDashList,
- RetainedGridAreaList, RetainedGridNameIndexList, RetainedGridTrackEntryList, RetainedPositionAreaList,
- RetainedPositionTryFallbackList, RetainedTextDecorationLineList, RetainedWillChangePropertyList, SVGResetValues,
- SizingValues, SurroundValues, TextResetValues, TransformValues,
+ FontValues, GRID_NO_INDEX, GridValues, InheritedBits, InheritedListTableValues, InheritedSVGValues,
+ InheritedSetValues, InheritedTextValues, InheritedUIValues, MaskValues, MiscInteractionValues, MiscLayoutValues,
+ ResetBits, RetainedComputedCursorList, RetainedComputedFilterOperationList, RetainedComputedResolvedTransformList,
+ RetainedComputedShadowList, RetainedComputedSvgDashList, RetainedGridAreaList, RetainedGridNameIndexList,
+ RetainedGridTrackEntryList, RetainedPositionAreaList, RetainedPositionTryFallbackList,
+ RetainedTextDecorationLineList, RetainedWillChangePropertyList, SVGResetValues, SizingValues, StyleBits,
+ SurroundValues, TextResetValues, TransformValues,
};
use crate::css::retained_fly_string::{RetainedUtf16FlyString, RetainedUtf16FlyStringList};
-use crate::css::style::fast_hash::{FastHasher, fast_hasher};
use crate::css::style_value::{RetainedStyleValueData, StyleValueData};
use crate::css::style_value::{retained_list_drop, retained_list_partial_eq};
use crate::css::table_group_builder::group_index;
-/// Reference count value marking an intentionally leaked payload.
-pub const STYLE_GROUP_STATIC_REFCOUNT: usize = usize::MAX;
-
-/// Layout of the inherited box style value group.
-///
-/// This is the source of truth for the group's payload layout: C++ derives its
-/// group struct from the cbindgen mirror of this type, adding its C++ identity
-/// and typed accessors on top. The fields hold C++ `enum class : u8` values
-/// generated from CSS/Enums.json, the same source as the C++ enums.
-#[repr(C)]
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub struct InheritedBoxValues {
- pub visibility: u8,
- pub direction: u8,
- pub writing_mode: u8,
- pub content_visibility: u8,
- pub image_rendering: u8,
- pub text_orientation: u8,
- /// https://drafts.csswg.org/css-viewport/#effective-zoom
- /// The bits of the effective zoom, as an `f32`.
- pub effective_zoom_bits: u32,
-}
-
impl ComputedStyleValueHandle {
pub(crate) fn empty() -> Self {
Self {
@@ -115,244 +90,6 @@ impl ComputedStyleValueHandle {
}
}
-/// Writes one value's content into `hasher` in a way consistent with its `PartialEq`: two values
-/// that compare equal always write the same bytes.
-///
-/// Consistency is what makes a content hash usable as an identity key. It holds by construction
-/// as long as every hashed field is hashed by the same notion of equality the comparison uses,
-/// and it survives omitting fields (the hash only gets coarser, and equality settles whatever
-/// shares a bucket). For the host-interned handles - fly strings, the font cascade list, the
-/// first available font - that notion *is* the address, because their `PartialEq` compares
-/// addresses. Floats hash by bit pattern with negative zero normalized; NaN never equals
-/// anything, so its hash is unconstrained.
-pub(crate) trait ContentHash {
- fn write_content_hash(&self, hasher: &mut FastHasher);
-}
-
-macro_rules! impl_content_hash_by_field {
- ($type:ty { $($field:ident),+ $(,)? }) => {
- impl ContentHash for $type {
- fn write_content_hash(&self, hasher: &mut FastHasher) {
- $(self.$field.write_content_hash(hasher);)+
- }
- }
- };
-}
-
-macro_rules! impl_content_hash_integers {
- ($($type:ty => $write:ident),+ $(,)?) => {
- $(impl ContentHash for $type {
- fn write_content_hash(&self, hasher: &mut FastHasher) {
- hasher.$write(*self);
- }
- })+
- };
-}
-
-impl_content_hash_integers!(u8 => write_u8, u16 => write_u16, u32 => write_u32, i32 => write_i32, u64 => write_u64, usize => write_usize);
-
-impl ContentHash for bool {
- fn write_content_hash(&self, hasher: &mut FastHasher) {
- hasher.write_u8(u8::from(*self));
- }
-}
-
-impl ContentHash for f32 {
- fn write_content_hash(&self, hasher: &mut FastHasher) {
- hasher.write_u32((if *self == 0.0 { 0.0_f32 } else { *self }).to_bits());
- }
-}
-
-impl ContentHash for f64 {
- fn write_content_hash(&self, hasher: &mut FastHasher) {
- hasher.write_u64((if *self == 0.0 { 0.0_f64 } else { *self }).to_bits());
- }
-}
-
-impl<T: ContentHash, const N: usize> ContentHash for [T; N] {
- fn write_content_hash(&self, hasher: &mut FastHasher) {
- for value in self {
- value.write_content_hash(hasher);
- }
- }
-}
-
-impl ContentHash for *const c_void {
- fn write_content_hash(&self, hasher: &mut FastHasher) {
- hasher.write_usize(*self as usize);
- }
-}
-
-impl ContentHash for crate::css::css_pixels::CssPixels {
- fn write_content_hash(&self, hasher: &mut FastHasher) {
- hasher.write_i32(self.raw_value());
- }
-}
-
-impl ContentHash for libgfx_rust::font::FontCascadeListHandle {
- fn write_content_hash(&self, hasher: &mut FastHasher) {
- hasher.write_usize(self.as_raw() as usize);
- }
-}
-
-impl ContentHash for libgfx_rust::font::FrozenFontListRef {
- fn write_content_hash(&self, hasher: &mut FastHasher) {
- hasher.write_usize(self.as_raw() as usize);
- }
-}
-
-impl ContentHash for RetainedUtf16FlyString {
- fn write_content_hash(&self, hasher: &mut FastHasher) {
- hasher.write_usize(self.raw());
- }
-}
-
-impl ContentHash for RetainedUtf16FlyStringList {
- fn write_content_hash(&self, hasher: &mut FastHasher) {
- let raws = self.raws();
- hasher.write_usize(raws.len());
- for &raw in raws {
- hasher.write_usize(raw);
- }
- }
-}
-
-impl ContentHash for ComputedStyleValueHandle {
- fn write_content_hash(&self, hasher: &mut FastHasher) {
- match self.data() {
- None => hasher.write_u8(0),
- Some(data) => {
- hasher.write_u8(1);
- hasher.write_u64(data.content_hash());
- }
- }
- }
-}
-
-impl ContentHash for ComputedSizeKind {
- fn write_content_hash(&self, hasher: &mut FastHasher) {
- hasher.write_u8(*self as u8);
- }
-}
-
-/// Hashes a Rust-owned retained list beside the equality `retained_list_partial_eq!` gives it:
-/// the length and then every element.
-macro_rules! impl_retained_list_content_hash {
- ($list:ty, $element:ty) => {
- impl ContentHash for $list {
- fn write_content_hash(&self, hasher: &mut FastHasher) {
- let values: &[$element] = self.as_slice();
- hasher.write_usize(values.len());
- for value in values {
- value.write_content_hash(hasher);
- }
- }
- }
- };
-}
-
-impl_content_hash_by_field!(ComputedSize { kind, value });
-impl_content_hash_by_field!(crate::css::display::FfiDisplay {
- tag,
- outside,
- inside,
- list_item,
- internal,
- box_value,
-});
-impl_content_hash_by_field!(ComputedAspectRatio {
- use_natural_aspect_ratio_if_available,
- has_preferred_ratio,
- preferred_ratio_numerator,
- preferred_ratio_denominator,
- computed_use_natural_aspect_ratio_if_available,
- has_computed_ratio,
- computed_ratio_numerator,
- computed_ratio_denominator,
-});
-impl_content_hash_by_field!(ComputedContainIntrinsicSize {
- has_auto,
- has_length,
- length_px,
-});
-impl_content_hash_by_field!(crate::css::computed_value_types::ComputedBorderSide {
- color,
- line_style,
- width,
-});
-impl_content_hash_by_field!(ComputedTextUnderlinePosition { horizontal, vertical });
-impl_content_hash_by_field!(ComputedGridTrackList {
- is_subgrid,
- preserves_line_name_sets,
- first_entry,
-});
-impl_content_hash_by_field!(ComputedGridPlacement {
- kind,
- has_line_number,
- line_number,
- has_name,
- name_index,
- implicit_start_name_index,
- implicit_end_name_index,
-});
-impl_content_hash_by_field!(ComputedGridArea {
- name_index,
- implicit_start_name_index,
- implicit_end_name_index,
- row_start,
- row_end,
- column_start,
- column_end,
-});
-impl_content_hash_by_field!(crate::css::computed_value_types::ComputedShadow {
- offset_x,
- offset_y,
- blur_radius,
- spread_distance,
- color,
- color_syntax,
- placement,
-});
-impl_content_hash_by_field!(ComputedClipEdge { is_auto, value, unit });
-impl_content_hash_by_field!(ComputedColorOrAuto {
- is_auto,
- computed_color,
- used_color,
-});
-impl_content_hash_by_field!(crate::css::computed_value_types::ComputedScrollbarColor {
- thumb_color,
- track_color,
- is_auto,
-});
-impl_content_hash_by_field!(InheritedTableValues {
- border_collapse,
- caption_side,
- empty_cells,
- border_spacing_horizontal,
- border_spacing_vertical,
-});
-impl_content_hash_by_field!(InheritedBoxValues {
- visibility,
- direction,
- writing_mode,
- content_visibility,
- image_rendering,
- text_orientation,
- effective_zoom_bits,
-});
-// The anchor-inset wrappers are pure derivatives of the anchor-inset fields, so payload equality
-// excludes them and the hash follows it field for field.
-impl_content_hash_by_field!(SurroundValues {
- inset,
- top_anchor_inset,
- right_anchor_inset,
- bottom_anchor_inset,
- left_anchor_inset,
- position_anchor,
- margin,
- padding,
-});
-
impl Clone for ComputedStyleValueHandle {
fn clone(&self) -> Self {
Self {
@@ -407,8 +144,6 @@ macro_rules! impl_computed_payload_clone_and_eq {
true $(&& self.$field == other.$field)+
}
}
-
- impl_content_hash_by_field!($type { $($field),+ });
};
// A style group whose payload holds values that layout does not read, each followed by `=> paint_only`, or values
// that layout reads only in part, each followed by `=>` and the function that compares that part.
@@ -561,8 +296,6 @@ impl PartialEq for RetainedTextDecorationLineList {
}
}
-impl_retained_list_content_hash!(RetainedTextDecorationLineList, u8);
-
impl_computed_payload_clone_and_eq!(TextResetValues {
text_decoration_lines,
text_decoration_thickness_kind,
@@ -619,7 +352,6 @@ macro_rules! impl_retained_computed_list {
retained_list_drop!($list);
retained_list_partial_eq!($list, $element);
- impl_retained_list_content_hash!($list, $element);
};
}
@@ -640,7 +372,6 @@ impl_computed_payload_clone_and_eq!(ComputedSvgPaint {
url,
has_color,
color,
- color_is_currentcolor,
});
impl_computed_payload_clone_and_eq!(ComputedSvgDash {
is_number,
@@ -659,11 +390,7 @@ impl_computed_payload_clone_and_eq!(ComputedTextUnderlineOffset {
value,
});
impl_computed_payload_clone_and_eq!(InheritedTextValues {
- text_align,
text_justify,
- white_space_collapse,
- text_wrap_mode,
- word_break,
line_break,
tab_size_is_number,
letter_spacing,
@@ -776,11 +503,12 @@ impl_computed_payload_clone_and_eq!(ContentValues {
counter_reset,
counter_set,
});
-impl_computed_payload_clone_and_eq!(InheritedListValues {
+impl_computed_payload_clone_and_eq!(InheritedListTableValues {
list_style_type,
- list_style_position,
list_style_image,
quotes,
+ border_spacing_horizontal,
+ border_spacing_vertical,
});
impl_computed_payload_clone_and_eq!(ComputedOverflowClipMarginSide {
has_visual_box,
@@ -793,10 +521,8 @@ impl_computed_payload_clone_and_eq!(ComputedOverflowClipMargin {
right,
bottom,
});
-impl_computed_payload_clone_and_eq!(MiscResetValues {
+impl_computed_payload_clone_and_eq!(MiscLayoutValues {
outline_offset_style_value,
- scroll_margin,
- scroll_padding,
overflow_clip_margin,
column_span,
break_before,
@@ -816,9 +542,17 @@ impl_computed_payload_clone_and_eq!(MiscResetValues {
column_rule_color => paint_only,
column_rule_width,
outline_offset,
- user_select,
object_position_x,
object_position_y,
+ shape_image_threshold,
+ shape_margin,
+ shape_outside,
+ content_visibility,
+});
+impl_computed_payload_clone_and_eq!(MiscInteractionValues {
+ scroll_margin,
+ scroll_padding,
+ user_select,
view_transition_name,
scroll_behavior,
scroll_snap_align_block,
@@ -830,48 +564,92 @@ impl_computed_payload_clone_and_eq!(MiscResetValues {
scrollbar_width,
overscroll_behavior_x,
overscroll_behavior_y,
- shape_image_threshold,
- shape_margin,
- shape_outside,
will_change,
implicit_will_change => implicit_will_change_layout_inputs_equal,
});
-impl_computed_payload_clone_and_eq!(FontValues {
- font_size,
- line_height_used,
- font_variant_emoji,
- font_ascent,
- font_descent,
- font_x_height,
- font_zero_advance,
- first_available_font,
- font_cascade_list,
- frozen_font_list,
- font_weight,
- font_width,
- math_shift,
- math_style,
- math_depth,
- font_family,
- font_style,
- font_optical_sizing,
- font_feature_settings,
- font_kerning,
- font_language_override,
- font_variant_alternates,
- font_variant_caps,
- font_variant_east_asian,
- font_variant_ligatures,
- font_variant_numeric,
- font_variant_position,
- font_variation_settings,
- text_rendering,
- line_height,
- math_shift_value,
- math_style_value,
- math_depth_value,
- font_size_value,
-});
+impl Clone for FontValues {
+ fn clone(&self) -> Self {
+ Self {
+ font_size: self.font_size,
+ resolved_line_height_used: self.resolved_line_height_used,
+ font_variant_emoji: self.font_variant_emoji,
+ resolved_font_ascent: self.resolved_font_ascent,
+ resolved_font_descent: self.resolved_font_descent,
+ resolved_font_x_height: self.resolved_font_x_height,
+ resolved_font_zero_advance: self.resolved_font_zero_advance,
+ resolved_first_available_font: self.resolved_first_available_font,
+ font_cascade_list: self.font_cascade_list.clone(),
+ frozen_font_list: self.frozen_font_list.clone(),
+ font_weight: self.font_weight,
+ font_width: self.font_width,
+ math_shift: self.math_shift,
+ math_style: self.math_style,
+ math_depth: self.math_depth,
+ font_family: self.font_family.clone(),
+ font_style: self.font_style.clone(),
+ font_optical_sizing: self.font_optical_sizing.clone(),
+ font_feature_settings: self.font_feature_settings.clone(),
+ font_kerning: self.font_kerning.clone(),
+ font_language_override: self.font_language_override.clone(),
+ font_variant_alternates: self.font_variant_alternates.clone(),
+ font_variant_caps: self.font_variant_caps.clone(),
+ font_variant_east_asian: self.font_variant_east_asian.clone(),
+ font_variant_ligatures: self.font_variant_ligatures.clone(),
+ font_variant_numeric: self.font_variant_numeric.clone(),
+ font_variant_position: self.font_variant_position.clone(),
+ font_variation_settings: self.font_variation_settings.clone(),
+ text_rendering: self.text_rendering.clone(),
+ line_height: self.line_height.clone(),
+ math_shift_value: self.math_shift_value.clone(),
+ math_style_value: self.math_style_value.clone(),
+ math_depth_value: self.math_depth_value.clone(),
+ font_size_value: self.font_size_value.clone(),
+ }
+ }
+}
+
+impl PartialEq for FontValues {
+ fn eq(&self, other: &Self) -> bool {
+ // A cascade the font computer published answers its first available font itself, which a load filling one of
+ // its faces in moves past what the cascade was resolved with. Only a cascade nobody published answers that.
+ let first_available_fonts_equal = (!self.frozen_font_list.is_null() && !other.frozen_font_list.is_null())
+ || (self.resolved_font_ascent == other.resolved_font_ascent
+ && self.resolved_font_descent == other.resolved_font_descent
+ && self.resolved_font_x_height == other.resolved_font_x_height
+ && self.resolved_font_zero_advance == other.resolved_font_zero_advance
+ && self.resolved_first_available_font == other.resolved_first_available_font);
+ first_available_fonts_equal
+ && self.font_size == other.font_size
+ && self.line_height_used() == other.line_height_used()
+ && self.font_variant_emoji == other.font_variant_emoji
+ && self.font_cascade_list == other.font_cascade_list
+ && self.frozen_font_list == other.frozen_font_list
+ && self.font_weight == other.font_weight
+ && self.font_width == other.font_width
+ && self.math_shift == other.math_shift
+ && self.math_style == other.math_style
+ && self.math_depth == other.math_depth
+ && self.font_family == other.font_family
+ && self.font_style == other.font_style
+ && self.font_optical_sizing == other.font_optical_sizing
+ && self.font_feature_settings == other.font_feature_settings
+ && self.font_kerning == other.font_kerning
+ && self.font_language_override == other.font_language_override
+ && self.font_variant_alternates == other.font_variant_alternates
+ && self.font_variant_caps == other.font_variant_caps
+ && self.font_variant_east_asian == other.font_variant_east_asian
+ && self.font_variant_ligatures == other.font_variant_ligatures
+ && self.font_variant_numeric == other.font_variant_numeric
+ && self.font_variant_position == other.font_variant_position
+ && self.font_variation_settings == other.font_variation_settings
+ && self.text_rendering == other.text_rendering
+ && self.line_height == other.line_height
+ && self.math_shift_value == other.math_shift_value
+ && self.math_style_value == other.math_style_value
+ && self.math_depth_value == other.math_depth_value
+ && self.font_size_value == other.font_size_value
+ }
+}
impl_computed_payload_clone_and_eq!(InheritedSVGValues {
fill,
stroke,
@@ -944,13 +722,13 @@ impl_computed_payload_clone_and_eq!(InheritedUIValues {
caret_color => paint_only,
accent_color => paint_only,
cursor,
- pointer_events,
forced_color_adjust,
interpolate_size,
scrollbar_color => paint_only,
color_scheme,
color_schemes,
color_scheme_only,
+ image_rendering,
});
impl RetainedComputedResolvedTransformList {
@@ -979,7 +757,6 @@ impl Clone for RetainedComputedResolvedTransformList {
retained_list_drop!(RetainedComputedResolvedTransformList);
retained_list_partial_eq!(RetainedComputedResolvedTransformList, ComputedResolvedTransform);
-impl_retained_list_content_hash!(RetainedComputedResolvedTransformList, ComputedResolvedTransform);
impl_computed_payload_clone_and_eq!(TransformValues {
transformations,
@@ -1012,18 +789,10 @@ impl_computed_payload_clone_and_eq!(ComputedVerticalAlign {
impl_computed_payload_clone_and_eq!(BoxValues {
display,
display_before_box_type_transformation,
- float_,
- clear,
- position,
- overflow_x,
- overflow_y,
- box_sizing,
field_sizing,
baseline_source,
resize,
text_overflow,
- unicode_bidi,
- table_layout,
grid_auto_flow_row,
grid_auto_flow_dense,
column_width,
@@ -1118,7 +887,6 @@ macro_rules! impl_retained_grid_list {
retained_list_drop!($list);
retained_list_partial_eq!($list, $element);
- impl_retained_list_content_hash!($list, $element);
};
}
@@ -1222,8 +990,7 @@ impl GridValues {
#[derive(Clone, Copy)]
pub(crate) enum StyleGroup {
Font,
- InheritedTable,
- InheritedBox,
+ InheritedListTable,
Sizing,
Alignment,
SVGReset,
@@ -1242,33 +1009,32 @@ pub(crate) enum StyleGroup {
Background,
Border,
Content,
- InheritedList,
- MiscReset,
+ MiscLayout,
+ MiscInteraction,
}
/// Every style group, in the order of the group indices both sides use (`group_index`, and
/// LIBWEB_ENUMERATE_COMPUTED_VALUE_STYLE_GROUPS in C++).
const STYLE_GROUPS: [StyleGroup; group_index::COUNT] = [
- StyleGroup::InheritedTable,
- StyleGroup::InheritedList,
+ StyleGroup::InheritedListTable,
StyleGroup::InheritedUI,
StyleGroup::InheritedSVG,
StyleGroup::InheritedText,
- StyleGroup::InheritedBox,
StyleGroup::Font,
StyleGroup::Animation,
StyleGroup::SVGReset,
StyleGroup::Grid,
StyleGroup::Anchor,
+ StyleGroup::Content,
+ StyleGroup::Alignment,
+ StyleGroup::MiscLayout,
+ StyleGroup::MiscInteraction,
StyleGroup::Effects,
StyleGroup::Mask,
StyleGroup::TextReset,
- StyleGroup::Content,
StyleGroup::Transform,
StyleGroup::Background,
StyleGroup::Border,
- StyleGroup::Alignment,
- StyleGroup::MiscReset,
StyleGroup::Sizing,
StyleGroup::Surround,
StyleGroup::Box,
@@ -1282,12 +1048,8 @@ fn style_group(group_index: usize) -> StyleGroup {
macro_rules! with_style_group_type {
($group:expr, $payload:ident => $body:expr) => {
match $group {
- StyleGroup::InheritedTable => {
- type $payload = InheritedTableValues;
- $body
- }
- StyleGroup::InheritedBox => {
- type $payload = InheritedBoxValues;
+ StyleGroup::InheritedListTable => {
+ type $payload = InheritedListTableValues;
$body
}
StyleGroup::Sizing => {
@@ -1362,12 +1124,12 @@ macro_rules! with_style_group_type {
type $payload = ContentValues;
$body
}
- StyleGroup::InheritedList => {
- type $payload = InheritedListValues;
+ StyleGroup::MiscLayout => {
+ type $payload = MiscLayoutValues;
$body
}
- StyleGroup::MiscReset => {
- type $payload = MiscResetValues;
+ StyleGroup::MiscInteraction => {
+ type $payload = MiscInteractionValues;
$body
}
StyleGroup::Font => {
@@ -1421,11 +1183,6 @@ unsafe fn payloads_equal(group: StyleGroup, a: *const c_void, b: *const c_void)
with_style_group_type!(group, Payload => unsafe { payload_ref::<Payload>(a) == payload_ref::<Payload>(b) })
}
-/// The payload must be a live payload of the group's type.
-unsafe fn payload_content_hash(group: StyleGroup, payload: *const c_void, hasher: &mut FastHasher) {
- with_style_group_type!(group, Payload => unsafe { payload_ref::<Payload>(payload) }.write_content_hash(hasher));
-}
-
/// The values of a style group's payload that layout reads. A box whose style changes only the other values keeps the
/// layout it cached, as only painting reads them.
trait StyleGroupLayoutInputs: PartialEq {
@@ -1467,10 +1224,8 @@ macro_rules! impl_style_group_read_whole_by_layout {
}
impl_style_group_read_whole_by_layout!(
- InheritedTableValues,
- InheritedListValues,
+ InheritedListTableValues,
InheritedSVGValues,
- InheritedBoxValues,
FontValues,
AnimationValues,
SVGResetValues,
@@ -1512,22 +1267,21 @@ unsafe fn payload_layout_inputs_equal(group: StyleGroup, a: *const c_void, b: *c
/// Whether two records' group payloads hold the same values that layout reads (see [`StyleGroupLayoutInputs`]), so a
/// box whose style moves from one record to the other keeps the layout it cached. The geometry of an SVG box can also
/// depend on `color`, through `currentColor`.
-///
-/// # Safety
-/// Every payload must be a live payload of the group at its index.
-pub(crate) unsafe fn style_payloads_layout_inputs_equal(
- a: &[*const c_void],
- b: &[*const c_void],
+pub(crate) fn style_payloads_layout_inputs_equal(
+ a: crate::css::computed_value_views::ComputedValuesView<'_>,
+ b: crate::css::computed_value_views::ComputedValuesView<'_>,
is_svg_box: bool,
) -> bool {
- debug_assert_eq!(a.len(), group_index::COUNT);
- debug_assert_eq!(b.len(), group_index::COUNT);
+ let (a, b) = (&a.record_groups().0, &b.record_groups().0);
+ if a.style_bits() != b.style_bits() {
+ return false;
+ }
if is_svg_box {
- // SAFETY: The caller guarantees live payloads of each group.
+ // SAFETY: Each style holds a live payload of each group.
let (first, second) = unsafe {
(
- payload_ref::<InheritedTextValues>(a[group_index::INHERITED_TEXT]),
- payload_ref::<InheritedTextValues>(b[group_index::INHERITED_TEXT]),
+ payload_ref::<InheritedTextValues>(a[group_index::INHERITED_TEXT].as_ptr()),
+ payload_ref::<InheritedTextValues>(b[group_index::INHERITED_TEXT].as_ptr()),
)
};
if first.color != second.color {
@@ -1535,33 +1289,26 @@ pub(crate) unsafe fn style_payloads_layout_inputs_equal(
}
}
(0..group_index::COUNT).all(|group| {
- // SAFETY: The caller guarantees live payloads of each group.
- a[group] == b[group] || unsafe { payload_layout_inputs_equal(style_group(group), a[group], b[group]) }
+ let (a, b) = (a[group].as_ptr(), b[group].as_ptr());
+ // SAFETY: Each style holds a live payload of each group.
+ a == b || unsafe { payload_layout_inputs_equal(style_group(group), a, b) }
})
}
-/// The style groups in `groups` whose payloads differ between two records, `[base, composed]` each: explicit
-/// inheritance reads both the base and the composition over it. `None` when a record holds fewer groups.
-///
-/// # Safety
-/// Every payload must be a live payload of the group at its index.
-pub(crate) unsafe fn changed_style_groups(
- old: [&[crate::css::host_shared::SharedPayload]; 2],
- new: [&[crate::css::host_shared::SharedPayload]; 2],
- groups: std::ops::Range<usize>,
-) -> Option<u32> {
- let mut changed = 0;
- for group in groups {
- for (before, after) in old.iter().zip(new.iter()) {
- let (&before, &after) = (before.get(group)?, after.get(group)?);
- // SAFETY: The caller guarantees live payloads of each group.
- if before != after && !unsafe { style_group_payloads_equal(group, before.as_ptr(), after.as_ptr()) } {
- changed |= 1 << group;
- break;
- }
- }
- }
- Some(changed)
+/// Whether `a` and `b` hold equal payloads in each group `compares` answers true for.
+pub(crate) fn style_groups_equal_in(
+ a: crate::css::computed_value_views::ComputedValuesView<'_>,
+ b: crate::css::computed_value_views::ComputedValuesView<'_>,
+ compares: impl Fn(usize) -> bool,
+) -> bool {
+ let (a, b) = (&a.record_groups().0, &b.record_groups().0);
+ // NB: The inherited bits and zoom are beside the inherited groups, compared with them.
+ (!compares(INHERITED_SET_GROUPS[0]) || a.inherited_values() == b.inherited_values())
+ && (0..group_index::COUNT).all(|group| {
+ let (a, b) = (a[group].as_ptr(), b[group].as_ptr());
+ // SAFETY: Each style holds a live payload of each group.
+ !compares(group) || a == b || unsafe { style_group_payloads_equal(group, a, b) }
+ })
}
/// Whether two payloads of the group at `group_index` hold the same values.
@@ -1575,22 +1322,6 @@ pub(crate) unsafe fn style_group_payloads_equal(group_index: usize, a: *const c_
unsafe { payloads_equal(style_group(group_index), a, b) }
}
-/// A content hash for one style-group payload, consistent with `style_group_payloads_equal`:
-/// two payloads that compare equal always hash equal, whoever built them and wherever they live.
-/// That is what lets a payload's identity be its content instead of its address. The group
-/// index is hashed with the content so payloads of different groups never share a bucket.
-///
-/// # Safety
-/// `payload` must be a live payload of the group at `group_index`.
-pub(crate) unsafe fn style_group_payloads_hash(group_index: usize, payload: *const c_void) -> u64 {
- assert!(!payload.is_null());
- let mut hasher = fast_hasher();
- hasher.write_usize(group_index);
- // SAFETY: The caller guarantees a live payload of the group.
- unsafe { payload_content_hash(style_group(group_index), payload, &mut hasher) };
- hasher.finish()
-}
-
/// Whether a layered image property holds an `<image>` in any layer. The value is one layer or a
/// comma-separated list of them.
fn layer_values_hold_image(handle: &ComputedStyleValueHandle) -> bool {
@@ -1612,7 +1343,7 @@ trait StyleGroupImageValues {
false
}
- /// Whether `self` and `new` hold different images, by identity.
+ /// Whether `self` and `new` hold different images, by value.
fn image_values_differ(&self, _new: &Self) -> bool {
false
}
@@ -1623,7 +1354,9 @@ fn image_handles_differ(
new: &ComputedStyleValueHandle,
holds_image: fn(&ComputedStyleValueHandle) -> bool,
) -> bool {
- old.pointer != new.pointer && (holds_image(old) || holds_image(new))
+ // NB: A computation may give an <image> a value of its own each time, which loads the same
+ // resources as an equal one.
+ old.pointer != new.pointer && (holds_image(old) || holds_image(new)) && old.data() != new.data()
}
fn handle_holds_image(handle: &ComputedStyleValueHandle) -> bool {
@@ -1660,7 +1393,7 @@ impl StyleGroupImageValues for BorderValues {
}
}
-impl StyleGroupImageValues for InheritedListValues {
+impl StyleGroupImageValues for InheritedListTableValues {
fn holds_image_values(&self) -> bool {
handle_holds_image(&self.list_style_image)
}
@@ -1688,8 +1421,6 @@ macro_rules! impl_style_group_without_image_values {
}
impl_style_group_without_image_values!(
- InheritedTableValues,
- InheritedBoxValues,
SizingValues,
AlignmentValues,
SVGResetValues,
@@ -1704,7 +1435,8 @@ impl_style_group_without_image_values!(
InheritedTextValues,
AnimationValues,
ContentValues,
- MiscResetValues,
+ MiscLayoutValues,
+ MiscInteractionValues,
FontValues,
);
@@ -1728,7 +1460,7 @@ pub(crate) unsafe fn style_group_payloads_hold_image_values(payloads: &[*const c
}
/// Whether the group payloads `old` and `new`, of two records, hold different `<image>` values in the properties whose
-/// images a layout node loads and observes, by identity. Where they hold the same ones, a box that moves from one
+/// images a layout node loads and observes, by value. Where they hold the same ones, a box that moves from one
/// record to the other keeps the images it loads and the facts it paints them with.
///
/// # Safety
@@ -1760,53 +1492,115 @@ unsafe fn payload_image_values_differ(group: StyleGroup, old: *const c_void, new
})
}
-/// The intentionally leaked per-group default payloads, for building groups without allocating when
-/// every field holds its initial value.
-struct DefaultPayloads([*const c_void; group_index::COUNT]);
-
-// SAFETY: The defaults are immortal, immutable payloads.
-unsafe impl Send for DefaultPayloads {}
-unsafe impl Sync for DefaultPayloads {}
-
-pub(crate) fn default_group_payload(group_index: usize) -> *const c_void {
- static DEFAULTS: OnceLock<DefaultPayloads> = OnceLock::new();
- DEFAULTS
- .get_or_init(|| {
- DefaultPayloads(STYLE_GROUPS.map(|group| {
- let payload = allocate_payload(group, STYLE_GROUP_STATIC_REFCOUNT);
- // SAFETY: The payload was just allocated for this group's layout.
- unsafe { default_construct(group, payload) };
- payload.cast_const()
- }))
- })
- .0[group_index]
+/// Whether `payload`, a live payload of the group at `group_index`, holds the group's default
+/// values.
+///
+/// # Safety
+/// `payload` must be a live payload of the group.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_style_group_holds_default_values(group_index: usize, payload: *const c_void) -> bool {
+ // SAFETY: The caller passes a live payload of the group.
+ unsafe { GroupPayloadRef::new(group_index, payload) }.is_some_and(GroupPayloadRef::holds_the_defaults)
}
-/// The default payload of a style group, which StyleStructRef shares instead of allocating.
+/// A new payload of the group at `group_index` holding the group's default values, with one
+/// reference for the caller.
#[unsafe(no_mangle)]
-pub extern "C" fn rust_style_group_default_payload(group_index: usize) -> *const c_void {
- default_group_payload(group_index)
+pub extern "C" fn rust_style_group_create_default(group_index: usize) -> *mut c_void {
+ let group = style_group(group_index);
+ let payload = allocate_payload(group, 1);
+ // SAFETY: The payload was just allocated with the layout of the group's type.
+ unsafe { default_construct(group, payload) };
+ payload
}
-/// Retains one reference to a payload, mirroring StyleStructRef::ref():
-/// intentionally leaked payloads are never counted.
-pub(crate) fn retain_group_payload(group_index: usize, payload: *const c_void) {
- let refcount = refcount_of(payload, payload_align(style_group(group_index)));
- if refcount.load(Ordering::Relaxed) == STYLE_GROUP_STATIC_REFCOUNT {
- return;
+/// The bytes of the allocation of `payload`, a payload of the group at `group_index`. What the
+/// payload holds beyond its own size is not counted.
+pub(crate) fn group_payload_allocation_bytes(group_index: usize, payload: *const c_void) -> usize {
+ if payload.is_null() {
+ return 0;
}
- refcount.fetch_add(1, Ordering::Relaxed);
+ allocation_layout(style_group(group_index)).size()
+}
+
+/// Retains one reference to a payload, mirroring StyleStructRef::ref().
+pub(crate) fn retain_group_payload(group_index: usize, payload: *const c_void) {
+ refcount_of(payload, payload_align(style_group(group_index))).fetch_add(1, Ordering::Relaxed);
}
fn header_size(align: usize) -> usize {
align.max(size_of::<usize>())
}
+/// Where a group's computed values start in its allocation: after its payload.
+fn values_offset(group: StyleGroup) -> usize {
+ (header_size(payload_align(group)) + payload_size(group)).next_multiple_of(align_of::<RetainedStyleValueData>())
+}
+
+/// How many computed values the allocation of `group` holds.
+fn value_count(group: StyleGroup) -> usize {
+ usize::from(GROUP_VALUE_LAYOUT.counts[group_index_of(group)])
+}
+
+fn group_index_of(group: StyleGroup) -> usize {
+ with_style_group_type!(group, Payload => <Payload as StyleGroupPayload>::GROUP_INDEX)
+}
+
fn allocation_layout(group: StyleGroup) -> Layout {
let payload_align = payload_align(group);
- let align = payload_align.max(align_of::<usize>());
- Layout::from_size_align(header_size(payload_align) + payload_size(group), align)
- .expect("style group layout overflow")
+ let align = payload_align
+ .max(align_of::<usize>())
+ .max(align_of::<RetainedStyleValueData>());
+ Layout::from_size_align(
+ values_offset(group) + value_count(group) * size_of::<RetainedStyleValueData>(),
+ align,
+ )
+ .expect("style group layout overflow")
+}
+
+/// The computed values the allocation of `payload`, a payload of `group`, holds after it.
+///
+/// # Safety
+/// `payload` must be a live payload of the group, allocated by `allocate_payload`.
+unsafe fn values_of<'a>(group: StyleGroup, payload: *const c_void) -> &'a [RetainedStyleValueData] {
+ // SAFETY: The allocation holds `value_count` initialized values at `values_offset`.
+ unsafe {
+ let start = (payload as *const u8)
+ .sub(header_size(payload_align(group)))
+ .add(values_offset(group))
+ .cast::<RetainedStyleValueData>();
+ ak::slice_from_raw_parts(start, value_count(group))
+ }
+}
+
+/// The computed values of a payload nothing else references yet, to write.
+///
+/// # Safety
+/// `payload` must be a live payload of the group, allocated by `allocate_payload`, that only the
+/// caller references.
+unsafe fn values_of_mut<'a>(group: StyleGroup, payload: *mut c_void) -> &'a mut [RetainedStyleValueData] {
+ // SAFETY: As in `values_of`, and the caller holds the only reference.
+ unsafe {
+ let start = (payload as *mut u8)
+ .sub(header_size(payload_align(group)))
+ .add(values_offset(group))
+ .cast::<RetainedStyleValueData>();
+ ak::slice_from_raw_parts_mut(start, value_count(group))
+ }
+}
+
+/// Destroys the payload and the values of an allocation nothing references, and frees it.
+///
+/// # Safety
+/// `payload` must be a payload of the group, allocated by `allocate_payload`, with no remaining
+/// references.
+unsafe fn destroy_allocation(group: StyleGroup, payload: *mut c_void) {
+ unsafe {
+ std::ptr::drop_in_place(values_of_mut(group, payload));
+ destruct(group, payload);
+ let allocation = (payload as *mut u8).sub(header_size(payload_align(group)));
+ dealloc(allocation, allocation_layout(group));
+ }
}
fn refcount_of(payload: *const c_void, align: usize) -> &'static AtomicUsize {
@@ -1818,13 +1612,6 @@ fn refcount_of(payload: *const c_void, align: usize) -> &'static AtomicUsize {
}
}
-/// One payload's live reference count, for tests that check which side of a publication ends up
-/// owning the reference it handed over.
-#[cfg(test)]
-pub(crate) fn group_payload_refcount(group_index: usize, payload: *const c_void) -> usize {
- refcount_of(payload, payload_align(style_group(group_index))).load(Ordering::Relaxed)
-}
-
fn allocate_payload(group: StyleGroup, initial_refcount: usize) -> *mut c_void {
// SAFETY: The layout is never zero-sized (the header is at least a usize).
unsafe {
@@ -1834,6 +1621,10 @@ fn allocate_payload(group: StyleGroup, initial_refcount: usize) -> *mut c_void {
}
let header = allocation as *mut AtomicUsize;
(*header).store(initial_refcount, Ordering::Relaxed);
+ let values = allocation.add(values_offset(group)).cast::<RetainedStyleValueData>();
+ for index in 0..value_count(group) {
+ values.add(index).write(RetainedStyleValueData::none());
+ }
allocation.add(header_size(payload_align(group))) as *mut c_void
}
}
@@ -1852,12 +1643,10 @@ macro_rules! impl_style_group_payload {
}
impl_style_group_payload!(
- InheritedTableValues => INHERITED_TABLE,
- InheritedListValues => INHERITED_LIST,
+ InheritedListTableValues => INHERITED_LIST_TABLE,
InheritedUIValues => INHERITED_UI,
InheritedSVGValues => INHERITED_SVG,
InheritedTextValues => INHERITED_TEXT,
- InheritedBoxValues => INHERITED_BOX,
FontValues => FONT,
AnimationValues => ANIMATION,
SVGResetValues => SVG_RESET,
@@ -1871,7 +1660,8 @@ impl_style_group_payload!(
BackgroundValues => BACKGROUND,
BorderValues => BORDER,
AlignmentValues => ALIGNMENT,
- MiscResetValues => MISC_RESET,
+ MiscLayoutValues => MISC_LAYOUT,
+ MiscInteractionValues => MISC_INTERACTION,
SizingValues => SIZING,
SurroundValues => SURROUND,
BoxValues => BOX,
@@ -1883,357 +1673,1441 @@ fn assert_group_payload_type<T: StyleGroupPayload>(group_index: usize) {
assert_eq!(group_index, T::GROUP_INDEX, "style group payload type mismatch");
}
-/// A live payload of the style group at `group_index`, borrowed for `'a`.
-#[derive(Clone, Copy)]
-pub(crate) struct GroupPayloadRef<'a> {
- group_index: usize,
- pointer: std::ptr::NonNull<c_void>,
- payload: std::marker::PhantomData<&'a c_void>,
-}
+/// The index of a computed-value style group, in the order both sides use (`group_index`,
+/// LIBWEB_ENUMERATE_COMPUTED_VALUE_STYLE_GROUPS).
+#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
+#[repr(transparent)]
+pub(crate) struct StyleGroupIndex(u8);
-impl<'a> GroupPayloadRef<'a> {
- /// The payload `pointer` names, or `None` for a null pointer.
- ///
- /// # Safety
- /// A non-null `pointer` must be a payload of the group at `group_index` that stays live and
- /// unmodified for `'a`.
- pub(crate) unsafe fn new(group_index: usize, pointer: *const c_void) -> Option<Self> {
- assert!(group_index < group_index::COUNT);
- Some(Self {
- group_index,
- pointer: std::ptr::NonNull::new(pointer.cast_mut())?,
- payload: std::marker::PhantomData,
- })
+impl StyleGroupIndex {
+ pub(crate) const fn new(index: usize) -> Self {
+ assert!(index < group_index::COUNT);
+ Self(index as u8)
}
- /// The group's immortal default payload.
- pub(crate) fn default_payload(group_index: usize) -> GroupPayloadRef<'static> {
- // SAFETY: Default payloads are leaked, so they stay live and unmodified forever.
- unsafe { GroupPayloadRef::new(group_index, default_group_payload(group_index)) }
- .expect("a style group has a default payload")
+ pub(crate) const fn usize(self) -> usize {
+ self.0 as usize
}
- pub(crate) fn as_ptr(self) -> *const c_void {
- self.pointer.as_ptr().cast_const()
+ /// Every group's index, in group order.
+ pub(crate) fn all() -> impl Iterator<Item = Self> {
+ (0..group_index::COUNT).map(Self::new)
}
+}
- /// The payload as its group's type, which must be `T`.
- fn values<T: StyleGroupPayload>(self) -> &'a T {
- assert_group_payload_type::<T>(self.group_index);
- // SAFETY: The payload is live for 'a and its group's type is `T`.
- unsafe { payload_ref::<T>(self.as_ptr()) }
- }
+/// A pointer to a live style group, which a [`StyleGroups`] holds a reference to.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+#[repr(transparent)]
+pub(crate) struct GroupPointer(std::ptr::NonNull<c_void>);
- /// Whether `other`, a payload of the same group, holds the same values.
- fn equals(self, other: GroupPayloadRef<'_>) -> bool {
- assert_eq!(self.group_index, other.group_index);
- // SAFETY: Both payloads are live payloads of the group.
- unsafe { payloads_equal(style_group(self.group_index), self.as_ptr(), other.as_ptr()) }
+impl GroupPointer {
+ pub(crate) fn as_ptr(self) -> *const c_void {
+ self.0.as_ptr().cast_const()
}
- /// The payload, with one more reference for the caller.
- fn retained(self) -> *const c_void {
- retain_group_payload(self.group_index, self.as_ptr());
- self.as_ptr()
+ /// The group, as its payload type `T`, borrowed.
+ pub(crate) fn cast<T>(self) -> crate::css::host_shared::HostShared<T> {
+ crate::css::host_shared::HostShared::new(self.as_ptr().cast())
}
}
-/// A freshly allocated payload of one group, which holds the payload's one reference and frees it unless published.
-struct ScratchPayload {
- group_index: usize,
- pointer: *mut c_void,
+/// Where a style keeps one of its groups: in its root, or in one of the group sets it may share
+/// with other styles.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub(crate) enum GroupPlace {
+ Root(u8),
+ Inherited(u8),
+ Rare(u8),
+ Visual(u8),
}
-impl ScratchPayload {
- fn new_default(group_index: usize) -> Self {
- let group = style_group(group_index);
- let pointer = allocate_payload(group, 1);
- // SAFETY: The payload was just allocated with the layout of the group's type.
- unsafe { default_construct(group, pointer) };
- Self { group_index, pointer }
+/// The groups a style keeps in its root, which elements styled apart differ in most often.
+pub(crate) const ROOT_GROUPS: [usize; 3] = [group_index::SIZING, group_index::SURROUND, group_index::BOX];
+
+/// The groups of the properties that inherit, which a child writing none of them holds as its
+/// parent's set.
+pub(crate) const INHERITED_SET_GROUPS: [usize; 5] = [
+ group_index::INHERITED_LIST_TABLE,
+ group_index::INHERITED_UI,
+ group_index::INHERITED_SVG,
+ group_index::INHERITED_TEXT,
+ group_index::FONT,
+];
+
+/// The groups of the properties few elements write.
+pub(crate) const RARE_SET_GROUPS: [usize; 8] = [
+ group_index::ANIMATION,
+ group_index::SVG_RESET,
+ group_index::GRID,
+ group_index::ANCHOR,
+ group_index::CONTENT,
+ group_index::ALIGNMENT,
+ group_index::MISC_LAYOUT,
+ group_index::MISC_INTERACTION,
+];
+
+/// The groups of the properties that paint a box.
+pub(crate) const VISUAL_SET_GROUPS: [usize; 6] = [
+ group_index::EFFECTS,
+ group_index::MASK,
+ group_index::TEXT_RESET,
+ group_index::TRANSFORM,
+ group_index::BACKGROUND,
+ group_index::BORDER,
+];
+
+// NB: Each place is a run of group indices, so that the host finds a group's place from its index
+// alone: the inherited set, then the rare set, the visual set and the root.
+const _: () = {
+ let runs: [&[usize]; 4] = [
+ &INHERITED_SET_GROUPS,
+ &RARE_SET_GROUPS,
+ &VISUAL_SET_GROUPS,
+ &ROOT_GROUPS,
+ ];
+ let mut next = 0;
+ let mut run = 0;
+ while run < runs.len() {
+ let mut slot = 0;
+ while slot < runs[run].len() {
+ assert!(runs[run][slot] == next);
+ next += 1;
+ slot += 1;
+ }
+ run += 1;
}
+ assert!(next == group_index::COUNT);
+ assert!(crate::css::computed_value_types::STYLE_GROUP_RARE_SET_START == RARE_SET_GROUPS[0]);
+ assert!(crate::css::computed_value_types::STYLE_GROUP_VISUAL_SET_START == VISUAL_SET_GROUPS[0]);
+ assert!(crate::css::computed_value_types::STYLE_GROUP_ROOT_START == ROOT_GROUPS[0]);
+};
- fn apply_pokes(&mut self, pokes: &[GroupFieldPoke<'_>]) {
- // SAFETY: The pokes come from the group's registered descriptors, whose offsets name fields of the right
- // type in the group's payload, and nothing else references the scratch payload yet.
- unsafe { apply_group_field_pokes(self.pointer, pokes) };
+/// The place of each group, by group index.
+pub(crate) const GROUP_PLACES: [GroupPlace; group_index::COUNT] = {
+ let mut places = [GroupPlace::Root(u8::MAX); group_index::COUNT];
+ let mut slot = 0;
+ while slot < ROOT_GROUPS.len() {
+ places[ROOT_GROUPS[slot]] = GroupPlace::Root(slot as u8);
+ slot += 1;
+ }
+ let mut slot = 0;
+ while slot < INHERITED_SET_GROUPS.len() {
+ places[INHERITED_SET_GROUPS[slot]] = GroupPlace::Inherited(slot as u8);
+ slot += 1;
+ }
+ let mut slot = 0;
+ while slot < RARE_SET_GROUPS.len() {
+ places[RARE_SET_GROUPS[slot]] = GroupPlace::Rare(slot as u8);
+ slot += 1;
+ }
+ let mut slot = 0;
+ while slot < VISUAL_SET_GROUPS.len() {
+ places[VISUAL_SET_GROUPS[slot]] = GroupPlace::Visual(slot as u8);
+ slot += 1;
+ }
+ let mut group = 0;
+ while group < group_index::COUNT {
+ assert!(
+ !matches!(places[group], GroupPlace::Root(u8::MAX)),
+ "every group has a place"
+ );
+ group += 1;
}
+ places
+};
- /// The payload as its group's type, which must be `T`.
- fn values_mut<T: StyleGroupPayload>(&mut self) -> &mut T {
- assert_group_payload_type::<T>(self.group_index);
- // SAFETY: The scratch payload is a live payload of type `T` that only this guard references.
- unsafe { &mut *self.pointer.cast::<T>() }
- }
+macro_rules! group_sets {
+ ($($(#[$meta:meta])* $set:ident => $groups:ident, $(#[$beside_meta:meta])* beside: $beside:ty,)+) => {$(
+ $(#[$meta])*
+ #[repr(C)]
+ pub(crate) struct $set {
+ // NB: First, so that the host reads the set's address as the address of its groups.
+ groups: [GroupPointer; $groups.len()],
+ $(#[$beside_meta])*
+ beside: $beside,
+ }
- fn as_ref(&self) -> GroupPayloadRef<'_> {
- // SAFETY: The scratch payload is live while the guard is, and nothing modifies it while borrowed.
- unsafe { GroupPayloadRef::new(self.group_index, self.pointer) }.expect("allocation never returns null")
- }
+ impl $set {
+ /// Takes over one reference to each group of the set, out of a style's groups in group order.
+ fn adopt(pointers: &[GroupPointer; group_index::COUNT]) -> Self {
+ Self {
+ groups: std::array::from_fn(|slot| pointers[$groups[slot]]),
+ beside: Default::default(),
+ }
+ }
- /// Hands the payload and its one reference to the caller.
- fn publish(self) -> *const c_void {
- let pointer = self.pointer.cast_const();
- std::mem::forget(self);
- pointer
- }
+ /// Whether `pointers` holds this set's groups.
+ fn holds(&self, pointers: &[GroupPointer; group_index::COUNT]) -> bool {
+ self.groups.iter().zip($groups).all(|(pointer, group)| *pointer == pointers[group])
+ }
+ }
+
+ impl Clone for $set {
+ fn clone(&self) -> Self {
+ for (pointer, group) in self.groups.iter().zip($groups) {
+ retain_group_payload(group, pointer.as_ptr());
+ }
+ Self {
+ groups: self.groups,
+ beside: self.beside.clone(),
+ }
+ }
+ }
+
+ impl Drop for $set {
+ fn drop(&mut self) {
+ for (pointer, group) in self.groups.iter().zip($groups) {
+ release_group_payload(group, pointer.as_ptr());
+ }
+ }
+ }
+ )+};
}
-impl Drop for ScratchPayload {
- fn drop(&mut self) {
- // SAFETY: The scratch payload was never published, so this guard holds its only reference.
- unsafe { free_scratch_payload(style_group(self.group_index), self.pointer) };
- }
+/// What a style's inherited set holds beside its groups.
+#[derive(Clone)]
+#[repr(C)]
+pub(crate) struct InheritedSetBeside {
+ /// NB: First, so that the host reads them right after the set's groups.
+ values: InheritedSetValues,
+ /// The custom properties the element holds, which its children holding the same share.
+ custom_properties: Option<std::sync::Arc<crate::css::custom_properties::CustomPropertyStore>>,
}
-/// The payload a build of the group at `group_index` can share instead of publishing its own: the parent's payload,
-/// retained for the caller, or the group's default payload, whichever `matches` first.
-fn share_matching_group_payload(
- group_index: usize,
- parent: Option<GroupPayloadRef<'_>>,
- matches: impl Fn(GroupPayloadRef<'_>) -> bool,
-) -> Option<*const c_void> {
- if let Some(parent) = parent {
- assert_eq!(parent.group_index, group_index);
- if matches(parent) {
- return Some(parent.retained());
+impl Default for InheritedSetBeside {
+ fn default() -> Self {
+ Self {
+ values: InheritedSetValues::INITIAL,
+ custom_properties: None,
}
}
- let default_payload = GroupPayloadRef::default_payload(group_index);
- matches(default_payload).then(|| default_payload.as_ptr())
}
-/// The payload `built` can share instead of being published.
-fn share_equal_group_payload(built: GroupPayloadRef<'_>, parent: Option<GroupPayloadRef<'_>>) -> Option<*const c_void> {
- share_matching_group_payload(built.group_index, parent, |candidate| built.equals(candidate))
+group_sets! {
+ /// The inherited groups of a style, which its children writing none of them hold too.
+ InheritedSet => INHERITED_SET_GROUPS,
+ /// The inherited longhands held as bits, the effective zoom and the custom properties, which
+ /// the children of an element holding the same share.
+ beside: InheritedSetBeside,
+ /// The groups of a style few elements write.
+ RareSet => RARE_SET_GROUPS,
+ /// What the computation of a record holding the set recorded beside its values, and the
+ /// element's own custom declarations.
+ beside: crate::css::style::pipeline::RareSetFacts,
+ /// The groups of a style painting a box, and its other reset groups.
+ VisualSet => VISUAL_SET_GROUPS,
+ beside: (),
}
-/// The payload a built group value can share instead of allocating its own.
-fn share_group_payload<T: StyleGroupPayload + PartialEq>(
- group_index: usize,
- built: &T,
- parent: Option<GroupPayloadRef<'_>>,
-) -> Option<*const c_void> {
- assert_group_payload_type::<T>(group_index);
- share_matching_group_payload(group_index, parent, |candidate| built == candidate.values::<T>())
-}
+/// One counted reference to a group set, which styles holding the same groups there share.
+#[repr(transparent)]
+pub(crate) struct SharedGroupSet<T>(std::ptr::NonNull<T>);
-/// The payload a built group value shares, or else a fresh payload holding it. Either carries one reference for the
-/// caller.
-fn share_or_publish_group_payload<T: StyleGroupPayload + PartialEq>(
- group_index: usize,
- built: T,
- parent: Option<GroupPayloadRef<'_>>,
-) -> *const c_void {
- share_group_payload(group_index, &built, parent).unwrap_or_else(|| publish_group_payload(group_index, built))
-}
+impl<T> SharedGroupSet<T> {
+ fn new(set: T) -> Self {
+ // SAFETY: `Arc::into_raw` never answers null.
+ Self(unsafe { std::ptr::NonNull::new_unchecked(std::sync::Arc::into_raw(std::sync::Arc::new(set)).cast_mut()) })
+ }
-/// Moves a built group value into a fresh payload that carries one reference for the caller.
-fn publish_group_payload<T: StyleGroupPayload>(group_index: usize, built: T) -> *const c_void {
- assert_group_payload_type::<T>(group_index);
- let payload = allocate_payload(style_group(group_index), 1);
- // SAFETY: The payload was just allocated with the layout of the group's type, which is `T`.
- unsafe { payload.cast::<T>().write(built) };
- payload.cast_const()
-}
+ fn get(&self) -> &T {
+ // SAFETY: The reference keeps the set alive.
+ unsafe { self.0.as_ref() }
+ }
-/// Allocates a new payload for `group_index` with a reference count of one,
-/// copy-constructed from `source`.
-///
-/// # Safety
-/// `source` must be a valid payload of the same group type.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_style_group_clone(group_index: usize, source: *const c_void) -> *mut c_void {
- unsafe { clone_group_payload(group_index, source) }
+ fn ptr_eq(&self, other: &Self) -> bool {
+ self.0 == other.0
+ }
+
+ /// The set, to write, copied first where another style shares it.
+ fn make_mut(&mut self) -> &mut T
+ where
+ T: Clone,
+ {
+ // SAFETY: The pointer came from `Arc::into_raw`, and this handle owns one reference.
+ let mut arc = unsafe { std::sync::Arc::from_raw(self.0.as_ptr().cast_const()) };
+ std::sync::Arc::make_mut(&mut arc);
+ // SAFETY: As above.
+ self.0 = unsafe { std::ptr::NonNull::new_unchecked(std::sync::Arc::into_raw(arc).cast_mut()) };
+ // SAFETY: `make_mut` left this handle the set's only reference.
+ unsafe { self.0.as_mut() }
+ }
}
-/// The source must be a live payload of the registered group type.
-pub(crate) unsafe fn clone_group_payload(group_index: usize, source: *const c_void) -> *mut c_void {
- let group = style_group(group_index);
- let payload = allocate_payload(group, 1);
- unsafe { copy_construct(group, payload, source) };
- payload
+impl<T> Clone for SharedGroupSet<T> {
+ fn clone(&self) -> Self {
+ // SAFETY: The pointer came from `Arc::into_raw`, and this handle keeps it alive.
+ unsafe { std::sync::Arc::increment_strong_count(self.0.as_ptr().cast_const()) };
+ Self(self.0)
+ }
}
-/// Destroys and deallocates a payload whose reference count has reached zero.
-///
-/// # Safety
-/// `payload` must be a payload of the given group type with no remaining
-/// references, and must not be a static default payload.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_style_group_free(group_index: usize, payload: *mut c_void) {
- unsafe {
- let group = style_group(group_index);
- debug_assert!(refcount_of(payload, payload_align(group)).load(Ordering::Relaxed) == 0);
- destruct(group, payload);
- let allocation = (payload as *mut u8).sub(header_size(payload_align(group)));
- dealloc(allocation, allocation_layout(group));
- };
+impl<T> Drop for SharedGroupSet<T> {
+ fn drop(&mut self) {
+ // SAFETY: The pointer came from `Arc::into_raw`, and this handle owns one reference.
+ unsafe { std::sync::Arc::decrement_strong_count(self.0.as_ptr().cast_const()) };
+ }
}
-pub(crate) fn release_group_payload(group_index: usize, payload: *const c_void) {
- let group = style_group(group_index);
- let refcount = refcount_of(payload, payload_align(group));
- if refcount.load(Ordering::Relaxed) == STYLE_GROUP_STATIC_REFCOUNT {
- return;
+/// One counted reference to the rare set of a style, which the next style recording the same rare
+/// facts and holding the same rare groups shares.
+#[derive(Clone)]
+#[repr(transparent)]
+pub(crate) struct RareSetRef(SharedGroupSet<RareSet>);
+
+impl RareSetRef {
+ /// The rare facts the set holds beside its groups.
+ pub(crate) fn facts(&self) -> &std::sync::Arc<crate::css::style::pipeline::RareStyleFacts> {
+ self.0
+ .get()
+ .beside
+ .facts
+ .as_ref()
+ .expect("a kept rare set holds its facts")
}
- if refcount.fetch_sub(1, Ordering::AcqRel) == 1 {
- // SAFETY: The count reached zero, so this reference was the last one.
- unsafe {
- destruct(group, payload.cast_mut());
- let allocation = (payload as *mut u8).sub(header_size(payload_align(group)));
- dealloc(allocation, allocation_layout(group));
- }
+
+ /// The custom declarations the set holds beside its groups.
+ pub(crate) fn custom_declarations(&self) -> Option<&crate::css::style::pipeline::CustomDeclarations> {
+ self.0.get().beside.custom_declarations.as_ref()
}
-}
-/// Clamps a border box size by the min and max sizes of a sizing group that resolve against the given basis, as
-/// resizing an element by its resizer does.
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_sizing_values_clamp_size(
- values: &SizingValues,
- basis_width: f64,
- basis_height: f64,
- width: &mut f64,
- height: &mut f64,
-) {
- use crate::css::css_pixels::CssPixels;
- let clamp = |size: f64, basis: f64, minimum: &ComputedSize, maximum: &ComputedSize| {
- let basis = CssPixels::nearest_value_for(basis);
- let mut size = size;
- if minimum.is_length_percentage() {
- size = size.max(minimum.to_px(basis).to_double());
- }
- if maximum.is_length_percentage() {
- size = size.min(maximum.to_px(basis).to_double());
- }
- size
- };
- *width = clamp(*width, basis_width, &values.min_width, &values.max_width);
- *height = clamp(*height, basis_height, &values.min_height, &values.max_height);
+ pub(crate) fn ptr_eq(&self, other: &Self) -> bool {
+ self.0.ptr_eq(&other.0)
+ }
}
-/// The pixels of a computed size given as an absolute length, written to `pixels`. Returns false for any other size.
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_computed_size_absolute_length_px(size: &ComputedSize, pixels: &mut f64) -> bool {
- let Some(StyleValueData::Length { value, unit }) = size.value.style_value() else {
- return false;
- };
- if size.kind != ComputedSizeKind::Length {
- return false;
+/// One counted reference to each group of an element's style: the groups elements styled apart
+/// differ in most often in the root, and the others in sets the style shares with the styles that
+/// hold the same groups there, such as its parent's inherited groups.
+#[repr(C)]
+pub(crate) struct StyleGroups {
+ root: [GroupPointer; ROOT_GROUPS.len()],
+ inherited: SharedGroupSet<InheritedSet>,
+ rare: SharedGroupSet<RareSet>,
+ visual: SharedGroupSet<VisualSet>,
+ /// The properties that do not inherit held as bits, after the set pointers.
+ reset: ResetBits,
+ /// The element's color, resolved, which `currentcolor` in its groups resolves to.
+ current_color: u32,
+}
+
+// NB: The host reads groups through this layout (`CSS::style_record_group`): the root's groups,
+// then a pointer to the first group of each set.
+const _: () = assert!(size_of::<StyleGroups>() == 56);
+const _: () = assert!(std::mem::offset_of!(StyleGroups, reset) == 48);
+const _: () = assert!(std::mem::offset_of!(StyleGroups, current_color) == 52);
+const _: () = assert!(std::mem::offset_of!(StyleGroups, root) == 0);
+const _: () = assert!(std::mem::offset_of!(StyleGroups, inherited) == 24);
+const _: () = assert!(std::mem::offset_of!(StyleGroups, rare) == 32);
+const _: () = assert!(std::mem::offset_of!(StyleGroups, visual) == 40);
+
+// SAFETY: A group is immutable once published, and its reference count is atomic, so the
+// references may move to and be read from any thread, as `HeldGroup`'s groups are. A set
+// is immutable while shared and its count is an `Arc`'s.
+unsafe impl Send for StyleGroups {}
+unsafe impl Sync for StyleGroups {}
+
+/// The groups of a style's group pointers that hold no reference of their own: each one of a set
+/// another style holds, which the style is to share, as an element sharing its parent's inherited
+/// set takes those groups without counting a reference to each.
+#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
+pub(crate) struct BorrowedGroups(u32);
+
+impl BorrowedGroups {
+ pub(crate) const NONE: Self = Self(0);
+
+ /// Every group of a set that `takes_as_it_is` answers true for.
+ pub(crate) fn of_groups_where(takes_as_it_is: impl Fn(usize) -> bool) -> Self {
+ let set_groups = INHERITED_SET_GROUPS
+ .iter()
+ .chain(&RARE_SET_GROUPS)
+ .chain(&VISUAL_SET_GROUPS);
+ Self(
+ set_groups
+ .filter(|&&group| takes_as_it_is(group))
+ .fold(0_u32, |mask, group| mask | 1 << group),
+ )
}
- let ratio = crate::css::style_compute::LENGTH_UNIT_CANONICAL_PX_RATIOS[*unit as usize];
- if !ratio.is_finite() {
- return false;
+
+ pub(crate) fn contains(self, group: usize) -> bool {
+ self.0 & (1 << group) != 0
}
- *pixels = value * ratio;
- true
}
-/// One field of a style group the generic builder can populate or check: a pokeable simple field
-/// at `offset` in the group's payload, or a constraint requiring the value to be one that leaves
-/// the payload's initial value standing.
-#[derive(Clone, Copy)]
-pub(crate) struct GroupFieldDescriptor {
- pub(crate) property_id: u16,
- pub(crate) offset: usize,
- pub(crate) kind: GroupFieldKind,
+/// The groups one computation of a style made, holding a reference to each but the borrowed ones
+/// until a style adopts them: a computation whose result is thrown away, as one computed again,
+/// releases them as it drops.
+pub(crate) struct ComputedGroups {
+ pointers: [*const c_void; group_index::COUNT],
+ bits: StyleBits,
+ current_color: u32,
+ borrowed: BorrowedGroups,
}
-#[derive(Clone, Copy)]
-pub(crate) enum GroupFieldKind {
- /// An enum stored as u8: the keyword's code through the converter. A keyword it rejects stays
- /// at the payload default for the Rust group builder to complete.
- EnumKeyword(fn(u16) -> Option<u8>),
- /// A number stored as f64.
- F64,
- /// A pixel length stored as raw CSSPixels (i32).
- CssPixels,
- /// A pixel length stored as raw CSSPixels, clamped at zero.
- CssPixelsNonNegative,
- /// An integer stored as u64.
- U64,
- /// A color stored as the C++ Color's raw 32-bit value, resolved by the gather loop, which owns
- /// the color resolution context.
- Color,
- /// A color like `Color`, except that this keyword leaves the initial value standing, for fields
- /// like outline-color whose auto keyword is not a resolvable color.
- ColorOrKeyword(u16),
- /// A number resolved by the gather loop, for values whose normalization has not moved into the
- /// core, like opacity: stored as f32, as f64, or as one byte for derived enum fields like the
- /// used color-scheme.
- ResolvedF32,
- ResolvedF64,
- ResolvedU8,
- /// The value's data stored into a single-pointer handle slot, retaining one reference; the
- /// slot's initial value must be null.
- RetainedData,
- /// A bool stored as one byte: whether the value is this keyword.
- KeywordEqualsBool(u16),
- /// Constraints, which write nothing: the value must be this keyword, a zero pixel length, or
- /// the property's initial value. The last compares data pointers, which holds exactly for
- /// untouched properties since the driver selects the initial table's entries directly.
- RequireKeyword(u16),
- RequireZeroPx,
- RequireInitialValue,
-}
+impl ComputedGroups {
+ /// Takes over one reference to each of `pointers` but the `borrowed` ones, with `inherited`
+ /// beside the inherited groups.
+ ///
+ /// # Safety
+ /// Each of `pointers` must be a live group of its index, with a reference the caller hands over
+ /// unless `borrowed` names it, and a borrowed one must stay live while these groups do.
+ pub(crate) unsafe fn new(
+ pointers: [*const c_void; group_index::COUNT],
+ bits: StyleBits,
+ current_color: u32,
+ borrowed: BorrowedGroups,
+ ) -> Self {
+ Self {
+ pointers,
+ bits,
+ current_color,
+ borrowed,
+ }
+ }
-/// The appearance keywords without the compatibility ones, which normalize to auto for the
-/// appearance field but stay raw for computed_appearance: the misc-reset group builder completes
-/// both fields for them.
-fn appearance_without_compat(keyword: u16) -> Option<u8> {
- use crate::css::css_enums::appearance::{AUTO, MENULIST_BUTTON, NONE, TEXTFIELD};
- crate::css::css_enums::keyword_to_appearance(keyword)
- .filter(|appearance| matches!(*appearance, AUTO | MENULIST_BUTTON | NONE | TEXTFIELD))
-}
+ /// What the groups hold as bits beside them.
+ pub(crate) fn style_bits(&self) -> StyleBits {
+ self.bits
+ }
-/// The fields of each group the generic builder decodes, in the order the gather loop reads their
-/// values. Groups that build through bespoke calls have none.
-pub(crate) fn group_field_descriptors(group: usize) -> &'static [GroupFieldDescriptor] {
- use crate::css::css_enums as enums;
- use crate::css::css_enums::keyword as k;
- use GroupFieldKind::*;
+ /// The groups, one live group of each index.
+ pub(crate) fn pointers(&self) -> &[*const c_void; group_index::COUNT] {
+ &self.pointers
+ }
- // `PROPERTY @ field => kind` describes a field of the group's payload, `PROPERTY => kind` a
- // constraint.
- macro_rules! fields {
- ($group:ty: $($property:ident $(@ $($field:ident).+)? => $kind:expr),* $(,)?) => {
- const {
- &[$(GroupFieldDescriptor {
- property_id: crate::css::property_metadata::property_id::$property,
- offset: 0 $(+ std::mem::offset_of!($group, $($field).+))?,
- kind: $kind,
- }),*]
+ /// The computed value of `property` these groups hold.
+ pub(crate) fn value(&self, property: u16) -> &RetainedStyleValueData {
+ // SAFETY: These groups hold a reference to each of their groups, or borrow it from a set
+ // that outlives them.
+ unsafe { value_in_groups_of(|group| self.pointers[group], &self.bits, property) }
+ }
+
+ /// The groups as a style's, sharing the sets of `shares` that hold the same groups.
+ pub(crate) fn adopt_sharing(self, shares: &[Option<&StyleGroups>]) -> StyleGroups {
+ let this = std::mem::ManuallyDrop::new(self);
+ // SAFETY: The groups hold the references `new` took over, which the style takes.
+ unsafe { StyleGroups::adopt_sharing(this.pointers, this.bits, this.borrowed, shares) }
+ .with_current_color(this.current_color)
+ }
+}
+
+impl Drop for ComputedGroups {
+ fn drop(&mut self) {
+ for (group, &pointer) in self.pointers.iter().enumerate() {
+ if !self.borrowed.contains(group) {
+ release_group_payload(group, pointer);
}
- };
+ }
}
+}
- match group {
- group_index::TEXT_RESET => fields! { TextResetValues:
- TEXT_DECORATION_LINE => RequireKeyword(k::NONE),
- TEXT_DECORATION_THICKNESS => RequireKeyword(k::AUTO),
- TEXT_DECORATION_STYLE @ text_decoration_style => EnumKeyword(enums::keyword_to_text_decoration_style),
- TEXT_DECORATION_COLOR @ text_decoration_color => Color,
- WHITE_SPACE_TRIM => RequireKeyword(k::NONE),
- },
- group_index::EFFECTS => fields! { EffectsValues:
- OPACITY @ opacity => ResolvedF32,
- FILTER => RequireKeyword(k::NONE),
- BACKDROP_FILTER => RequireKeyword(k::NONE),
- MIX_BLEND_MODE @ mix_blend_mode => EnumKeyword(enums::keyword_to_mix_blend_mode),
+impl StyleGroups {
+ /// Takes over one reference to each of `pointers` but the `borrowed` ones, with `bits` beside
+ /// them, sharing the sets of `shares` that hold the same.
+ ///
+ /// # Safety
+ /// Each of `pointers` must be a live group of its index, with a reference the caller hands over
+ /// unless `borrowed` names it, and a borrowed one must stay live for this call.
+ pub(crate) unsafe fn adopt_sharing(
+ pointers: [*const c_void; group_index::COUNT],
+ bits: StyleBits,
+ borrowed: BorrowedGroups,
+ shares: &[Option<&StyleGroups>],
+ ) -> Self {
+ assert!(
+ ROOT_GROUPS.iter().all(|&group| !borrowed.contains(group)),
+ "a root group is never borrowed"
+ );
+ let pointers = pointers.map(|pointer| {
+ GroupPointer(std::ptr::NonNull::new(pointer.cast_mut()).expect("a style group is never null"))
+ });
+ fn set<T: Clone>(
+ pointers: &[GroupPointer; group_index::COUNT],
+ borrowed: BorrowedGroups,
+ shares: &[Option<&StyleGroups>],
+ of: impl Fn(&StyleGroups) -> &SharedGroupSet<T>,
+ holds: impl Fn(&T, &[GroupPointer; group_index::COUNT]) -> bool,
+ adopt: impl Fn(&[GroupPointer; group_index::COUNT]) -> T,
+ groups: &[usize],
+ ) -> SharedGroupSet<T> {
+ match shares
+ .iter()
+ .flatten()
+ .map(|share| of(share))
+ .find(|set| holds(set.get(), pointers))
+ {
+ Some(shared) => {
+ // The shared set holds references of its own.
+ for &group in groups.iter().filter(|&&group| !borrowed.contains(group)) {
+ release_group_payload(group, pointers[group].as_ptr());
+ }
+ shared.clone()
+ }
+ None => {
+ // A set of its own counts a reference to each of its groups.
+ for &group in groups.iter().filter(|&&group| borrowed.contains(group)) {
+ retain_group_payload(group, pointers[group].as_ptr());
+ }
+ SharedGroupSet::new(adopt(pointers))
+ }
+ }
+ }
+ Self {
+ root: std::array::from_fn(|slot| pointers[ROOT_GROUPS[slot]]),
+ inherited: set(
+ &pointers,
+ borrowed,
+ shares,
+ |groups| &groups.inherited,
+ |set, pointers| set.holds(pointers) && set.beside.values == bits.inherited,
+ |pointers| {
+ let mut set = InheritedSet::adopt(pointers);
+ set.beside.values = bits.inherited;
+ set
+ },
+ &INHERITED_SET_GROUPS,
+ ),
+ rare: set(
+ &pointers,
+ borrowed,
+ shares,
+ |groups| &groups.rare,
+ RareSet::holds,
+ RareSet::adopt,
+ &RARE_SET_GROUPS,
+ ),
+ visual: set(
+ &pointers,
+ borrowed,
+ shares,
+ |groups| &groups.visual,
+ VisualSet::holds,
+ VisualSet::adopt,
+ &VISUAL_SET_GROUPS,
+ ),
+ reset: bits.reset,
+ current_color: 0,
+ }
+ }
+
+ /// Takes over one reference to each of `pointers`, with `inherited` beside the inherited
+ /// groups.
+ ///
+ /// # Safety
+ /// Each of `pointers` must be a live group of its index, with a reference the caller hands over.
+ pub(crate) unsafe fn adopt(pointers: [*const c_void; group_index::COUNT], bits: StyleBits) -> Self {
+ // SAFETY: As the caller guarantees.
+ unsafe { Self::adopt_sharing(pointers, bits, BorrowedGroups::NONE, &[]) }
+ }
+
+ /// Takes one more reference to each of `pointers`, with `inherited` beside the inherited
+ /// groups.
+ ///
+ /// # Safety
+ /// `pointers` must hold one live group of each index, in group order.
+ pub(crate) unsafe fn retained(pointers: &[*const c_void], bits: StyleBits) -> Self {
+ // SAFETY: As the caller guarantees.
+ unsafe { Self::retained_sharing(pointers, bits, &[]) }
+ }
+
+ /// Takes one more reference to each of `pointers`, with `inherited` beside the inherited
+ /// groups, sharing the sets of `shares` that hold the same.
+ ///
+ /// # Safety
+ /// `pointers` must hold one live group of each index, in group order.
+ pub(crate) unsafe fn retained_sharing(
+ pointers: &[*const c_void],
+ bits: StyleBits,
+ shares: &[Option<&StyleGroups>],
+ ) -> Self {
+ let pointers: &[*const c_void; group_index::COUNT] =
+ pointers.try_into().expect("an element's style has every group");
+ for (group, pointer) in pointers.iter().enumerate() {
+ retain_group_payload(group, *pointer);
+ }
+ // SAFETY: Each pointer is live, with the reference just taken.
+ unsafe { Self::adopt_sharing(*pointers, bits, BorrowedGroups::NONE, shares) }
+ }
+
+ /// The address and allocation size of each group set the style holds, which a memory report
+ /// counts once however many styles share it.
+ pub(crate) fn set_allocations(&self) -> [(*const c_void, usize); 3] {
+ fn allocation<T>(set: &SharedGroupSet<T>) -> (*const c_void, usize) {
+ (
+ set.0.as_ptr().cast_const().cast(),
+ crate::heap_size::ARC_HEADER_BYTES + size_of::<T>(),
+ )
+ }
+ [
+ allocation(&self.inherited),
+ allocation(&self.rare),
+ allocation(&self.visual),
+ ]
+ }
+
+ /// The computed value of `property` these groups hold.
+ pub(crate) fn value(&self, property: u16) -> &RetainedStyleValueData {
+ // SAFETY: The style holds a reference to each of its groups.
+ unsafe { value_in_groups_of(|group| self[group].as_ptr(), &self.style_bits(), property) }
+ }
+
+ /// The groups, in group order.
+ pub(crate) fn pointers(&self) -> [*const c_void; group_index::COUNT] {
+ std::array::from_fn(|group| self[group].as_ptr())
+ }
+
+ /// The custom properties the element holds.
+ pub(crate) fn custom_properties(
+ &self,
+ ) -> Option<&std::sync::Arc<crate::css::custom_properties::CustomPropertyStore>> {
+ self.inherited.get().beside.custom_properties.as_ref()
+ }
+
+ /// The inherited longhands these groups hold as bits, and the effective zoom.
+ #[inline]
+ pub(crate) fn inherited_values(&self) -> InheritedSetValues {
+ self.inherited.get().beside.values
+ }
+
+ /// The inherited longhands these groups hold as bits.
+ #[inline]
+ pub(crate) fn inherited_bits(&self) -> InheritedBits {
+ self.inherited.get().beside.values.bits
+ }
+
+ /// The properties that do not inherit these groups hold as bits.
+ #[inline]
+ pub(crate) fn reset_bits(&self) -> ResetBits {
+ self.reset
+ }
+
+ /// What these groups hold as bits beside them.
+ #[inline]
+ pub(crate) fn style_bits(&self) -> StyleBits {
+ StyleBits {
+ inherited: self.inherited_values(),
+ reset: self.reset,
+ }
+ }
+
+ /// These groups, with `bits` beside them: in a copy of the inherited set where it holds other
+ /// inherited bits.
+ pub(crate) fn with_style_bits(mut self, bits: StyleBits) -> Self {
+ self.set_inherited_values(bits.inherited);
+ self.reset = bits.reset;
+ self
+ }
+
+ /// Puts `reset` in place of the reset bits.
+ pub(crate) fn set_reset_bits(&mut self, reset: ResetBits) {
+ self.reset = reset;
+ }
+
+ /// The element's color, resolved, which `currentcolor` in its groups resolves to.
+ #[inline]
+ pub(crate) fn current_color(&self) -> u32 {
+ self.current_color
+ }
+
+ /// These groups, with `current_color` as the element's resolved color.
+ pub(crate) fn with_current_color(mut self, current_color: u32) -> Self {
+ self.current_color = current_color;
+ self
+ }
+
+ /// Puts `values` beside the inherited groups, in a copy of the inherited set where it holds
+ /// others.
+ pub(crate) fn set_inherited_values(&mut self, values: InheritedSetValues) {
+ if self.inherited.get().beside.values != values {
+ self.inherited.make_mut().beside.values = values;
+ }
+ }
+
+ /// These groups, holding `store` as the element's custom properties: in the inherited set they
+ /// share where it holds `store` already, otherwise in a copy of it.
+ pub(crate) fn with_custom_properties(
+ mut self,
+ store: Option<&std::sync::Arc<crate::css::custom_properties::CustomPropertyStore>>,
+ ) -> Self {
+ let holds_store = match (&self.inherited.get().beside.custom_properties, store) {
+ (None, None) => true,
+ (Some(held), Some(store)) => std::sync::Arc::ptr_eq(held, store),
+ _ => false,
+ };
+ if !holds_store {
+ self.inherited.make_mut().beside.custom_properties = store.cloned();
+ }
+ self
+ }
+
+ /// What the computation of the record holding these groups recorded beside its values.
+ pub(crate) fn rare_facts(&self) -> Option<&std::sync::Arc<crate::css::style::pipeline::RareStyleFacts>> {
+ self.rare.get().beside.facts.as_ref()
+ }
+
+ /// The custom declarations the cascade of the element holding these groups decided.
+ pub(crate) fn custom_declarations(&self) -> Option<&crate::css::style::pipeline::CustomDeclarations> {
+ self.rare.get().beside.custom_declarations.as_ref()
+ }
+
+ /// The rare set of these groups.
+ pub(crate) fn rare_set(&self) -> &RareSetRef {
+ // SAFETY: `RareSetRef` is a transparent wrapper of the set's handle.
+ unsafe { &*std::ptr::from_ref(&self.rare).cast::<RareSetRef>() }
+ }
+
+ /// These groups, holding `facts` and `custom_declarations` beside their rare groups: in the
+ /// one of `shares` that holds all three, where one does, otherwise in their own set, copied
+ /// first where it is shared.
+ pub(crate) fn with_rare_facts(
+ mut self,
+ facts: std::sync::Arc<crate::css::style::pipeline::RareStyleFacts>,
+ custom_declarations: Option<crate::css::style::pipeline::CustomDeclarations>,
+ shares: &[Option<&RareSetRef>],
+ ) -> Self {
+ let beside = crate::css::style::pipeline::RareSetFacts {
+ facts: Some(facts),
+ custom_declarations,
+ };
+ let holds_facts = |set: &RareSet| set.beside.is(&beside);
+ if holds_facts(self.rare.get()) {
+ return self;
+ }
+ if let Some(shared) = shares
+ .iter()
+ .flatten()
+ .map(|share| &share.0)
+ .find(|set| set.get().groups == self.rare.get().groups && holds_facts(set.get()))
+ {
+ self.rare = shared.clone();
+ return self;
+ }
+ self.rare.make_mut().beside = beside;
+ self
+ }
+
+ /// Whether `other` holds this style's inherited set itself, and so its inherited groups.
+ pub(crate) fn shares_inherited_groups_with(&self, other: &StyleGroups) -> bool {
+ self.inherited.ptr_eq(&other.inherited)
+ }
+
+ /// Whether `other` holds this style's root groups and its other sets themselves, and so its
+ /// groups of the properties that do not inherit.
+ pub(crate) fn shares_reset_groups_with(&self, other: &StyleGroups) -> bool {
+ self.root == other.root && self.rare.ptr_eq(&other.rare) && self.visual.ptr_eq(&other.visual)
+ }
+
+ /// The groups `other` holds the very same payload of, one bit per group: a set both hold
+ /// itself holds the same payloads, so only the groups of sets they hold apart are compared.
+ pub(crate) fn shared_group_mask(&self, other: &StyleGroups) -> u32 {
+ fn set_mask(groups: &[usize], mine: &[GroupPointer], theirs: &[GroupPointer], same_set: bool) -> u32 {
+ groups
+ .iter()
+ .zip(mine.iter().zip(theirs))
+ .filter(|(_, (mine, theirs))| same_set || mine == theirs)
+ .fold(0, |mask, (&group, _)| mask | 1 << group)
+ }
+ let (inherited, rare, visual) = (
+ self.inherited.ptr_eq(&other.inherited),
+ self.rare.ptr_eq(&other.rare),
+ self.visual.ptr_eq(&other.visual),
+ );
+ set_mask(&ROOT_GROUPS, &self.root, &other.root, false)
+ | set_mask(
+ &INHERITED_SET_GROUPS,
+ &self.inherited.get().groups,
+ &other.inherited.get().groups,
+ inherited,
+ )
+ | set_mask(
+ &RARE_SET_GROUPS,
+ &self.rare.get().groups,
+ &other.rare.get().groups,
+ rare,
+ )
+ | set_mask(
+ &VISUAL_SET_GROUPS,
+ &self.visual.get().groups,
+ &other.visual.get().groups,
+ visual,
+ )
+ }
+
+ /// Whether `other` holds equal payloads of every group, and the same inherited bits and
+ /// zoom: the very same ones where it holds a set itself, and else each group's very same
+ /// payload or an equal one.
+ pub(crate) fn holds_equal_payloads_as(&self, other: &StyleGroups) -> bool {
+ fn equal(groups: &[usize], mine: &[GroupPointer], theirs: &[GroupPointer]) -> bool {
+ groups
+ .iter()
+ .zip(mine.iter().zip(theirs))
+ .all(|(&group, (mine, theirs))| {
+ // SAFETY: Both styles hold a reference to each of their groups.
+ mine == theirs || unsafe { style_group_payloads_equal(group, mine.as_ptr(), theirs.as_ptr()) }
+ })
+ }
+ self.reset == other.reset
+ && equal(&ROOT_GROUPS, &self.root, &other.root)
+ && (self.inherited.ptr_eq(&other.inherited)
+ || (self.inherited_values() == other.inherited_values()
+ && equal(
+ &INHERITED_SET_GROUPS,
+ &self.inherited.get().groups,
+ &other.inherited.get().groups,
+ )))
+ && (self.rare.ptr_eq(&other.rare)
+ || equal(&RARE_SET_GROUPS, &self.rare.get().groups, &other.rare.get().groups))
+ && (self.visual.ptr_eq(&other.visual)
+ || equal(
+ &VISUAL_SET_GROUPS,
+ &self.visual.get().groups,
+ &other.visual.get().groups,
+ ))
+ }
+
+ /// Whether `other` holds the same groups.
+ pub(crate) fn holds_the_same_groups_as(&self, other: &StyleGroups) -> bool {
+ self.root == other.root
+ && self.reset == other.reset
+ && (self.inherited.ptr_eq(&other.inherited)
+ || (self.inherited.get().groups == other.inherited.get().groups
+ && self.inherited_values() == other.inherited_values()))
+ && (self.visual.ptr_eq(&other.visual) || self.visual.get().groups == other.visual.get().groups)
+ && (self.rare.ptr_eq(&other.rare) || self.rare.get().groups == other.rare.get().groups)
+ }
+
+ pub(crate) fn group(&self, index: StyleGroupIndex) -> GroupPayloadRef<'_> {
+ GroupPayloadRef {
+ group_index: index.usize(),
+ pointer: self[index.usize()].0,
+ payload: std::marker::PhantomData,
+ }
+ }
+
+ fn slot_mut(&mut self, group: usize) -> &mut GroupPointer {
+ match GROUP_PLACES[group] {
+ GroupPlace::Root(slot) => &mut self.root[slot as usize],
+ GroupPlace::Inherited(slot) => &mut self.inherited.make_mut().groups[slot as usize],
+ GroupPlace::Visual(slot) => &mut self.visual.make_mut().groups[slot as usize],
+ GroupPlace::Rare(slot) => &mut self.rare.make_mut().groups[slot as usize],
+ }
+ }
+
+ /// Puts `group` in place of the group at its index, answering the one it held.
+ pub(crate) fn replace(&mut self, group: HeldGroup) -> HeldGroup {
+ let index = group.group;
+ let new = GroupPointer(std::ptr::NonNull::new(group.payload.cast_mut()).expect("a style group is never null"));
+ std::mem::forget(group);
+ if self[index] == new {
+ // A set another style shares stays shared where its group does not change.
+ return HeldGroup {
+ group: index,
+ payload: new.as_ptr(),
+ };
+ }
+ let pointer = std::mem::replace(self.slot_mut(index), new);
+ HeldGroup {
+ group: index,
+ payload: pointer.as_ptr(),
+ }
+ }
+
+ /// Puts `other`'s group at `index` in place of this one's.
+ pub(crate) fn share_group(&mut self, other: &StyleGroups, index: StyleGroupIndex) {
+ drop(self.replace(other.group(index).held()));
+ }
+
+ /// Puts a copy of the group of `T`, written by `write`, in place of it.
+ ///
+ /// # Safety
+ /// The group at `index` must be a `T`.
+ pub(crate) unsafe fn write_group<T>(&mut self, index: usize, write: impl FnOnce(&mut T)) {
+ // SAFETY: The style holds a reference to its group, and the copy is uniquely owned.
+ let copy = unsafe { clone_group_payload(index, self[index].as_ptr()) };
+ // SAFETY: As the caller guarantees, the copy is a `T`.
+ write(unsafe { &mut *copy.cast::<T>() });
+ drop(self.replace(HeldGroup {
+ group: index,
+ payload: copy.cast_const(),
+ }));
+ }
+
+ /// The groups, in group order.
+ pub(crate) fn iter(&self) -> impl Iterator<Item = GroupPointer> + '_ {
+ (0..group_index::COUNT).map(|group| self[group])
+ }
+}
+
+impl std::ops::Index<usize> for StyleGroups {
+ type Output = GroupPointer;
+
+ #[inline]
+ fn index(&self, group: usize) -> &GroupPointer {
+ match GROUP_PLACES[group] {
+ GroupPlace::Root(slot) => &self.root[slot as usize],
+ GroupPlace::Inherited(slot) => &self.inherited.get().groups[slot as usize],
+ GroupPlace::Visual(slot) => &self.visual.get().groups[slot as usize],
+ GroupPlace::Rare(slot) => &self.rare.get().groups[slot as usize],
+ }
+ }
+}
+
+impl Clone for StyleGroups {
+ fn clone(&self) -> Self {
+ for (pointer, group) in self.root.iter().zip(ROOT_GROUPS) {
+ retain_group_payload(group, pointer.as_ptr());
+ }
+ Self {
+ root: self.root,
+ inherited: self.inherited.clone(),
+ rare: self.rare.clone(),
+ visual: self.visual.clone(),
+ reset: self.reset,
+ current_color: self.current_color,
+ }
+ }
+}
+
+impl Drop for StyleGroups {
+ fn drop(&mut self) {
+ for (pointer, group) in self.root.iter().zip(ROOT_GROUPS) {
+ release_group_payload(group, pointer.as_ptr());
+ }
+ }
+}
+
+impl std::fmt::Debug for StyleGroups {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter.debug_list().entries(self.pointers()).finish()
+ }
+}
+
+/// A live payload of the style group at `group_index`, borrowed for `'a`.
+#[derive(Clone, Copy)]
+pub(crate) struct GroupPayloadRef<'a> {
+ group_index: usize,
+ pointer: std::ptr::NonNull<c_void>,
+ payload: std::marker::PhantomData<&'a c_void>,
+}
+
+impl<'a> GroupPayloadRef<'a> {
+ /// The payload `pointer` names, or `None` for a null pointer.
+ ///
+ /// # Safety
+ /// A non-null `pointer` must be a payload of the group at `group_index` that stays live and
+ /// unmodified for `'a`.
+ pub(crate) unsafe fn new(group_index: usize, pointer: *const c_void) -> Option<Self> {
+ assert!(group_index < group_index::COUNT);
+ Some(Self {
+ group_index,
+ pointer: std::ptr::NonNull::new(pointer.cast_mut())?,
+ payload: std::marker::PhantomData,
+ })
+ }
+
+ /// The computed values the payload's group holds.
+ pub(crate) fn group_values(self) -> &'a [RetainedStyleValueData] {
+ // SAFETY: The payload is live for 'a.
+ unsafe { values_of(style_group(self.group_index), self.as_ptr()) }
+ }
+
+ pub(crate) fn as_ptr(self) -> *const c_void {
+ self.pointer.as_ptr().cast_const()
+ }
+
+ /// The payload as its group's type, which must be `T`.
+ fn values<T: StyleGroupPayload>(self) -> &'a T {
+ assert_group_payload_type::<T>(self.group_index);
+ // SAFETY: The payload is live for 'a and its group's type is `T`.
+ unsafe { payload_ref::<T>(self.as_ptr()) }
+ }
+
+ /// Whether the payload holds the group's initial values, as a default-constructed payload does.
+ pub(crate) fn holds_the_defaults(self) -> bool {
+ self.equals(ScratchPayload::new_default(self.group_index).as_ref())
+ }
+
+ /// Whether `other`, a payload of the same group, holds the same values.
+ fn equals(self, other: GroupPayloadRef<'_>) -> bool {
+ assert_eq!(self.group_index, other.group_index);
+ // SAFETY: Both payloads are live payloads of the group.
+ unsafe { payloads_equal(style_group(self.group_index), self.as_ptr(), other.as_ptr()) }
+ }
+
+ /// The group, with one more reference to it.
+ pub(crate) fn held(self) -> HeldGroup {
+ HeldGroup {
+ group: self.group_index,
+ payload: self.retained(),
+ }
+ }
+
+ /// The payload, with one more reference for the caller.
+ fn retained(self) -> *const c_void {
+ retain_group_payload(self.group_index, self.as_ptr());
+ self.as_ptr()
+ }
+}
+
+/// A freshly allocated payload of one group, which holds the payload's one reference and frees it unless published.
+struct ScratchPayload {
+ group_index: usize,
+ pointer: *mut c_void,
+}
+
+impl ScratchPayload {
+ fn new_default(group_index: usize) -> Self {
+ let group = style_group(group_index);
+ let pointer = allocate_payload(group, 1);
+ // SAFETY: The payload was just allocated with the layout of the group's type.
+ unsafe { default_construct(group, pointer) };
+ Self { group_index, pointer }
+ }
+
+ fn apply_pokes(&mut self, pokes: &[GroupFieldPoke<'_>]) {
+ // SAFETY: The pokes come from the group's registered descriptors, whose offsets name fields of the right
+ // type in the group's payload, and nothing else references the scratch payload yet.
+ unsafe { apply_group_field_pokes(self.pointer, pokes) };
+ }
+
+ /// The payload as its group's type, which must be `T`.
+ fn values_mut<T: StyleGroupPayload>(&mut self) -> &mut T {
+ assert_group_payload_type::<T>(self.group_index);
+ // SAFETY: The scratch payload is a live payload of type `T` that only this guard references.
+ unsafe { &mut *self.pointer.cast::<T>() }
+ }
+
+ fn as_ref(&self) -> GroupPayloadRef<'_> {
+ // SAFETY: The scratch payload is live while the guard is, and nothing modifies it while borrowed.
+ unsafe { GroupPayloadRef::new(self.group_index, self.pointer) }.expect("allocation never returns null")
+ }
+
+ /// Hands the payload and its one reference to the caller.
+ fn publish(self) -> *const c_void {
+ let pointer = self.pointer.cast_const();
+ std::mem::forget(self);
+ pointer
+ }
+}
+
+impl Drop for ScratchPayload {
+ fn drop(&mut self) {
+ // SAFETY: The scratch payload was never published, so this guard holds its only reference.
+ unsafe { free_scratch_payload(style_group(self.group_index), self.pointer) };
+ }
+}
+
+/// The payload a build of the group at `group_index` can share instead of publishing its own: the parent's payload,
+/// retained for the caller, or the group's default payload, whichever `matches` first.
+fn share_matching_group_payload(
+ group_index: usize,
+ shares: GroupShares<'_>,
+ matches: impl Fn(GroupPayloadRef<'_>) -> bool,
+) -> Option<*const c_void> {
+ if let Some(parent) = shares.parent {
+ assert_eq!(parent.group_index, group_index);
+ if matches(parent) {
+ return Some(parent.retained());
+ }
+ }
+ assert_eq!(shares.default.group_index, group_index);
+ matches(shares.default).then(|| shares.default.retained())
+}
+
+/// The payloads a group being built may share instead of holding its own: the parent's payload of
+/// the group, if any, and else the process's default payload.
+#[derive(Clone, Copy)]
+pub(crate) struct GroupShares<'a> {
+ pub(crate) parent: Option<GroupPayloadRef<'a>>,
+ pub(crate) default: GroupPayloadRef<'a>,
+}
+
+impl<'a> GroupShares<'a> {
+ pub(crate) fn new(defaults: &'a DefaultGroups, group: usize, parent: Option<GroupPayloadRef<'a>>) -> Self {
+ Self {
+ parent,
+ default: defaults.groups().group(StyleGroupIndex::new(group)),
+ }
+ }
+
+ /// The default payload, with one more reference to it.
+ pub(crate) fn default_retained(self) -> *const c_void {
+ self.default.retained()
+ }
+}
+
+/// The payload `built` can share instead of being published.
+fn share_equal_group_payload(built: GroupPayloadRef<'_>, parent: GroupShares<'_>) -> Option<*const c_void> {
+ share_matching_group_payload(built.group_index, parent, |candidate| built.equals(candidate))
+}
+
+/// The payload a built group value can share instead of allocating its own.
+fn share_group_payload<T: StyleGroupPayload + PartialEq>(
+ group_index: usize,
+ built: &T,
+ parent: GroupShares<'_>,
+) -> Option<*const c_void> {
+ assert_group_payload_type::<T>(group_index);
+ share_matching_group_payload(group_index, parent, |candidate| built == candidate.values::<T>())
+}
+
+/// The payload a built group value shares, or else a fresh payload holding it. Either carries one reference for the
+/// caller.
+fn share_or_publish_group_payload<T: StyleGroupPayload + PartialEq>(
+ group_index: usize,
+ built: T,
+ parent: GroupShares<'_>,
+) -> *const c_void {
+ share_group_payload(group_index, &built, parent).unwrap_or_else(|| publish_group_payload(group_index, built))
+}
+
+/// The payload of a group holding the values `source` holds but for what `patch` changes: a
+/// shared payload where one equals it, or else a fresh one. Either carries one reference for the
+/// caller.
+///
+/// # Safety
+/// `source` must be a live payload of the group at `group_index`, whose type is `T`.
+pub(crate) unsafe fn patch_group_payload<T: StyleGroupPayload + PartialEq + Clone>(
+ group_index: usize,
+ source: *const c_void,
+ patch: impl FnOnce(&mut T),
+ parent: GroupShares<'_>,
+) -> *const c_void {
+ assert_group_payload_type::<T>(group_index);
+ // SAFETY: The caller passes a live payload of the group, whose type was just asserted.
+ let mut built = unsafe { payload_ref::<T>(source) }.clone();
+ patch(&mut built);
+ share_or_publish_group_payload(group_index, built, parent)
+}
+
+/// Moves a built group value into a fresh payload that carries one reference for the caller.
+fn publish_group_payload<T: StyleGroupPayload>(group_index: usize, built: T) -> *const c_void {
+ assert_group_payload_type::<T>(group_index);
+ let payload = allocate_payload(style_group(group_index), 1);
+ // SAFETY: The payload was just allocated with the layout of the group's type, which is `T`.
+ unsafe { payload.cast::<T>().write(built) };
+ payload.cast_const()
+}
+
+/// Allocates a new payload for `group_index` with a reference count of one,
+/// copy-constructed from `source`.
+///
+/// # Safety
+/// `source` must be a valid payload of the same group type.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_style_group_clone(group_index: usize, source: *const c_void) -> *mut c_void {
+ unsafe { clone_group_payload(group_index, source) }
+}
+
+/// The source must be a live payload of the registered group type.
+pub(crate) unsafe fn clone_group_payload(group_index: usize, source: *const c_void) -> *mut c_void {
+ let group = style_group(group_index);
+ let payload = allocate_payload(group, 1);
+ unsafe {
+ copy_construct(group, payload, source);
+ values_of_mut(group, payload).clone_from_slice(values_of(group, source));
+ }
+ payload
+}
+
+/// Destroys and deallocates a payload whose reference count has reached zero.
+///
+/// # Safety
+/// `payload` must be a payload of the given group type with no remaining
+/// references, and must not be a static default payload.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_style_group_free(group_index: usize, payload: *mut c_void) {
+ unsafe {
+ let group = style_group(group_index);
+ debug_assert!(refcount_of(payload, payload_align(group)).load(Ordering::Relaxed) == 0);
+ destroy_allocation(group, payload);
+ };
+}
+
+pub(crate) fn release_group_payload(group_index: usize, payload: *const c_void) {
+ let group = style_group(group_index);
+ let refcount = refcount_of(payload, payload_align(group));
+ if refcount.fetch_sub(1, Ordering::AcqRel) == 1 {
+ // SAFETY: The count reached zero, so this reference was the last one.
+ unsafe { destroy_allocation(group, payload.cast_mut()) }
+ }
+}
+
+/// The computed values the group of `payload`, a payload of the group at `group_index`, holds, in
+/// the order of the group's longhands.
+///
+/// # Safety
+/// `payload` must be a live payload of the group that stays live for `'a`.
+pub(crate) unsafe fn group_values<'a>(group_index: usize, payload: *const c_void) -> &'a [RetainedStyleValueData] {
+ unsafe { values_of(style_group(group_index), payload) }
+}
+
+/// The computed value of `property` in the groups `group_of` answers by group index, with
+/// `inherited` beside the inherited groups.
+///
+/// # Safety
+/// The groups `group_of` answers must be live payloads of the group at their index, which stay
+/// live for `'a`.
+unsafe fn value_in_groups_of<'a>(
+ group_of: impl Fn(usize) -> *const c_void + Copy,
+ bits: &StyleBits,
+ property: u16,
+) -> &'a RetainedStyleValueData {
+ // SAFETY: As the caller guarantees.
+ let property = GROUP_VALUE_LAYOUT.resolved(property, |property| unsafe {
+ value_in_groups_of(group_of, bits, property)
+ });
+ let place = GROUP_VALUE_LAYOUT.place_of(property);
+ if let Some(field) = place.bit_field() {
+ return bits.value(field);
+ }
+ // SAFETY: As the caller guarantees.
+ unsafe {
+ let payload = group_of(place.group());
+ place.value_in(payload, group_values(place.group(), payload))
+ }
+}
+
+/// The computed value at `place` of `group`, a payload of the place's group.
+pub(crate) fn value_at(group: GroupPayloadRef<'_>, place: LonghandPlace) -> &RetainedStyleValueData {
+ // SAFETY: The payload is live for as long as `group` is borrowed and holds its group's values.
+ unsafe { place.value_in(group.as_ptr(), group.group_values()) }
+}
+
+/// Whether the groups `first` and `second`, payloads of the group at `group_index`, hold the same
+/// computed values, each by identity or else by value, in their values and their payload handles.
+///
+/// # Safety
+/// Both must be live payloads of the group.
+pub(crate) unsafe fn hold_the_same_values(group_index: usize, first: *const c_void, second: *const c_void) -> bool {
+ let (first_values, second_values) =
+ unsafe { (group_values(group_index, first), group_values(group_index, second)) };
+ same_group_values(first_values, second_values)
+ && GroupValueLayout::handles_of(group_index).all(|(_, place)| {
+ // SAFETY: As the caller guarantees.
+ let (first, second) = unsafe {
+ (
+ place.value_in(first, first_values),
+ place.value_in(second, second_values),
+ )
+ };
+ first.pointer() == second.pointer() || first == second
+ })
+}
+
+/// Whether `first` and `second` hold the same computed values, each by identity or else by value.
+pub(crate) fn same_group_values(first: &[RetainedStyleValueData], second: &[RetainedStyleValueData]) -> bool {
+ first.len() == second.len()
+ && first
+ .iter()
+ .zip(second)
+ .all(|(first, second)| first.pointer() == second.pointer() || first == second)
+}
+
+/// Whether the groups `first` and `second`, payloads of the group at `group_index`, hold the same
+/// payload and the same computed values.
+///
+/// # Safety
+/// Both must be live payloads of the group.
+pub(crate) unsafe fn groups_hold_the_same(group_index: usize, first: *const c_void, second: *const c_void) -> bool {
+ let group = style_group(group_index);
+ first == second
+ || unsafe {
+ payloads_equal(group, first, second) && same_group_values(values_of(group, first), values_of(group, second))
+ }
+}
+
+/// The group holding the payload of `payload` and the computed values `values`, which takes over
+/// the caller's reference to `payload` and carries one for the caller: `payload` itself where it
+/// holds those values already, else the first of `candidates` holding the same payload and values,
+/// else `payload` with the values written into it where only the caller references it, else a copy
+/// of it holding them.
+///
+/// # Safety
+/// `payload` and every non-null candidate must be live payloads of the group at `group_index`.
+pub(crate) unsafe fn group_with_values(
+ group_index: usize,
+ payload: *const c_void,
+ values: &[RetainedStyleValueData],
+ candidates: &[*const c_void],
+) -> *const c_void {
+ let group = style_group(group_index);
+ assert_eq!(values.len(), value_count(group));
+ // SAFETY: The caller passes live payloads of the group.
+ unsafe {
+ if same_group_values(values_of(group, payload), values) {
+ return payload;
+ }
+ if let Some(&shared) = candidates.iter().find(|&&candidate| {
+ !candidate.is_null()
+ && candidate != payload
+ && payloads_equal(group, candidate, payload)
+ && same_group_values(values_of(group, candidate), values)
+ }) {
+ retain_group_payload(group_index, shared);
+ release_group_payload(group_index, payload);
+ return shared;
+ }
+ let refcount = refcount_of(payload, payload_align(group));
+ if refcount.load(Ordering::Acquire) == 1 {
+ values_of_mut(group, payload.cast_mut()).clone_from_slice(values);
+ return payload;
+ }
+ let copy = allocate_payload(group, 1);
+ copy_construct(group, copy, payload);
+ values_of_mut(group, copy).clone_from_slice(values);
+ release_group_payload(group_index, payload);
+ copy.cast_const()
+ }
+}
+
+/// Clamps a border box size by the min and max sizes of a sizing group that resolve against the given basis, as
+/// resizing an element by its resizer does.
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_sizing_values_clamp_size(
+ values: &SizingValues,
+ basis_width: f64,
+ basis_height: f64,
+ width: &mut f64,
+ height: &mut f64,
+) {
+ use crate::css::css_pixels::CssPixels;
+ let clamp = |size: f64, basis: f64, minimum: &ComputedSize, maximum: &ComputedSize| {
+ let basis = CssPixels::nearest_value_for(basis);
+ let mut size = size;
+ if minimum.is_length_percentage() {
+ size = size.max(minimum.to_px(basis).to_double());
+ }
+ if maximum.is_length_percentage() {
+ size = size.min(maximum.to_px(basis).to_double());
+ }
+ size
+ };
+ *width = clamp(*width, basis_width, &values.min_width, &values.max_width);
+ *height = clamp(*height, basis_height, &values.min_height, &values.max_height);
+}
+
+/// The used line height of a font group, as [`FontValues::line_height_used`] reads it.
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_font_values_line_height_used_raw(values: &FontValues) -> i32 {
+ values.line_height_used().raw_value()
+}
+
+/// The pixels of a computed size given as an absolute length, written to `pixels`. Returns false for any other size.
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_computed_size_absolute_length_px(size: &ComputedSize, pixels: &mut f64) -> bool {
+ let Some(StyleValueData::Length { value, unit }) = size.value.style_value() else {
+ return false;
+ };
+ if size.kind != ComputedSizeKind::Length {
+ return false;
+ }
+ let ratio = crate::css::style_compute::LENGTH_UNIT_CANONICAL_PX_RATIOS[*unit as usize];
+ if !ratio.is_finite() {
+ return false;
+ }
+ *pixels = value * ratio;
+ true
+}
+
+/// One field of a style group the generic builder can populate or check: a pokeable simple field
+/// at `offset` in the group's payload, or a constraint requiring the value to be one that leaves
+/// the payload's initial value standing.
+#[derive(Clone, Copy)]
+pub(crate) struct GroupFieldDescriptor {
+ pub(crate) property_id: u16,
+ pub(crate) offset: usize,
+ pub(crate) kind: GroupFieldKind,
+}
+
+#[derive(Clone, Copy)]
+pub(crate) enum GroupFieldKind {
+ /// An enum stored as u8: the keyword's code through the converter. A keyword it rejects stays
+ /// at the payload default for the Rust group builder to complete.
+ EnumKeyword(fn(u16) -> Option<u8>),
+ /// A number stored as f64.
+ F64,
+ /// A pixel length stored as raw CSSPixels (i32).
+ CssPixels,
+ /// A pixel length stored as raw CSSPixels, clamped at zero.
+ CssPixelsNonNegative,
+ /// An integer stored as u64.
+ U64,
+ /// A color stored as the C++ Color's raw 32-bit value, resolved by the gather loop, which owns
+ /// the color resolution context.
+ Color,
+ /// A color stored as a [`crate::css::computed_value_types::StyleColor`]: plain `currentcolor`
+ /// stays for the reader to resolve, any other color is resolved by the gather loop.
+ HeldColor,
+ /// A color like `HeldColor`, except that this keyword leaves the initial value standing, for
+ /// fields like outline-color whose auto keyword is not a resolvable color.
+ HeldColorOrKeyword(u16),
+ /// A number resolved by the gather loop, for values whose normalization has not moved into the
+ /// core, like opacity: stored as f32, as f64, or as one byte for derived enum fields like the
+ /// used color-scheme.
+ ResolvedF32,
+ ResolvedF64,
+ ResolvedU8,
+ /// The value's data stored into a single-pointer handle slot, retaining one reference; the
+ /// slot's initial value must be null.
+ RetainedData,
+ /// A bool stored as one byte: whether the value is this keyword.
+ KeywordEqualsBool(u16),
+ /// Constraints, which write nothing: the value must be this keyword, a zero pixel length, or
+ /// the property's initial value. The last compares data pointers, which holds exactly for
+ /// untouched properties since the driver selects the initial table's entries directly.
+ RequireKeyword(u16),
+ RequireZeroPx,
+ RequireInitialValue,
+}
+
+/// The appearance keywords without the compatibility ones, which normalize to auto for the
+/// appearance field but stay raw for computed_appearance: the misc-reset group builder completes
+/// both fields for them.
+fn appearance_without_compat(keyword: u16) -> Option<u8> {
+ use crate::css::css_enums::appearance::{AUTO, MENULIST_BUTTON, NONE, TEXTFIELD};
+ crate::css::css_enums::keyword_to_appearance(keyword)
+ .filter(|appearance| matches!(*appearance, AUTO | MENULIST_BUTTON | NONE | TEXTFIELD))
+}
+
+/// The fields of each group the generic builder decodes, in the order the gather loop reads their
+/// values. Groups that build through bespoke calls have none.
+pub(crate) fn group_field_descriptors(group: usize) -> &'static [GroupFieldDescriptor] {
+ use crate::css::css_enums as enums;
+ use crate::css::css_enums::keyword as k;
+ use GroupFieldKind::*;
+
+ // `PROPERTY @ field => kind` describes a field of the group's payload, `PROPERTY => kind` a
+ // constraint.
+ macro_rules! fields {
+ ($group:ty: $($property:ident $(@ $($field:ident).+)? => $kind:expr),* $(,)?) => {
+ const {
+ &[$(GroupFieldDescriptor {
+ property_id: crate::css::property_metadata::property_id::$property,
+ offset: 0 $(+ std::mem::offset_of!($group, $($field).+))?,
+ kind: $kind,
+ }),*]
+ }
+ };
+ }
+
+ match group {
+ group_index::TEXT_RESET => fields! { TextResetValues:
+ TEXT_DECORATION_LINE => RequireKeyword(k::NONE),
+ TEXT_DECORATION_THICKNESS => RequireKeyword(k::AUTO),
+ TEXT_DECORATION_STYLE @ text_decoration_style => EnumKeyword(enums::keyword_to_text_decoration_style),
+ TEXT_DECORATION_COLOR @ text_decoration_color => HeldColor,
+ WHITE_SPACE_TRIM => RequireKeyword(k::NONE),
+ },
+ group_index::EFFECTS => fields! { EffectsValues:
+ OPACITY @ opacity => ResolvedF32,
+ FILTER => RequireKeyword(k::NONE),
+ BACKDROP_FILTER => RequireKeyword(k::NONE),
+ MIX_BLEND_MODE @ mix_blend_mode => EnumKeyword(enums::keyword_to_mix_blend_mode),
ISOLATION @ isolation => EnumKeyword(enums::keyword_to_isolation),
BOX_SHADOW => RequireKeyword(k::NONE),
CLIP => RequireKeyword(k::AUTO),
},
- group_index::MISC_RESET => fields! { MiscResetValues:
- SCROLL_MARGIN_TOP => RequireZeroPx,
- SCROLL_MARGIN_RIGHT => RequireZeroPx,
- SCROLL_MARGIN_BOTTOM => RequireZeroPx,
- SCROLL_MARGIN_LEFT => RequireZeroPx,
- SCROLL_PADDING_TOP => RequireKeyword(k::AUTO),
- SCROLL_PADDING_RIGHT => RequireKeyword(k::AUTO),
- SCROLL_PADDING_BOTTOM => RequireKeyword(k::AUTO),
- SCROLL_PADDING_LEFT => RequireKeyword(k::AUTO),
+ group_index::MISC_LAYOUT => fields! { MiscLayoutValues:
OVERFLOW_CLIP_MARGIN_TOP => RequireInitialValue,
OVERFLOW_CLIP_MARGIN_RIGHT => RequireInitialValue,
OVERFLOW_CLIP_MARGIN_BOTTOM => RequireInitialValue,
@@ -2250,13 +3124,27 @@ pub(crate) fn group_field_descriptors(group: usize) -> &'static [GroupFieldDescr
OUTLINE_STYLE @ outline_style => EnumKeyword(enums::keyword_to_outline_style),
OBJECT_FIT @ object_fit => EnumKeyword(enums::keyword_to_object_fit),
COLUMN_HEIGHT => RequireKeyword(k::AUTO),
- OUTLINE_COLOR @ outline_color => ColorOrKeyword(k::AUTO),
+ OUTLINE_COLOR @ outline_color => HeldColorOrKeyword(k::AUTO),
OUTLINE_OFFSET => RequireZeroPx,
OUTLINE_WIDTH @ outline_width => CssPixelsNonNegative,
- COLUMN_RULE_COLOR @ column_rule_color => Color,
+ COLUMN_RULE_COLOR @ column_rule_color => HeldColor,
COLUMN_RULE_WIDTH @ column_rule_width => CssPixelsNonNegative,
- USER_SELECT @ user_select => EnumKeyword(enums::keyword_to_user_select),
OBJECT_POSITION => RequireInitialValue,
+ SHAPE_IMAGE_THRESHOLD @ shape_image_threshold => ResolvedF64,
+ SHAPE_MARGIN => RequireZeroPx,
+ SHAPE_OUTSIDE => RequireKeyword(k::NONE),
+ CONTENT_VISIBILITY @ content_visibility => EnumKeyword(enums::keyword_to_content_visibility),
+ },
+ group_index::MISC_INTERACTION => fields! { MiscInteractionValues:
+ SCROLL_MARGIN_TOP => RequireZeroPx,
+ SCROLL_MARGIN_RIGHT => RequireZeroPx,
+ SCROLL_MARGIN_BOTTOM => RequireZeroPx,
+ SCROLL_MARGIN_LEFT => RequireZeroPx,
+ SCROLL_PADDING_TOP => RequireKeyword(k::AUTO),
+ SCROLL_PADDING_RIGHT => RequireKeyword(k::AUTO),
+ SCROLL_PADDING_BOTTOM => RequireKeyword(k::AUTO),
+ SCROLL_PADDING_LEFT => RequireKeyword(k::AUTO),
+ USER_SELECT @ user_select => EnumKeyword(enums::keyword_to_user_select),
VIEW_TRANSITION_CLASS => RequireKeyword(k::NONE),
VIEW_TRANSITION_NAME => RequireKeyword(k::NONE),
TOUCH_ACTION => RequireInitialValue,
@@ -2268,9 +3156,6 @@ pub(crate) fn group_field_descriptors(group: usize) -> &'static [GroupFieldDescr
SCROLLBAR_WIDTH @ scrollbar_width => EnumKeyword(enums::keyword_to_scrollbar_width),
OVERSCROLL_BEHAVIOR_X @ overscroll_behavior_x => EnumKeyword(enums::keyword_to_overscroll_behavior),
OVERSCROLL_BEHAVIOR_Y @ overscroll_behavior_y => EnumKeyword(enums::keyword_to_overscroll_behavior),
- SHAPE_IMAGE_THRESHOLD @ shape_image_threshold => ResolvedF64,
- SHAPE_MARGIN => RequireZeroPx,
- SHAPE_OUTSIDE => RequireKeyword(k::NONE),
WILL_CHANGE => RequireKeyword(k::AUTO),
},
group_index::INHERITED_TEXT => fields! { InheritedTextValues:
@@ -2280,18 +3165,14 @@ pub(crate) fn group_field_descriptors(group: usize) -> &'static [GroupFieldDescr
_WEBKIT_TEXT_FILL_COLOR @ webkit_text_fill_color => Color,
_WEBKIT_TEXT_FILL_COLOR @ webkit_text_fill_color_is_current_color => KeywordEqualsBool(k::CURRENTCOLOR),
TEXT_SHADOW => RequireKeyword(k::NONE),
- TEXT_ALIGN @ text_align => EnumKeyword(enums::keyword_to_text_align),
TEXT_JUSTIFY @ text_justify => EnumKeyword(enums::keyword_to_text_justify),
TEXT_TRANSFORM @ text_transform => EnumKeyword(enums::keyword_to_text_transform),
- TEXT_WRAP_MODE @ text_wrap_mode => EnumKeyword(enums::keyword_to_text_wrap_mode),
TEXT_WRAP_STYLE @ text_wrap_style => EnumKeyword(enums::keyword_to_text_wrap_style),
TEXT_DECORATION_SKIP_INK @ text_decoration_skip_ink => EnumKeyword(enums::keyword_to_text_decoration_skip_ink),
TEXT_UNDERLINE_POSITION => RequireKeyword(k::AUTO),
TEXT_UNDERLINE_OFFSET => RequireKeyword(k::AUTO),
TEXT_INDENT => RequireInitialValue,
TAB_SIZE => RequireInitialValue,
- WHITE_SPACE_COLLAPSE @ white_space_collapse => EnumKeyword(enums::keyword_to_white_space_collapse),
- WORD_BREAK @ word_break => EnumKeyword(enums::keyword_to_word_break),
LINE_BREAK @ line_break => EnumKeyword(enums::keyword_to_line_break),
OVERFLOW_WRAP @ overflow_wrap => EnumKeyword(enums::keyword_to_overflow_wrap),
BLOCK_ELLIPSIS @ block_ellipsis => RetainedData,
@@ -2303,17 +3184,16 @@ pub(crate) fn group_field_descriptors(group: usize) -> &'static [GroupFieldDescr
WIDOWS @ widows => U64,
},
group_index::INHERITED_UI => fields! { InheritedUIValues:
- CARET_COLOR @ caret_color.used_color => Color,
CARET_COLOR => RequireKeyword(k::AUTO),
- ACCENT_COLOR @ accent_color.used_color => Color,
+ ACCENT_COLOR @ accent_color.color => HeldColor,
ACCENT_COLOR => RequireKeyword(k::AUTO),
CURSOR => RequireKeyword(k::AUTO),
- POINTER_EVENTS @ pointer_events => EnumKeyword(enums::keyword_to_pointer_events),
FORCED_COLOR_ADJUST @ forced_color_adjust => EnumKeyword(enums::keyword_to_forced_color_adjust),
INTERPOLATE_SIZE @ interpolate_size => EnumKeyword(enums::keyword_to_interpolate_size),
SCROLLBAR_COLOR => RequireKeyword(k::AUTO),
COLOR_SCHEME @ color_scheme => ResolvedU8,
COLOR_SCHEME => RequireInitialValue,
+ IMAGE_RENDERING @ image_rendering => EnumKeyword(enums::keyword_to_image_rendering),
},
group_index::TRANSFORM => fields! { TransformValues:
TRANSFORM => RequireKeyword(k::NONE),
@@ -2390,11 +3270,11 @@ pub(crate) fn group_field_descriptors(group: usize) -> &'static [GroupFieldDescr
DOMINANT_BASELINE => RequireKeyword(k::AUTO),
SHAPE_RENDERING @ shape_rendering => EnumKeyword(enums::keyword_to_shape_rendering),
},
- group_index::INHERITED_LIST => fields! { InheritedListValues:
+ group_index::INHERITED_LIST_TABLE => fields! { InheritedListTableValues:
LIST_STYLE_TYPE => RequireInitialValue,
- LIST_STYLE_POSITION @ list_style_position => EnumKeyword(enums::keyword_to_list_style_position),
LIST_STYLE_IMAGE => RequireKeyword(k::NONE),
QUOTES => RequireKeyword(k::AUTO),
+ BORDER_SPACING => RequireInitialValue,
},
group_index::CONTENT => fields! { ContentValues:
CONTENT => RequireKeyword(k::NORMAL),
@@ -2414,19 +3294,19 @@ pub(crate) fn group_field_descriptors(group: usize) -> &'static [GroupFieldDescr
// A none border-style keeps the used width at zero; the Rust group builder completes styled
// borders.
group_index::BORDER => fields! { BorderValues:
- BORDER_LEFT_COLOR @ border_left.color => Color,
+ BORDER_LEFT_COLOR @ border_left.color => HeldColor,
BORDER_LEFT_COLOR => RequireInitialValue,
BORDER_LEFT_STYLE => RequireKeyword(k::NONE),
BORDER_LEFT_WIDTH @ border_left_computed_width => CssPixelsNonNegative,
- BORDER_TOP_COLOR @ border_top.color => Color,
+ BORDER_TOP_COLOR @ border_top.color => HeldColor,
BORDER_TOP_COLOR => RequireInitialValue,
BORDER_TOP_STYLE => RequireKeyword(k::NONE),
BORDER_TOP_WIDTH @ border_top_computed_width => CssPixelsNonNegative,
- BORDER_RIGHT_COLOR @ border_right.color => Color,
+ BORDER_RIGHT_COLOR @ border_right.color => HeldColor,
BORDER_RIGHT_COLOR => RequireInitialValue,
BORDER_RIGHT_STYLE => RequireKeyword(k::NONE),
BORDER_RIGHT_WIDTH @ border_right_computed_width => CssPixelsNonNegative,
- BORDER_BOTTOM_COLOR @ border_bottom.color => Color,
+ BORDER_BOTTOM_COLOR @ border_bottom.color => HeldColor,
BORDER_BOTTOM_COLOR => RequireInitialValue,
BORDER_BOTTOM_STYLE => RequireKeyword(k::NONE),
BORDER_BOTTOM_WIDTH @ border_bottom_computed_width => CssPixelsNonNegative,
@@ -2446,7 +3326,7 @@ pub(crate) fn group_field_descriptors(group: usize) -> &'static [GroupFieldDescr
BORDER_IMAGE_WIDTH => RequireInitialValue,
},
group_index::BACKGROUND => fields! { BackgroundValues:
- BACKGROUND_COLOR @ background_color => Color,
+ BACKGROUND_COLOR @ background_color => HeldColor,
BACKGROUND_COLOR => RequireInitialValue,
BACKGROUND_IMAGE => RequireInitialValue,
BACKGROUND_CLIP => RequireInitialValue,
@@ -2460,98 +3340,2002 @@ pub(crate) fn group_field_descriptors(group: usize) -> &'static [GroupFieldDescr
},
_ => &[],
}
-}
+}
+
+/// How many longhands there are, logical aliases included.
+const LONGHAND_COUNT: usize = (crate::css::property_metadata::LAST_LONGHAND_PROPERTY_ID
+ - crate::css::property_metadata::FIRST_LONGHAND_PROPERTY_ID
+ + 1) as usize;
+
+const fn longhand_index_of(property: u16) -> usize {
+ (property - crate::css::property_metadata::FIRST_LONGHAND_PROPERTY_ID) as usize
+}
+
+const fn is_logical_alias(property: u16) -> bool {
+ use crate::css::property_metadata::{FIRST_SHORTHAND_PROPERTY_ID, PROPERTY_IS_LOGICAL_ALIAS};
+ PROPERTY_IS_LOGICAL_ALIAS[(property - FIRST_SHORTHAND_PROPERTY_ID) as usize]
+}
+
+/// Whether `property` is a logical alias that maps to a physical longhand in every flow, which it
+/// then computes as.
+const fn maps_in_every_flow(property: u16) -> bool {
+ use crate::css::style_compute::{DIRECTION_COUNT, WRITING_MODE_COUNT};
+ if !is_logical_alias(property) {
+ return false;
+ }
+ let mut writing_mode = 0;
+ while writing_mode < WRITING_MODE_COUNT {
+ let mut direction = 0;
+ while direction < DIRECTION_COUNT {
+ if physical_longhand(property, writing_mode, direction) == property {
+ return false;
+ }
+ direction += 1;
+ }
+ writing_mode += 1;
+ }
+ true
+}
+
+/// As `map_logical_alias_to_physical`, for a longhand.
+const fn physical_longhand(property: u16, writing_mode: usize, direction: usize) -> u16 {
+ use crate::css::property_metadata::LOGICAL_ALIAS_TO_PHYSICAL;
+ use crate::css::style_compute::{DIRECTION_COUNT, WRITING_MODE_COUNT};
+ match LOGICAL_ALIAS_TO_PHYSICAL
+ [(longhand_index_of(property) * WRITING_MODE_COUNT + writing_mode) * DIRECTION_COUNT + direction]
+ {
+ 0 => property,
+ physical => physical,
+ }
+}
+
+/// The physical longhands `transition-property: all` names, per writing mode and direction, in the
+/// order the recursive expansion of `all` lists them, logical aliases mapped: a table the compiler
+/// computes from the property metadata.
+struct AllTransitionLonghands {
+ longhands: [[u16; ALL_TRANSITION_LONGHAND_COUNT];
+ crate::css::style_compute::WRITING_MODE_COUNT * crate::css::style_compute::DIRECTION_COUNT],
+}
+
+/// How many longhands the recursive expansion of `all` lists, a logical pair's longhands each once.
+const ALL_TRANSITION_LONGHAND_COUNT: usize =
+ all_transition_longhand_count(crate::css::property_metadata::property_id::ALL);
+
+const fn all_transition_longhand_count(property: u16) -> usize {
+ use crate::css::property_metadata::{
+ FIRST_SHORTHAND_PROPERTY_ID, LAST_SHORTHAND_PROPERTY_ID, SHORTHAND_EXPANSIONS, property_id,
+ };
+ if property >= FIRST_SHORTHAND_PROPERTY_ID && property <= LAST_SHORTHAND_PROPERTY_ID {
+ let longhands = SHORTHAND_EXPANSIONS[(property - FIRST_SHORTHAND_PROPERTY_ID) as usize];
+ let mut count = 0;
+ let mut index = 0;
+ while index < longhands.len() {
+ count += all_transition_longhand_count(longhands[index]);
+ index += 1;
+ }
+ return count;
+ }
+ (property != property_id::CUSTOM) as usize
+}
+
+impl AllTransitionLonghands {
+ const fn compute() -> Self {
+ use crate::css::style_compute::{DIRECTION_COUNT, WRITING_MODE_COUNT};
+ let mut longhands = [[0; ALL_TRANSITION_LONGHAND_COUNT]; WRITING_MODE_COUNT * DIRECTION_COUNT];
+ let mut writing_mode = 0;
+ while writing_mode < WRITING_MODE_COUNT {
+ let mut direction = 0;
+ while direction < DIRECTION_COUNT {
+ let row = &mut longhands[writing_mode * DIRECTION_COUNT + direction];
+ let written = Self::expand(
+ crate::css::property_metadata::property_id::ALL,
+ writing_mode,
+ direction,
+ row,
+ 0,
+ );
+ assert!(written == ALL_TRANSITION_LONGHAND_COUNT);
+ direction += 1;
+ }
+ writing_mode += 1;
+ }
+ Self { longhands }
+ }
+
+ /// Writes the physical longhands `property` names from `at` on, answering where it stopped.
+ const fn expand(
+ property: u16,
+ writing_mode: usize,
+ direction: usize,
+ row: &mut [u16; ALL_TRANSITION_LONGHAND_COUNT],
+ at: usize,
+ ) -> usize {
+ use crate::css::property_metadata::{
+ FIRST_SHORTHAND_PROPERTY_ID, LAST_SHORTHAND_PROPERTY_ID, SHORTHAND_EXPANSIONS, property_id,
+ };
+ if property >= FIRST_SHORTHAND_PROPERTY_ID && property <= LAST_SHORTHAND_PROPERTY_ID {
+ let longhands = SHORTHAND_EXPANSIONS[(property - FIRST_SHORTHAND_PROPERTY_ID) as usize];
+ let mut at = at;
+ let mut index = 0;
+ while index < longhands.len() {
+ at = Self::expand(longhands[index], writing_mode, direction, row, at);
+ index += 1;
+ }
+ return at;
+ }
+ if property == property_id::CUSTOM {
+ return at;
+ }
+ row[at] = physical_longhand(property, writing_mode, direction);
+ at + 1
+ }
+}
+
+const ALL_TRANSITION_LONGHANDS: AllTransitionLonghands = AllTransitionLonghands::compute();
+
+/// The physical longhands `transition-property: all` names under `writing_mode` and `direction`.
+pub(crate) fn all_transition_longhands(writing_mode: u8, direction: u8) -> &'static [u16] {
+ const TABLE: &AllTransitionLonghands = &ALL_TRANSITION_LONGHANDS;
+ &TABLE.longhands[usize::from(writing_mode) * crate::css::style_compute::DIRECTION_COUNT + usize::from(direction)]
+}
+
+/// The computed style groups each longhand reaches, a table the compiler computes from the property metadata.
+pub(crate) struct StyleGroupMasks {
+ /// Per longhand, the groups a change of its specified winner may change.
+ masks: [u32; LONGHAND_COUNT],
+ /// Per longhand, the group that owns its output.
+ output_masks: [u32; LONGHAND_COUNT],
+ /// The inherited longhands no group holds, which a child reads from its parent's table alone, in the first
+ /// `ungrouped_inherited_count` entries.
+ ungrouped_inherited: [u16; LONGHAND_COUNT],
+ ungrouped_inherited_count: usize,
+}
+
+/// The style groups each longhand reaches, computed as the engine is compiled.
+const STYLE_GROUP_MASKS: StyleGroupMasks = StyleGroupMasks::compute();
+
+impl StyleGroupMasks {
+ pub(crate) fn get() -> &'static Self {
+ &STYLE_GROUP_MASKS
+ }
+
+ const fn compute() -> Self {
+ use crate::css::property_metadata::property_id::{
+ CONTENT_VISIBILITY, DIRECTION, POSITION_ANCHOR, WRITING_MODE,
+ };
+ use crate::css::property_metadata::{
+ FIRST_INHERITED_PROPERTY_ID, FIRST_LONGHAND_PROPERTY_ID, LAST_INHERITED_PROPERTY_ID,
+ PROPERTY_STYLE_GROUP_INDICES,
+ };
+ use crate::css::style_compute::{DIRECTION_COUNT, WRITING_MODE_COUNT};
+
+ const fn group_mask(property: u16) -> u32 {
+ match PROPERTY_STYLE_GROUP_INDICES[(property - FIRST_LONGHAND_PROPERTY_ID) as usize] {
+ u8::MAX => 0,
+ group => 1 << group,
+ }
+ }
+ const fn physical(property: u16, writing_mode: usize, direction: usize) -> u16 {
+ physical_longhand(property, writing_mode, direction)
+ }
+ const fn index(property: u16) -> usize {
+ longhand_index_of(property)
+ }
+
+ let mut output_masks = [0; LONGHAND_COUNT];
+ let mut longhand = 0;
+ while longhand < LONGHAND_COUNT {
+ let property = FIRST_LONGHAND_PROPERTY_ID + longhand as u16;
+ if !is_logical_alias(property) {
+ output_masks[longhand] = group_mask(property);
+ }
+ longhand += 1;
+ }
+ let mut masks = output_masks;
+
+ // Direction and writing-mode select the physical winners for every logical property group.
+ // Those aliases own no payload, so they reach the groups of every physical property they
+ // map to.
+ let mut logical_mapping_mask = 0;
+ let mut longhand = 0;
+ while longhand < LONGHAND_COUNT {
+ let property = FIRST_LONGHAND_PROPERTY_ID + longhand as u16;
+ if is_logical_alias(property) {
+ let mut alias_mask = 0;
+ let mut writing_mode = 0;
+ while writing_mode < WRITING_MODE_COUNT {
+ let mut direction = 0;
+ while direction < DIRECTION_COUNT {
+ alias_mask |= group_mask(physical(property, writing_mode, direction));
+ direction += 1;
+ }
+ writing_mode += 1;
+ }
+ masks[longhand] |= alias_mask;
+ logical_mapping_mask |= alias_mask;
+ }
+ longhand += 1;
+ }
+ masks[index(DIRECTION)] |= logical_mapping_mask;
+ masks[index(WRITING_MODE)] |= logical_mapping_mask;
+ // NB: The box group holds the used containment flags implied by hidden content visibility.
+ masks[index(CONTENT_VISIBILITY)] |= 1 << crate::css::table_group_builder::group_index::BOX;
+ // NB: The surround group holds whether the element names a default anchor, which layout reads beside the
+ // anchor group's name.
+ masks[index(POSITION_ANCHOR)] |= 1 << crate::css::table_group_builder::group_index::SURROUND;
+ // NB: The misc layout group holds whether an author declaration disables native appearance, which these
+ // properties' winners decide.
+ let disabling = crate::css::style_compute::PROPERTIES_DISABLING_NATIVE_APPEARANCE;
+ let mut disabling_index = 0;
+ while disabling_index < disabling.len() {
+ masks[index(disabling[disabling_index])] |= 1 << crate::css::table_group_builder::group_index::MISC_LAYOUT;
+ disabling_index += 1;
+ }
+
+ let mut ungrouped_inherited = [0; LONGHAND_COUNT];
+ let mut ungrouped_inherited_count = 0;
+ let mut longhand = 0;
+ while longhand < LONGHAND_COUNT {
+ let property = FIRST_LONGHAND_PROPERTY_ID + longhand as u16;
+ if property >= FIRST_INHERITED_PROPERTY_ID
+ && property <= LAST_INHERITED_PROPERTY_ID
+ && !is_logical_alias(property)
+ && (masks[longhand] == 0 || StyleBitField::of(property).is_some())
+ {
+ ungrouped_inherited[ungrouped_inherited_count] = property;
+ ungrouped_inherited_count += 1;
+ }
+ longhand += 1;
+ }
+ Self {
+ masks,
+ output_masks,
+ ungrouped_inherited,
+ ungrouped_inherited_count,
+ }
+ }
+
+ /// The inherited longhands no group holds, which a child reads from its parent's table alone.
+ pub(crate) fn ungrouped_inherited(&self) -> &[u16] {
+ &self.ungrouped_inherited[..self.ungrouped_inherited_count]
+ }
+
+ fn longhand_index(property: u16) -> Option<usize> {
+ use crate::css::property_metadata::FIRST_LONGHAND_PROPERTY_ID;
+ property.checked_sub(FIRST_LONGHAND_PROPERTY_ID).map(usize::from)
+ }
+
+ /// The computed style groups which may change when `property`'s specified winner changes; none
+ /// for a longhand that feeds no group of its own.
+ pub(crate) fn dependencies(&self, property: u16) -> u32 {
+ Self::longhand_index(property)
+ .and_then(|index| self.masks.get(index))
+ .copied()
+ .unwrap_or(0)
+ }
+}
+
+/// The computed style group which directly owns one longhand's output.
+pub(crate) fn computed_group_output_mask(property: u16) -> Option<u32> {
+ let masks = StyleGroupMasks::get();
+ StyleGroupMasks::longhand_index(property)
+ .and_then(|index| masks.output_masks.get(index))
+ .copied()
+ .filter(|mask| *mask != 0)
+}
+
+/// The most computed values one group holds, so that a read names each of a group's values by one bit.
+pub(crate) const MAX_GROUP_VALUES: usize = 64;
+
+/// A longhand property, by its id.
+#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
+pub(crate) struct LonghandID(u16);
+
+impl LonghandID {
+ pub(crate) const fn new(property: u16) -> Self {
+ use crate::css::property_metadata::{FIRST_LONGHAND_PROPERTY_ID, LAST_LONGHAND_PROPERTY_ID};
+ assert!(property >= FIRST_LONGHAND_PROPERTY_ID && property <= LAST_LONGHAND_PROPERTY_ID);
+ Self(property)
+ }
+
+ pub(crate) const fn property(self) -> u16 {
+ self.0
+ }
+
+ const fn index(self) -> usize {
+ (self.0 - crate::css::property_metadata::FIRST_LONGHAND_PROPERTY_ID) as usize
+ }
+}
+
+/// The words of bits a style holds beside its groups.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+enum BitWord {
+ /// The inherited bits beside the inherited set's groups.
+ Inherited,
+ /// The reset bits in the style's root.
+ Reset,
+}
+
+/// Declares the fields of the bits a style holds beside its groups: each field's word, its
+/// longhand, the CSS enum its codes are of, the code of its initial value, the mapping of keywords
+/// to codes, and the shift and width the C++ readers read it at.
+macro_rules! style_bit_fields {
+ ($($word:ident $field:ident: $property:ident, $enumeration:ident::$initial:ident, $code_of:ident, $shift:ident, $width:ident;)+) => {
+ /// One field of the bits a style holds beside its groups.
+ #[derive(Clone, Copy, PartialEq, Eq, Debug)]
+ pub(crate) enum StyleBitField {
+ $($field,)+
+ }
+
+ impl StyleBitField {
+ const ALL: &[Self] = &[$(Self::$field,)+];
+
+ /// The word of bits holding the field.
+ const fn word(self) -> BitWord {
+ match self {
+ $(Self::$field => BitWord::$word,)+
+ }
+ }
+
+ /// The field holding `property`'s value, where the bits hold it.
+ pub(crate) const fn of(property: u16) -> Option<Self> {
+ match property {
+ $(crate::css::property_metadata::property_id::$property => Some(Self::$field),)+
+ _ => None,
+ }
+ }
+
+ /// The longhand the field holds.
+ const fn property(self) -> u16 {
+ match self {
+ $(Self::$field => crate::css::property_metadata::property_id::$property,)+
+ }
+ }
+
+ const fn shift(self) -> u32 {
+ match self {
+ $(Self::$field => crate::css::computed_value_types::$shift,)+
+ }
+ }
+
+ const fn width(self) -> u32 {
+ match self {
+ $(Self::$field => crate::css::computed_value_types::$width,)+
+ }
+ }
+
+ /// The code of the field's initial value.
+ const fn initial(self) -> u8 {
+ match self {
+ $(Self::$field => crate::css::css_enums::$enumeration::$initial,)+
+ }
+ }
+
+ /// The keyword of each code the field holds, by code.
+ const fn keywords(self) -> &'static [u16] {
+ match self {
+ $(Self::$field => &crate::css::css_enums::$enumeration::KEYWORDS,)+
+ }
+ }
+
+ /// The code of `keyword` in the field's enum.
+ fn code_of(self, keyword: u16) -> Option<u8> {
+ match self {
+ $(Self::$field => crate::css::css_enums::$code_of(keyword),)+
+ }
+ }
+ }
+ };
+}
+
+style_bit_fields! {
+ Inherited WritingMode: WRITING_MODE, writing_mode::HORIZONTAL_TB, keyword_to_writing_mode,
+ INHERITED_BITS_WRITING_MODE_SHIFT, INHERITED_BITS_WRITING_MODE_WIDTH;
+ Inherited Direction: DIRECTION, direction::LTR, keyword_to_direction,
+ INHERITED_BITS_DIRECTION_SHIFT, INHERITED_BITS_DIRECTION_WIDTH;
+ Inherited Visibility: VISIBILITY, visibility::VISIBLE, keyword_to_visibility,
+ INHERITED_BITS_VISIBILITY_SHIFT, INHERITED_BITS_VISIBILITY_WIDTH;
+ Inherited TextOrientation: TEXT_ORIENTATION, text_orientation::MIXED, keyword_to_text_orientation,
+ INHERITED_BITS_TEXT_ORIENTATION_SHIFT, INHERITED_BITS_TEXT_ORIENTATION_WIDTH;
+ Inherited PointerEvents: POINTER_EVENTS, pointer_events::AUTO, keyword_to_pointer_events,
+ INHERITED_BITS_POINTER_EVENTS_SHIFT, INHERITED_BITS_POINTER_EVENTS_WIDTH;
+ Inherited ListStylePosition: LIST_STYLE_POSITION, list_style_position::OUTSIDE, keyword_to_list_style_position,
+ INHERITED_BITS_LIST_STYLE_POSITION_SHIFT, INHERITED_BITS_LIST_STYLE_POSITION_WIDTH;
+ Inherited BorderCollapse: BORDER_COLLAPSE, border_collapse::SEPARATE, keyword_to_border_collapse,
+ INHERITED_BITS_BORDER_COLLAPSE_SHIFT, INHERITED_BITS_BORDER_COLLAPSE_WIDTH;
+ Inherited CaptionSide: CAPTION_SIDE, caption_side::TOP, keyword_to_caption_side,
+ INHERITED_BITS_CAPTION_SIDE_SHIFT, INHERITED_BITS_CAPTION_SIDE_WIDTH;
+ Inherited EmptyCells: EMPTY_CELLS, empty_cells::SHOW, keyword_to_empty_cells,
+ INHERITED_BITS_EMPTY_CELLS_SHIFT, INHERITED_BITS_EMPTY_CELLS_WIDTH;
+ Inherited TextAlign: TEXT_ALIGN, text_align::START, keyword_to_text_align,
+ INHERITED_BITS_TEXT_ALIGN_SHIFT, INHERITED_BITS_TEXT_ALIGN_WIDTH;
+ Inherited WhiteSpaceCollapse: WHITE_SPACE_COLLAPSE, white_space_collapse::COLLAPSE, keyword_to_white_space_collapse,
+ INHERITED_BITS_WHITE_SPACE_COLLAPSE_SHIFT, INHERITED_BITS_WHITE_SPACE_COLLAPSE_WIDTH;
+ Inherited TextWrapMode: TEXT_WRAP_MODE, text_wrap_mode::WRAP, keyword_to_text_wrap_mode,
+ INHERITED_BITS_TEXT_WRAP_MODE_SHIFT, INHERITED_BITS_TEXT_WRAP_MODE_WIDTH;
+ Inherited WordBreak: WORD_BREAK, word_break::NORMAL, keyword_to_word_break,
+ INHERITED_BITS_WORD_BREAK_SHIFT, INHERITED_BITS_WORD_BREAK_WIDTH;
+ Reset Position: POSITION, positioning::STATIC, keyword_to_positioning,
+ RESET_BITS_POSITION_SHIFT, RESET_BITS_POSITION_WIDTH;
+ Reset Float: FLOAT, float::NONE, keyword_to_float,
+ RESET_BITS_FLOAT_SHIFT, RESET_BITS_FLOAT_WIDTH;
+ Reset Clear: CLEAR, clear::NONE, keyword_to_clear,
+ RESET_BITS_CLEAR_SHIFT, RESET_BITS_CLEAR_WIDTH;
+ Reset OverflowX: OVERFLOW_X, overflow::VISIBLE, keyword_to_overflow,
+ RESET_BITS_OVERFLOW_X_SHIFT, RESET_BITS_OVERFLOW_X_WIDTH;
+ Reset OverflowY: OVERFLOW_Y, overflow::VISIBLE, keyword_to_overflow,
+ RESET_BITS_OVERFLOW_Y_SHIFT, RESET_BITS_OVERFLOW_Y_WIDTH;
+ Reset BoxSizing: BOX_SIZING, box_sizing::CONTENT_BOX, keyword_to_box_sizing,
+ RESET_BITS_BOX_SIZING_SHIFT, RESET_BITS_BOX_SIZING_WIDTH;
+ Reset UnicodeBidi: UNICODE_BIDI, unicode_bidi::NORMAL, keyword_to_unicode_bidi,
+ RESET_BITS_UNICODE_BIDI_SHIFT, RESET_BITS_UNICODE_BIDI_WIDTH;
+ Reset TableLayout: TABLE_LAYOUT, table_layout::AUTO, keyword_to_table_layout,
+ RESET_BITS_TABLE_LAYOUT_SHIFT, RESET_BITS_TABLE_LAYOUT_WIDTH;
+}
+
+impl StyleBitField {
+ const fn from_index(index: u8) -> Self {
+ Self::ALL[index as usize]
+ }
+}
+
+// NB: Each field's codes fit its width, and the fields of a word do not overlap.
+const _: () = {
+ let mut field = 0;
+ let mut taken = [0_u32; 2];
+ while field < StyleBitField::ALL.len() {
+ let bits = StyleBitField::ALL[field];
+ assert!(bits.keywords().len() <= 1 << bits.width());
+ let mask = ((1 << bits.width()) - 1) << bits.shift();
+ let word = bits.word() as usize;
+ assert!(taken[word] & mask == 0);
+ taken[word] |= mask;
+ field += 1;
+ }
+};
+
+/// The codes of one word of bits a style holds beside its groups, by field.
+macro_rules! impl_bit_word {
+ ($bits:ident, $word:ident) => {
+ impl crate::css::computed_value_types::$bits {
+ /// The bits of the initial values.
+ pub(crate) const INITIAL: Self = {
+ let mut bits = Self(0);
+ let mut field = 0;
+ while field < StyleBitField::ALL.len() {
+ let field_at = StyleBitField::ALL[field];
+ if matches!(field_at.word(), BitWord::$word) {
+ bits = bits.with(field_at, field_at.initial());
+ }
+ field += 1;
+ }
+ bits
+ };
+
+ /// The code `field`, a field of these bits, holds.
+ pub(crate) const fn get(self, field: StyleBitField) -> u8 {
+ assert!(matches!(field.word(), BitWord::$word));
+ ((self.0 >> field.shift()) & ((1 << field.width()) - 1)) as u8
+ }
+
+ /// These bits, with `code` in `field`, a field of them.
+ pub(crate) const fn with(self, field: StyleBitField, code: u8) -> Self {
+ assert!(matches!(field.word(), BitWord::$word));
+ let mask = ((1 << field.width()) - 1) << field.shift();
+ Self((self.0 & !mask) | ((code as u32) << field.shift() & mask))
+ }
+ }
+ };
+}
+
+impl_bit_word!(InheritedBits, Inherited);
+impl_bit_word!(ResetBits, Reset);
+
+impl crate::css::computed_value_types::InheritedBits {
+ pub(crate) fn writing_mode(self) -> u8 {
+ self.get(StyleBitField::WritingMode)
+ }
+
+ pub(crate) fn direction(self) -> u8 {
+ self.get(StyleBitField::Direction)
+ }
+}
+
+impl crate::css::computed_value_types::InheritedSetValues {
+ /// The values of the initial style.
+ pub(crate) const INITIAL: Self = Self {
+ bits: crate::css::computed_value_types::InheritedBits::INITIAL,
+ effective_zoom_bits: 0x3f80_0000,
+ };
+
+ /// https://drafts.csswg.org/css-viewport/#effective-zoom
+ pub(crate) fn effective_zoom(&self) -> f32 {
+ f32::from_bits(self.effective_zoom_bits)
+ }
+}
+
+impl crate::css::computed_value_types::StyleBits {
+ /// The bits of the initial style.
+ pub(crate) const INITIAL: Self = Self {
+ inherited: InheritedSetValues::INITIAL,
+ reset: crate::css::computed_value_types::ResetBits::INITIAL,
+ };
+
+ /// The code `field` holds.
+ pub(crate) const fn get(&self, field: StyleBitField) -> u8 {
+ match field.word() {
+ BitWord::Inherited => self.inherited.bits.get(field),
+ BitWord::Reset => self.reset.get(field),
+ }
+ }
+
+ /// These bits, with `code` in `field`.
+ pub(crate) const fn with(mut self, field: StyleBitField, code: u8) -> Self {
+ match field.word() {
+ BitWord::Inherited => self.inherited.bits = self.inherited.bits.with(field, code),
+ BitWord::Reset => self.reset = self.reset.with(field, code),
+ }
+ self
+ }
+
+ /// The computed value `field` holds: its keyword, as the shared keyword values hold it.
+ pub(crate) fn value(&self, field: StyleBitField) -> &'static RetainedStyleValueData {
+ RetainedStyleValueData::shared_keyword(field.keywords()[usize::from(self.get(field))])
+ }
+
+ /// These bits, with the code of `value`, a computed keyword of `field`'s enum, in `field`.
+ pub(crate) fn with_value(self, field: StyleBitField, value: &RetainedStyleValueData) -> Self {
+ match value.optional_data() {
+ Some(StyleValueData::Keyword { keyword }) => self.with(
+ field,
+ field.code_of(*keyword).expect("a computed keyword of the field's enum"),
+ ),
+ _ => panic!("a computed value held as bits is a keyword"),
+ }
+ }
+
+ /// The bits of a style whose longhands `value_of` answers, with `effective_zoom`.
+ pub(crate) fn of_values<'v>(value_of: impl Fn(u16) -> &'v RetainedStyleValueData, effective_zoom: f32) -> Self {
+ let bits = StyleBitField::ALL.iter().fold(Self::INITIAL, |bits, &field| {
+ let value = value_of(field.property());
+ match value.optional_data() {
+ Some(_) => bits.with_value(field, value),
+ None => bits,
+ }
+ });
+ Self {
+ inherited: InheritedSetValues {
+ effective_zoom_bits: effective_zoom.to_bits(),
+ ..bits.inherited
+ },
+ ..bits
+ }
+ }
+}
+
+/// Where one longhand's computed value lives: in the allocation of the computed-value group
+/// holding it, at its index among the group's values, in a handle of the group's payload that
+/// holds the computed value itself, or in the inherited bits beside the style's inherited groups.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub(crate) struct LonghandPlace {
+ group: u8,
+ index: u8,
+ /// The offset of the payload handle holding the value, or zero where the group's values hold
+ /// it.
+ handle: u16,
+}
+
+const _: () = assert!(size_of::<LonghandPlace>() == 4);
+
+impl LonghandPlace {
+ /// The place of a longhand holding no value of its own.
+ const NONE: Self = Self {
+ group: u8::MAX,
+ index: 0,
+ handle: 0,
+ };
+
+ /// The offset of the payload handle holding the value, where one does.
+ pub(crate) fn handle_offset(self) -> Option<usize> {
+ (self.handle != 0).then_some(usize::from(self.handle))
+ }
+
+ /// The value at this place of `payload`, a live payload of the group whose values are
+ /// `values`.
+ ///
+ /// # Safety
+ /// `payload` must be a live payload of the place's group, holding `values`, live for `'a`.
+ unsafe fn value_in(self, payload: *const c_void, values: &[RetainedStyleValueData]) -> &RetainedStyleValueData {
+ match self.handle_offset() {
+ // SAFETY: The handle is a `ComputedStyleValueHandle`, a single retained pointer laid out
+ // as a `RetainedStyleValueData` is, which the payload keeps live.
+ Some(offset) => unsafe { &*payload.byte_add(offset).cast::<RetainedStyleValueData>() },
+ None => &values[self.index()],
+ }
+ }
+
+ /// The place of a longhand the inherited bits hold, in `field`.
+ const fn bits(field: StyleBitField) -> Self {
+ Self {
+ group: Self::BITS_GROUP,
+ index: field as u8,
+ handle: 0,
+ }
+ }
+
+ /// The `group` of a place in the inherited bits.
+ const BITS_GROUP: u8 = u8::MAX - 1;
+
+ /// The field of the inherited bits holding the value, where those hold it.
+ pub(crate) fn bit_field(self) -> Option<StyleBitField> {
+ (self.group == Self::BITS_GROUP).then(|| StyleBitField::from_index(self.index))
+ }
+
+ /// The group holding the value, which a place in the inherited bits has none of.
+ pub(crate) fn group(self) -> usize {
+ assert!(self.group != Self::BITS_GROUP, "the inherited bits are in no group");
+ usize::from(self.group)
+ }
+
+ pub(crate) fn index(self) -> usize {
+ usize::from(self.index)
+ }
+}
+
+/// The values a group's build reads, of each group, one bit per value index.
+pub(crate) type GroupReads = [u64; group_index::COUNT];
+
+/// The longhands whose computed value a handle of their group's payload holds as it is, by the
+/// handle's offset: the group's values keep no second copy of them.
+const PAYLOAD_HANDLE_LONGHANDS: [(u16, usize, usize); 19] = {
+ use crate::css::computed_value_types::FontValues;
+ use crate::css::property_metadata::property_id as p;
+ use std::mem::offset_of;
+ let font = group_index::FONT;
+ [
+ (p::FONT_FAMILY, font, offset_of!(FontValues, font_family)),
+ (p::FONT_STYLE, font, offset_of!(FontValues, font_style)),
+ (
+ p::FONT_OPTICAL_SIZING,
+ font,
+ offset_of!(FontValues, font_optical_sizing),
+ ),
+ (
+ p::FONT_FEATURE_SETTINGS,
+ font,
+ offset_of!(FontValues, font_feature_settings),
+ ),
+ (p::FONT_KERNING, font, offset_of!(FontValues, font_kerning)),
+ (
+ p::FONT_LANGUAGE_OVERRIDE,
+ font,
+ offset_of!(FontValues, font_language_override),
+ ),
+ (
+ p::FONT_VARIANT_ALTERNATES,
+ font,
+ offset_of!(FontValues, font_variant_alternates),
+ ),
+ (p::FONT_VARIANT_CAPS, font, offset_of!(FontValues, font_variant_caps)),
+ (
+ p::FONT_VARIANT_EAST_ASIAN,
+ font,
+ offset_of!(FontValues, font_variant_east_asian),
+ ),
+ (
+ p::FONT_VARIANT_LIGATURES,
+ font,
+ offset_of!(FontValues, font_variant_ligatures),
+ ),
+ (
+ p::FONT_VARIANT_NUMERIC,
+ font,
+ offset_of!(FontValues, font_variant_numeric),
+ ),
+ (
+ p::FONT_VARIANT_POSITION,
+ font,
+ offset_of!(FontValues, font_variant_position),
+ ),
+ (
+ p::FONT_VARIATION_SETTINGS,
+ font,
+ offset_of!(FontValues, font_variation_settings),
+ ),
+ (p::TEXT_RENDERING, font, offset_of!(FontValues, text_rendering)),
+ (p::LINE_HEIGHT, font, offset_of!(FontValues, line_height)),
+ (p::MATH_SHIFT, font, offset_of!(FontValues, math_shift_value)),
+ (p::MATH_STYLE, font, offset_of!(FontValues, math_style_value)),
+ (p::MATH_DEPTH, font, offset_of!(FontValues, math_depth_value)),
+ (p::FONT_SIZE, font, offset_of!(FontValues, font_size_value)),
+ ]
+};
+
+const _: () = assert!(
+ size_of::<crate::css::computed_value_types::ComputedStyleValueHandle>() == size_of::<RetainedStyleValueData>()
+);
+
+/// Where each longhand's computed value lives among an element's groups, and which of them each
+/// group's build reads, computed as the engine is compiled.
+///
+/// A longhand's value lives in the group owning its output. A logical alias's lives in the group
+/// of the physical longhand it maps to in a horizontal, left-to-right flow, and the value of a
+/// longhand no group owns lives in the font group where it inherits, as the font longhands do, or
+/// in the box group where it does not. A group's values then inherit or not as its payload does.
+pub(crate) struct GroupValueLayout {
+ places: [LonghandPlace; LONGHAND_COUNT],
+ counts: [u8; group_index::COUNT],
+ longhands: [[u16; MAX_GROUP_VALUES]; group_index::COUNT],
+ /// Per group, the values its build reads: those of the longhands whose changes may change it,
+ /// but for logical aliases, and all of its own. The longhands whose changes feed no group are
+ /// read by the font group's build.
+ reads: [GroupReads; group_index::COUNT],
+}
+
+const GROUP_VALUE_LAYOUT: GroupValueLayout = GroupValueLayout::compute();
+
+impl GroupValueLayout {
+ pub(crate) fn get() -> &'static Self {
+ &GROUP_VALUE_LAYOUT
+ }
+
+ const fn compute() -> Self {
+ use crate::css::property_metadata::{
+ FIRST_INHERITED_PROPERTY_ID, FIRST_LONGHAND_PROPERTY_ID, LAST_INHERITED_PROPERTY_ID,
+ };
+ const fn home(property: u16) -> usize {
+ let masks = &STYLE_GROUP_MASKS;
+ let output = masks.output_masks[longhand_index_of(property)];
+ if output != 0 {
+ return output.trailing_zeros() as usize;
+ }
+ if is_logical_alias(property) {
+ let physical = masks.output_masks[longhand_index_of(physical_longhand(property, 0, 0))];
+ if physical != 0 {
+ return physical.trailing_zeros() as usize;
+ }
+ }
+ match property >= FIRST_INHERITED_PROPERTY_ID && property <= LAST_INHERITED_PROPERTY_ID {
+ true => group_index::FONT,
+ false => group_index::BOX,
+ }
+ }
+
+ let mut places = [LonghandPlace {
+ group: 0,
+ index: 0,
+ handle: 0,
+ }; LONGHAND_COUNT];
+ let mut counts = [0_u8; group_index::COUNT];
+ let mut longhands = [[0_u16; MAX_GROUP_VALUES]; group_index::COUNT];
+ let mut longhand = 0;
+ while longhand < LONGHAND_COUNT {
+ let property = FIRST_LONGHAND_PROPERTY_ID + longhand as u16;
+ if maps_in_every_flow(property) {
+ places[longhand] = LonghandPlace::NONE;
+ longhand += 1;
+ continue;
+ }
+ if let Some(field) = StyleBitField::of(property) {
+ places[longhand] = LonghandPlace::bits(field);
+ longhand += 1;
+ continue;
+ }
+ let group = home(property);
+ let mut handle = 0;
+ while handle < PAYLOAD_HANDLE_LONGHANDS.len() {
+ let (handle_property, handle_group, offset) = PAYLOAD_HANDLE_LONGHANDS[handle];
+ if handle_property == property {
+ assert!(handle_group == group, "a payload handle holds a longhand of its group");
+ assert!(offset != 0 && offset <= u16::MAX as usize);
+ break;
+ }
+ handle += 1;
+ }
+ if handle < PAYLOAD_HANDLE_LONGHANDS.len() {
+ places[longhand] = LonghandPlace {
+ group: group as u8,
+ index: u8::MAX,
+ handle: PAYLOAD_HANDLE_LONGHANDS[handle].2 as u16,
+ };
+ longhand += 1;
+ continue;
+ }
+ let index = counts[group] as usize;
+ assert!(
+ index < MAX_GROUP_VALUES,
+ "a group holds no more values than a read names"
+ );
+ longhands[group][index] = property;
+ places[longhand] = LonghandPlace {
+ group: group as u8,
+ index: index as u8,
+ handle: 0,
+ };
+ counts[group] += 1;
+ longhand += 1;
+ }
+
+ let mut reads = [[0_u64; group_index::COUNT]; group_index::COUNT];
+ let mut longhand = 0;
+ while longhand < LONGHAND_COUNT {
+ let property = FIRST_LONGHAND_PROPERTY_ID + longhand as u16;
+ let place = places[longhand];
+ // NB: No group's build reads the inherited bits: they are no group's values.
+ if place.group == LonghandPlace::NONE.group || place.group == LonghandPlace::BITS_GROUP {
+ longhand += 1;
+ continue;
+ }
+ // NB: A build reading a value a payload handle holds keys on the group holding it, as
+ // a build reading the group's values does: see `GroupValues::read_hash`.
+ if place.handle != 0 {
+ longhand += 1;
+ continue;
+ }
+ let read_by = match STYLE_GROUP_MASKS.masks[longhand] {
+ _ if is_logical_alias(property) => 0,
+ 0 => 1 << group_index::FONT,
+ groups => groups,
+ } | (1 << place.group);
+ let mut group = 0;
+ while group < group_index::COUNT {
+ if read_by & (1 << group) != 0 {
+ reads[group][place.group as usize] |= 1 << place.index;
+ }
+ group += 1;
+ }
+ longhand += 1;
+ }
+ let mut handle = 0;
+ while handle < PAYLOAD_HANDLE_LONGHANDS.len() {
+ let (property, group, _) = PAYLOAD_HANDLE_LONGHANDS[handle];
+ let read_by = match STYLE_GROUP_MASKS.masks[longhand_index_of(property)] {
+ 0 => 1 << group_index::FONT,
+ groups => groups,
+ } | (1 << group);
+ let mut reader = 0;
+ while reader < group_index::COUNT {
+ assert!(
+ read_by & (1 << reader) == 0 || reads[reader][group] != 0,
+ "a build reading a payload handle's value reads a value of its group"
+ );
+ reader += 1;
+ }
+ handle += 1;
+ }
+ Self {
+ places,
+ counts,
+ longhands,
+ reads,
+ }
+ }
+
+ /// The longhands that inherit by default.
+ pub(crate) fn inherited_longhands() -> impl Iterator<Item = u16> {
+ use crate::css::property_metadata::{FIRST_INHERITED_PROPERTY_ID, LAST_INHERITED_PROPERTY_ID};
+ (FIRST_INHERITED_PROPERTY_ID..=LAST_INHERITED_PROPERTY_ID).filter(|&property| !is_logical_alias(property))
+ }
+
+ /// Where the computed value of `longhand` lives. A logical alias mapping to a physical
+ /// longhand in every flow holds no value of its own: see [`Self::resolved`].
+ pub(crate) fn place(&self, longhand: LonghandID) -> LonghandPlace {
+ self.places[longhand.index()]
+ }
+
+ /// Whether `longhand` holds a value of its own, which a logical alias mapping to a physical
+ /// longhand in every flow does not.
+ pub(crate) fn holds_value(&self, longhand: LonghandID) -> bool {
+ self.places[longhand.index()] != LonghandPlace::NONE
+ }
+
+ /// The longhand whose value is the computed value of `property`, among values `value_of`
+ /// answers: `property` itself, or for a logical alias holding no value of its own, the
+ /// physical longhand it maps to in the flow of the writing mode and direction those values
+ /// hold. https://drafts.csswg.org/css-logical/#box
+ /// NB: A logical alias computes as the physical longhand it maps to, so its value is that
+ /// longhand's, held once.
+ pub(crate) fn resolved<'v>(&self, property: u16, value_of: impl Fn(u16) -> &'v RetainedStyleValueData) -> u16 {
+ use crate::css::property_metadata::property_id;
+ if self.holds_value(LonghandID::new(property)) {
+ return property;
+ }
+ let (writing_mode, direction) = match (
+ value_of(property_id::WRITING_MODE).optional_data(),
+ value_of(property_id::DIRECTION).optional_data(),
+ ) {
+ (Some(_), Some(_)) => crate::css::style_compute::writing_mode_and_direction_of(
+ Some(value_of(property_id::WRITING_MODE)),
+ Some(value_of(property_id::DIRECTION)),
+ ),
+ _ => (0, 0),
+ };
+ crate::css::style_compute::map_logical_alias_to_physical(property, writing_mode, direction)
+ }
+
+ fn place_of(&self, property: u16) -> LonghandPlace {
+ self.place(LonghandID::new(property))
+ }
+
+ /// The longhands whose values `group` holds, in order.
+ pub(crate) fn longhands_of(&self, group: usize) -> &[u16] {
+ &self.longhands[group][..usize::from(self.counts[group])]
+ }
+
+ /// The values the build of `group` may read.
+ pub(crate) fn reads_of(&self, group: usize) -> &GroupReads {
+ &self.reads[group]
+ }
+
+ /// Whether a build reading `reads` reads the value at `place`.
+ pub(crate) fn reads(reads: &GroupReads, place: LonghandPlace) -> bool {
+ place != LonghandPlace::NONE
+ && place.bit_field().is_none()
+ && match place.handle_offset() {
+ Some(_) => reads[place.group()] != 0,
+ None => reads[place.group()] & (1 << place.index) != 0,
+ }
+ }
+
+ /// The places of the payload handles holding values of `group`.
+ pub(crate) fn handles_of(group: usize) -> impl Iterator<Item = (u16, LonghandPlace)> {
+ PAYLOAD_HANDLE_LONGHANDS
+ .iter()
+ .filter(move |(_, handle_group, _)| *handle_group == group)
+ .map(|&(property, _, _)| (property, GROUP_VALUE_LAYOUT.place_of(property)))
+ }
+}
+
+/// The recorded specified value of a longhand whose computed value depends on what the element
+/// inherits.
+#[derive(Clone)]
+pub(crate) struct InheritanceDependentValue {
+ property: u16,
+ value: RetainedStyleValueData,
+ /// Whether a group build reads the value in place of the computed value, as it does for a
+ /// currentcolor-dependent value of a longhand a drive did not evaluate.
+ read_by_groups: bool,
+}
+
+impl crate::heap_size::HeapSize for InheritanceDependentValue {
+ fn heap_size(&self, sizer: &mut crate::heap_size::HeapSizer) -> usize {
+ self.value.heap_size(sizer)
+ }
+}
+
+/// What an element's groups are built from beside their computed values: the recorded specified
+/// values of the longhands whose computed values depend on what the element inherits, its zoom,
+/// its display before the box type transformation, and its color scheme.
+#[derive(Clone)]
+pub(crate) struct GroupValueFacts {
+ inheritance_dependent_values: Option<std::sync::Arc<[InheritanceDependentValue]>>,
+ effective_zoom: f32,
+ display_before_box_type_transformation: u32,
+ effective_color_scheme: i16,
+ /// https://drafts.csswg.org/css-ui/#appearance-disabling-properties
+ /// Whether an author declaration disables the element's native appearance.
+ native_appearance_disabled: bool,
+}
+
+impl crate::heap_size::HeapSize for GroupValueFacts {
+ fn heap_size(&self, sizer: &mut crate::heap_size::HeapSizer) -> usize {
+ self.inheritance_dependent_values.heap_size(sizer)
+ }
+}
+
+impl GroupValueFacts {
+ /// The facts of no values: no recorded specified values, no zoom, no display before the box
+ /// type transformation and no color scheme.
+ pub(crate) fn empty() -> Self {
+ Self {
+ inheritance_dependent_values: None,
+ effective_zoom: 1.0,
+ display_before_box_type_transformation: 0,
+ effective_color_scheme: -1,
+ native_appearance_disabled: false,
+ }
+ }
+
+ /// 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, &RetainedStyleValueData)> + Clone {
+ self.inheritance_dependent_values
+ .iter()
+ .flat_map(|values| values.iter())
+ .map(|held| (held.property, &held.value))
+ }
+
+ /// The recorded value a group build reads for `property` in place of its computed value: its
+ /// currentcolor-dependent specified value where a drive did not evaluate it.
+ pub(crate) fn value_read_in_place(&self, property: u16) -> Option<&RetainedStyleValueData> {
+ self.inheritance_dependent_values
+ .as_deref()?
+ .iter()
+ .find(|held| held.property == property && held.read_by_groups)
+ .map(|held| &held.value)
+ }
+
+ /// The recorded values a group build reading `reads` reads in place of computed values.
+ pub(crate) fn values_read_in_place<'a>(
+ &'a self,
+ reads: &'a GroupReads,
+ ) -> impl Iterator<Item = (u16, &'a RetainedStyleValueData)> + 'a {
+ self.inheritance_dependent_values
+ .iter()
+ .flat_map(|values| values.iter())
+ .filter(move |held| {
+ held.read_by_groups && GroupValueLayout::reads(reads, GROUP_VALUE_LAYOUT.place_of(held.property))
+ })
+ .map(|held| (held.property, &held.value))
+ }
+
+ pub(crate) fn effective_zoom(&self) -> f32 {
+ self.effective_zoom
+ }
+
+ pub(crate) fn display_before_box_type_transformation(&self) -> u32 {
+ self.display_before_box_type_transformation
+ }
+
+ pub(crate) fn effective_color_scheme(&self) -> i16 {
+ self.effective_color_scheme
+ }
+
+ pub(crate) fn native_appearance_disabled(&self) -> bool {
+ self.native_appearance_disabled
+ }
+
+ /// Whether these and `other` publish the same recorded specified values, zoom, box display
+ /// and color scheme.
+ pub(crate) fn publication_equals(&self, other: &Self) -> bool {
+ use crate::css::style_value::retained_style_values_equal;
+ let (mine, theirs) = (
+ self.inheritance_dependent_values.as_deref().unwrap_or_default(),
+ other.inheritance_dependent_values.as_deref().unwrap_or_default(),
+ );
+ self.effective_zoom.to_bits() == other.effective_zoom.to_bits()
+ && self.display_before_box_type_transformation == other.display_before_box_type_transformation
+ && self.effective_color_scheme == other.effective_color_scheme
+ && self.native_appearance_disabled == other.native_appearance_disabled
+ && mine.len() == theirs.len()
+ && mine.iter().all(|held| {
+ theirs
+ .iter()
+ .find(|other| other.property == held.property)
+ .is_some_and(|other| retained_style_values_equal(&held.value, &other.value))
+ })
+ }
+
+ /// What these and `other` hold differently, if anything.
+ pub(crate) fn difference(&self, other: &Self) -> Option<String> {
+ let recorded = |facts: &Self| {
+ let mut values: Vec<_> = facts
+ .inheritance_dependent_values
+ .iter()
+ .flat_map(|values| values.iter())
+ .map(|held| (held.property, held.value.pointer() as usize, held.read_by_groups))
+ .collect();
+ values.sort_unstable();
+ values
+ };
+ if recorded(self) != recorded(other) {
+ return Some("the recorded specified values".into());
+ }
+ if self.effective_zoom.to_bits() != other.effective_zoom.to_bits()
+ || self.display_before_box_type_transformation != other.display_before_box_type_transformation
+ || self.effective_color_scheme != other.effective_color_scheme
+ || self.native_appearance_disabled != other.native_appearance_disabled
+ {
+ return Some("the zoom, box display, color scheme or native appearance".into());
+ }
+ None
+ }
+}
+
+/// The groups an element's values start from: those of its parent's style or of the initial
+/// style, with what those were built from beside their values.
+#[derive(Clone, Copy)]
+pub(crate) struct GroupSeed<'a> {
+ groups: &'a StyleGroups,
+ facts: &'a GroupValueFacts,
+}
+
+impl<'a> GroupSeed<'a> {
+ pub(crate) fn new(groups: &'a StyleGroups, facts: &'a GroupValueFacts) -> Self {
+ Self { groups, facts }
+ }
+
+ fn group(&self, group: usize) -> GroupPayloadRef<'a> {
+ self.groups.group(StyleGroupIndex::new(group))
+ }
+
+ fn values(&self, group: usize) -> &'a [RetainedStyleValueData] {
+ self.group(group).group_values()
+ }
+
+ fn style_bits(&self) -> StyleBits {
+ self.groups.style_bits()
+ }
+}
+
+/// One payload of each group holding the group's defaults and no values: what a computation
+/// starting from nothing starts from. The process style holds them.
+pub(crate) struct DefaultGroups(StyleGroups);
+
+impl Default for DefaultGroups {
+ fn default() -> Self {
+ // SAFETY: Each payload is a default-constructed payload of its group with one reference,
+ // which the groups take over.
+ Self(unsafe {
+ StyleGroups::adopt(
+ STYLE_GROUPS.map(|group| {
+ let payload = allocate_payload(group, 1);
+ default_construct(group, payload);
+ payload.cast_const()
+ }),
+ StyleBits::INITIAL,
+ )
+ })
+ }
+}
+
+impl DefaultGroups {
+ pub(crate) fn groups(&self) -> &StyleGroups {
+ &self.0
+ }
+}
+
+/// Calls `compute` with a seed of `defaults`, which hold no values, and the facts of no values:
+/// what a computation starting from nothing starts from.
+pub(crate) fn with_default_seed<R>(defaults: &DefaultGroups, compute: impl FnOnce(GroupSeed<'_>) -> R) -> R {
+ let facts = GroupValueFacts::empty();
+ compute(GroupSeed::new(defaults.groups(), &facts))
+}
+
+/// One group's computed values while an element's style is computed: a seed group's, or a group
+/// of its own, which holds a copy of a seed group's payload until its own is built.
+enum DraftValues<'a> {
+ Seed(GroupPayloadRef<'a>),
+ Own(HeldGroup),
+}
+
+/// A group, with a reference to it.
+pub(crate) struct HeldGroup {
+ group: usize,
+ payload: *const c_void,
+}
+
+// SAFETY: As for `StyleGroups`.
+unsafe impl Send for HeldGroup {}
+unsafe impl Sync for HeldGroup {}
+
+impl HeldGroup {
+ /// The group `payload`, a payload of the group at `group`, taking over the caller's
+ /// reference to it.
+ ///
+ /// # Safety
+ /// `payload` must be a live payload of the group, with a reference the caller hands over.
+ pub(crate) unsafe fn adopt(group: usize, payload: *const c_void) -> Self {
+ assert!(!payload.is_null());
+ Self { group, payload }
+ }
+
+ pub(crate) fn as_ptr(&self) -> *const c_void {
+ self.payload
+ }
+
+ /// A new group holding a copy of the payload of `base` and the values `values` yields.
+ fn new_copy<'v>(base: GroupPayloadRef<'_>, values: impl Iterator<Item = &'v RetainedStyleValueData>) -> Self {
+ let group = style_group(base.group_index);
+ let payload = allocate_payload(group, 1);
+ // SAFETY: The payload was just allocated for the group, which `base` is a live payload of,
+ // and nothing else references it yet.
+ unsafe {
+ copy_construct(group, payload, base.as_ptr());
+ for (slot, value) in values_of_mut(group, payload).iter_mut().zip(values) {
+ *slot = value.clone();
+ }
+ }
+ Self {
+ group: base.group_index,
+ payload: payload.cast_const(),
+ }
+ }
+
+ pub(crate) fn values(&self) -> &[RetainedStyleValueData] {
+ // SAFETY: The held reference keeps the group live.
+ unsafe { group_values(self.group, self.payload) }
+ }
+
+ /// The values to write, where this is the only reference to the group.
+ fn values_mut(&mut self) -> Option<&mut [RetainedStyleValueData]> {
+ let group = style_group(self.group);
+ (refcount_of(self.payload, payload_align(group)).load(Ordering::Acquire) == 1)
+ // SAFETY: The group is live, and this is its only reference.
+ .then(|| unsafe { values_of_mut(group, self.payload.cast_mut()) })
+ }
+
+ /// Puts `value` in the payload handle at `place`, where this is the only reference to the group.
+ fn set_handle(&mut self, place: LonghandPlace, value: &RetainedStyleValueData) {
+ let group = style_group(self.group);
+ let offset = place.handle_offset().expect("a payload handle place");
+ assert_eq!(
+ refcount_of(self.payload, payload_align(group)).load(Ordering::Acquire),
+ 1
+ );
+ // SAFETY: The handle is a single retained pointer laid out as a `RetainedStyleValueData`
+ // is, and this is the only reference to the group.
+ unsafe {
+ *self
+ .payload
+ .cast_mut()
+ .byte_add(offset)
+ .cast::<RetainedStyleValueData>() = value.clone();
+ };
+ }
+
+ /// The group, with another reference to it.
+ fn held(&self) -> Self {
+ retain_group_payload(self.group, self.payload);
+ Self {
+ group: self.group,
+ payload: self.payload,
+ }
+ }
+}
+
+impl Drop for HeldGroup {
+ fn drop(&mut self) {
+ release_group_payload(self.group, self.payload);
+ }
+}
+
+impl Clone for DraftValues<'_> {
+ fn clone(&self) -> Self {
+ match self {
+ Self::Seed(group) => Self::Seed(*group),
+ Self::Own(own) => Self::Own(own.held()),
+ }
+ }
+}
+
+impl<'a> DraftValues<'a> {
+ /// The value at `place`, a place of this group.
+ fn value(&self, place: LonghandPlace) -> &RetainedStyleValueData {
+ // SAFETY: The draft's group is live while the draft is, and holds these values.
+ unsafe { place.value_in(self.group(), self.values()) }
+ }
+
+ fn values(&self) -> &[RetainedStyleValueData] {
+ match self {
+ Self::Seed(group) => group.group_values(),
+ Self::Own(group) => group.values(),
+ }
+ }
+
+ /// The group whose values these are.
+ fn group(&self) -> *const c_void {
+ match self {
+ Self::Seed(group) => group.as_ptr(),
+ Self::Own(group) => group.payload,
+ }
+ }
+
+ #[cfg(test)]
+ fn seed(&self) -> Option<*const c_void> {
+ match self {
+ Self::Seed(group) => Some(group.as_ptr()),
+ Self::Own(_) => None,
+ }
+ }
+
+ /// The group of the first of `seeds` holding the very values `values` yields, or else a group
+ /// of the element's own holding them, with a copy of the payload of `base`.
+ fn shared_or_own<'v>(
+ seeds: &[GroupSeed<'a>],
+ base: GroupPayloadRef<'_>,
+ values: impl ExactSizeIterator<Item = &'v RetainedStyleValueData> + Clone,
+ ) -> Self {
+ let group = base.group_index;
+ match seeds.iter().find(|seed| {
+ values
+ .clone()
+ .zip(seed.values(group))
+ .all(|(value, held)| value.pointer() == held.pointer())
+ && GroupValueLayout::handles_of(group)
+ .all(|(_, place)| value_at(seed.group(group), place).pointer() == value_at(base, place).pointer())
+ }) {
+ Some(seed) => Self::Seed(seed.group(group)),
+ None => Self::Own(HeldGroup::new_copy(base, values)),
+ }
+ }
+}
+
+/// An element's computed values by group while its style is computed, before its groups are
+/// built: each group's values are those of a seed group, its parent's or the initial style's, or
+/// its own. Building the groups then puts each group's values into the group's allocation.
+pub(crate) struct GroupValues<'a> {
+ groups: [DraftValues<'a>; group_index::COUNT],
+ /// The values of the longhands held as bits.
+ bits: StyleBits,
+ facts: GroupValueFacts,
+}
+
+impl GroupValues<'_> {
+ /// Whether the values of `group` are those of `payload` itself, a seed the element holds as it
+ /// is, which taking the values into it leaves.
+ pub(crate) fn hold_the_seed(&self, group: usize, payload: *const c_void) -> bool {
+ matches!(&self.groups[group], DraftValues::Seed(seed) if seed.as_ptr() == payload)
+ }
+
+ /// The computed value of `property`.
+ pub(crate) fn value(&self, property: u16) -> &RetainedStyleValueData {
+ let property = GROUP_VALUE_LAYOUT.resolved(property, |property| self.value(property));
+ let place = GROUP_VALUE_LAYOUT.place_of(property);
+ if let Some(field) = place.bit_field() {
+ return self.bits.value(field);
+ }
+ self.groups[place.group()].value(place)
+ }
+
+ /// What the groups holding these values hold as bits beside them.
+ pub(crate) fn style_bits(&self) -> StyleBits {
+ StyleBits {
+ inherited: InheritedSetValues {
+ bits: self.bits.inherited.bits,
+ effective_zoom_bits: self.facts.effective_zoom.to_bits(),
+ },
+ reset: self.bits.reset,
+ }
+ }
+
+ /// 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(crate) fn effective_value(&self, property: u16) -> &RetainedStyleValueData {
+ self.facts
+ .value_read_in_place(property)
+ .unwrap_or_else(|| self.value(property))
+ }
+
+ pub(crate) fn facts(&self) -> &GroupValueFacts {
+ &self.facts
+ }
+
+ /// A hash of the values `reads` names, by their contents.
+ pub(crate) fn read_hash(&self, reads: &GroupReads, hasher: &mut impl std::hash::Hasher) {
+ for (group, &indices) in reads.iter().enumerate() {
+ let values = self.groups[group].values();
+ let mut remaining = indices;
+ while remaining != 0 {
+ let at = remaining.trailing_zeros() as usize;
+ remaining &= remaining - 1;
+ hasher.write_u64(crate::css::style_value::style_value_content_hash(
+ values[at].optional_data(),
+ ));
+ }
+ // NB: A build reading any of a group's values may read the ones its payload handles
+ // hold, which no read bit names.
+ if indices != 0 {
+ for (_, place) in GroupValueLayout::handles_of(group) {
+ hasher.write_u64(crate::css::style_value::style_value_content_hash(
+ self.groups[group].value(place).optional_data(),
+ ));
+ }
+ }
+ }
+ }
+
+ /// The values of each group `reads` reads any of, held, in group order.
+ pub(crate) fn held_read_groups(&self, reads: &GroupReads) -> impl Iterator<Item = HeldGroup> + '_ {
+ let reads = *reads;
+ (0..group_index::COUNT)
+ .filter(move |&group| reads[group] != 0)
+ .map(|group| match &self.groups[group] {
+ DraftValues::Seed(seed) => HeldGroup {
+ group,
+ payload: seed.retained(),
+ },
+ DraftValues::Own(own) => own.held(),
+ })
+ }
+
+ /// Whether these hold the values `held`, the values of each group `reads` reads any of in group
+ /// order, hold at the indices `reads` names, each by identity or else by value.
+ pub(crate) fn holds_read_values(&self, reads: &GroupReads, held: &[HeldGroup]) -> bool {
+ let mut held = held.iter();
+ reads
+ .iter()
+ .enumerate()
+ .filter(|(_, indices)| **indices != 0)
+ .all(|(group, &indices)| {
+ let Some(held) = held.next() else {
+ return false;
+ };
+ if self.groups[group].group() == held.as_ptr() {
+ return true;
+ }
+ // SAFETY: The held group is live while it is held.
+ let held_group = unsafe { GroupPayloadRef::new(group, held.as_ptr()) }.expect("a held group");
+ if !GroupValueLayout::handles_of(group).all(|(_, place)| {
+ let (value, held) = (self.groups[group].value(place), value_at(held_group, place));
+ value.pointer() == held.pointer() || value == held
+ }) {
+ return false;
+ }
+ let (values, held) = (self.groups[group].values(), held.values());
+ let mut remaining = indices;
+ while remaining != 0 {
+ let at = remaining.trailing_zeros() as usize;
+ remaining &= remaining - 1;
+ if values[at].pointer() != held[at].pointer() && values[at] != held[at] {
+ return false;
+ }
+ }
+ true
+ })
+ }
+
+ /// Puts the values of each group into the group `groups` holds for it, built from them,
+ /// taking over the reference `groups` holds: the very group where it holds them already, or
+ /// the draft's group, a seed's or the element's own, where it holds the same payload, or else
+ /// the built group with the values in it.
+ ///
+ /// # Safety
+ /// `groups` must hold one live payload of each group, each with a reference the caller holds.
+ pub(crate) unsafe fn put_into(&self, groups: &mut [*const c_void; group_index::COUNT]) {
+ for (group, (payload, values)) in groups.iter_mut().zip(&self.groups).enumerate() {
+ // SAFETY: The caller passes live payloads, and the drafts' groups are live while they are.
+ *payload = unsafe { group_with_values(group, *payload, values.values(), &[values.group()]) };
+ }
+ }
+
+ /// The groups holding these values, a seed group or one of the element's own each, with a
+ /// reference to each: groups of values, whose payloads are not built from them.
+ pub(crate) fn into_groups(self) -> StyleGroups {
+ let bits = self.style_bits();
+ let pointers = self.groups.map(|draft| match draft {
+ DraftValues::Seed(seed) => seed.retained(),
+ DraftValues::Own(own) => std::mem::ManuallyDrop::new(own).payload,
+ });
+ // SAFETY: Each pointer is a live group of its index, with a reference handed over.
+ unsafe { StyleGroups::adopt(pointers, bits) }
+ }
+
+ /// What the groups are built from beside their values.
+ pub(crate) fn into_facts(self) -> GroupValueFacts {
+ self.facts
+ }
+}
+
+/// An element's computed values as the engine computes them, directly or through the longhand drive,
+/// over the values the element holds before its own declarations, with the flags its record keeps
+/// beside them. The writes are kept beside those values, which the writer only borrows where its
+/// parent or the initial style holds them: a group's values are copied only as the writer finishes,
+/// for the groups whose written values no seed holds: a copy-on-write style builder, at the
+/// granularity of groups.
+#[derive(Clone)]
+pub(crate) struct GroupValuesWriter<'a> {
+ /// The values the element holds before its own declarations, which no write changes.
+ seeded: [DraftValues<'a>; group_index::COUNT],
+ /// The values written over the seeded ones, one per longhand whose value differs from the
+ /// seeded one where it was written.
+ writes: smallvec::SmallVec<[ValueWrite; WRITES_INLINE]>,
+ /// The groups `writes` writes into, one bit per group.
+ written_groups: u32,
+ /// The values of the longhands held as bits, as written so far. The zoom beside them is
+ /// `effective_zoom`'s.
+ bits: StyleBits,
+ /// The recorded specified values of the longhands whose computed values depend on what the
+ /// element inherits, as the initial style records them.
+ seeded_inheritance_dependent_values: Option<std::sync::Arc<[InheritanceDependentValue]>>,
+ /// The recorded specified values of the longhands whose computed values depend on what the
+ /// element inherits, once the computation records others than the seeded ones.
+ inheritance_dependent_values: Option<Vec<(u16, RetainedStyleValueData)>>,
+ effective_zoom: f32,
+ display_before_box_type_transformation: u32,
+ effective_color_scheme: i16,
+ /// Whether each longhand's value is important, inherited and evaluated by the computation,
+ /// and what the box adjustments and the font computation settled.
+ flags: crate::css::computed_longhand_table::LonghandTableFlags,
+ /// What the computed values depend on, as `DEPENDS_ON_VIEWPORT_METRICS` and the like.
+ dependency_flags: u8,
+}
+
+/// A value written over an element's seeded values, at its place among them.
+#[derive(Clone)]
+struct ValueWrite {
+ place: LonghandPlace,
+ value: RetainedStyleValueData,
+}
+
+/// How many written values a [`GroupValuesWriter`] holds before they go to an allocation of their
+/// own.
+const WRITES_INLINE: usize = 16;
+
+impl<'a> GroupValuesWriter<'a> {
+ /// The values a child of the element whose groups are `parent` holds before its own
+ /// declarations: the initial values, with the parent's values of the longhands that inherit in
+ /// place of the ones they are not equal to, and then likewise the values `inherited_overrides`
+ /// hands down in place of those. The child starts with the parent's zoom and color scheme and
+ /// the initial recorded specified values.
+ ///
+ /// The writer starts with the flags `flags` and the dependency flags `dependency_flags`.
+ pub(crate) fn seeded_for_child(
+ parent: GroupSeed<'a>,
+ initial: GroupSeed<'a>,
+ inherited_overrides: impl Iterator<Item = (u16, RetainedStyleValueData)>,
+ flags: crate::css::computed_longhand_table::LonghandTableFlags,
+ dependency_flags: u8,
+ ) -> Self {
+ use crate::css::property_metadata::property_is_inherited;
+ let seeded = std::array::from_fn(|group| {
+ let (parent_group, initial_group) = (parent.group(group), initial.group(group));
+ let longhands = GROUP_VALUE_LAYOUT.longhands_of(group);
+ if parent_group.as_ptr() == initial_group.as_ptr()
+ || !longhands.iter().any(|&property| property_is_inherited(property))
+ {
+ return DraftValues::Seed(initial_group);
+ }
+ let (parent_values, initial_values) = (parent_group.group_values(), initial_group.group_values());
+ // NB: An inherited value equal to the initial one keeps the initial one, as the seed
+ // of a longhand table does.
+ let inherited_value = |(index, &property): (usize, &u16)| {
+ let (value, initial_value) = (&parent_values[index], &initial_values[index]);
+ match property_is_inherited(property)
+ && !value.pointer().is_null()
+ && value.pointer() != initial_value.pointer()
+ && (initial_value.pointer().is_null() || value != initial_value)
+ {
+ true => value,
+ false => initial_value,
+ }
+ };
+ DraftValues::shared_or_own(
+ &[parent, initial],
+ parent_group,
+ longhands.iter().enumerate().map(inherited_value),
+ )
+ });
+ let mut writer = Self {
+ seeded,
+ writes: smallvec::SmallVec::new(),
+ written_groups: 0,
+ // NB: A child inherits its parent's inherited bits, and starts from the initial reset ones.
+ bits: StyleBits {
+ inherited: parent.style_bits().inherited,
+ reset: initial.style_bits().reset,
+ },
+ seeded_inheritance_dependent_values: initial.facts.inheritance_dependent_values.clone(),
+ inheritance_dependent_values: None,
+ effective_zoom: parent.facts.effective_zoom,
+ display_before_box_type_transformation: initial.facts.display_before_box_type_transformation,
+ effective_color_scheme: parent.facts.effective_color_scheme,
+ flags,
+ dependency_flags,
+ };
+ // NB: What the parent hands down is not the child's computation, so it is not evaluated.
+ for (property, value) in inherited_overrides {
+ let held = writer.value(property);
+ if held.pointer().is_null() || *held != value {
+ writer.put(property, std::borrow::Cow::Owned(value));
+ }
+ }
+ // NB: An initial recorded value is that of the initial value. A longhand that inherits another one holds none,
+ // or a group build would read the initial `currentcolor` in place of what the parent hands down.
+ for held in initial
+ .facts
+ .inheritance_dependent_values
+ .as_deref()
+ .unwrap_or_default()
+ {
+ if property_is_inherited(held.property)
+ && crate::css::style_value::retained_value_depends_on_current_color(&held.value)
+ && *writer.value(held.property) != held.value
+ {
+ writer.set_inheritance_dependent_value(held.property, None);
+ }
+ }
+ writer
+ }
+
+ /// This writer, holding a reference to each group it borrowed, so that it outlives the
+ /// groups it was seeded with, as a drive waiting on a font does.
+ pub(crate) fn detached(self) -> GroupValuesWriter<'static> {
+ let Self {
+ seeded,
+ writes,
+ written_groups,
+ bits,
+ seeded_inheritance_dependent_values,
+ inheritance_dependent_values,
+ effective_zoom,
+ display_before_box_type_transformation,
+ effective_color_scheme,
+ flags,
+ dependency_flags,
+ } = self;
+ GroupValuesWriter {
+ seeded: seeded.map(|draft| match draft {
+ DraftValues::Seed(seed) => DraftValues::Own(HeldGroup {
+ group: seed.group_index,
+ payload: seed.retained(),
+ }),
+ DraftValues::Own(own) => DraftValues::Own(own),
+ }),
+ writes,
+ written_groups,
+ bits,
+ seeded_inheritance_dependent_values,
+ inheritance_dependent_values,
+ effective_zoom,
+ display_before_box_type_transformation,
+ effective_color_scheme,
+ flags,
+ dependency_flags,
+ }
+ }
-/// The computed style groups each longhand reaches.
-pub(crate) struct StyleGroupMasks {
- /// Per longhand, the groups a change of its specified winner may change.
- masks: Box<[u32]>,
- /// Per longhand, the group that owns its output.
- output_masks: Box<[u32]>,
-}
+ fn was_written(&self, property: u16) -> bool {
+ self.flags.is_evaluated(property)
+ }
-impl StyleGroupMasks {
- pub(crate) fn get() -> &'static Self {
- static MASKS: OnceLock<StyleGroupMasks> = OnceLock::new();
- MASKS.get_or_init(Self::compute)
+ /// The recorded specified values the initial style holds of the longhands whose computed
+ /// values depend on what the element inherits.
+ fn seeded_inheritance_dependent_values(&self) -> &[InheritanceDependentValue] {
+ self.seeded_inheritance_dependent_values.as_deref().unwrap_or_default()
}
- fn compute() -> Self {
- use crate::css::property_metadata::property_id::{DIRECTION, WRITING_MODE};
- use crate::css::property_metadata::{
- FIRST_LONGHAND_PROPERTY_ID, LAST_LONGHAND_PROPERTY_ID, longhand_is_logical_alias,
- property_style_group_index,
- };
- use crate::css::style_compute::{DIRECTION_COUNT, WRITING_MODE_COUNT, map_logical_alias_to_physical};
+ /// The write at `place`, if there is one.
+ fn write_at(&self, place: LonghandPlace) -> Option<&ValueWrite> {
+ if self.written_groups & (1 << place.group()) == 0 {
+ return None;
+ }
+ self.writes.iter().find(|write| write.place == place)
+ }
- let group_mask = |property| property_style_group_index(property).map_or(0, |group| 1u32 << group);
- let index = |property: u16| usize::from(property - FIRST_LONGHAND_PROPERTY_ID);
- let longhands = FIRST_LONGHAND_PROPERTY_ID..=LAST_LONGHAND_PROPERTY_ID;
- // Direction and writing-mode select the physical winners for every logical property group.
- // Those aliases own no payload, so they reach the groups of every physical property they
- // map to.
- let output_masks: Box<[u32]> = longhands
- .clone()
- .map(|property| {
- if longhand_is_logical_alias(property) {
- 0
- } else {
- group_mask(property)
- }
- })
- .collect();
- let mut masks = output_masks.clone();
+ /// The computed value of `property` written so far.
+ pub(crate) fn value(&self, property: u16) -> &RetainedStyleValueData {
+ let property = GROUP_VALUE_LAYOUT.resolved(property, |property| self.value(property));
+ let place = GROUP_VALUE_LAYOUT.place_of(property);
+ if let Some(field) = place.bit_field() {
+ return self.bits.value(field);
+ }
+ match self.write_at(place) {
+ Some(write) => &write.value,
+ None => self.seeded[place.group()].value(place),
+ }
+ }
- let mut logical_mapping_mask = 0;
- for property in longhands.filter(|&property| longhand_is_logical_alias(property)) {
- let mut alias_mask = 0;
- for writing_mode in 0..WRITING_MODE_COUNT as u8 {
- for direction in 0..DIRECTION_COUNT as u8 {
- alias_mask |= group_mask(map_logical_alias_to_physical(property, writing_mode, direction));
+ /// The values of the longhands held as bits, as written so far.
+ pub(crate) fn bits(&self) -> StyleBits {
+ self.bits
+ }
+
+ /// Whether the value of `property` differs from what the writer was seeded with, the bits
+ /// standing as `seeded_bits`.
+ pub(crate) fn moved_from_seed(&self, property: u16, seeded_bits: StyleBits) -> bool {
+ let property = GROUP_VALUE_LAYOUT.resolved(property, |property| self.value(property));
+ let place = GROUP_VALUE_LAYOUT.place_of(property);
+ if let Some(field) = place.bit_field() {
+ return self.bits.get(field) != seeded_bits.get(field);
+ }
+ self.write_at(place)
+ .is_some_and(|write| write.value != *self.seeded[place.group()].value(place))
+ }
+
+ /// The computed value of `property` written so far, where it has one.
+ pub(crate) fn get(&self, property: u16) -> Option<&RetainedStyleValueData> {
+ Some(self.value(property)).filter(|value| !value.pointer().is_null())
+ }
+
+ /// The value a group build reads for `property`: its recorded currentcolor-dependent specified
+ /// value where the computation did not evaluate it, else its computed value.
+ pub(crate) fn effective_value(&self, property: u16) -> &RetainedStyleValueData {
+ if !self.was_written(property) {
+ let recorded = match &self.inheritance_dependent_values {
+ Some(values) => values
+ .iter()
+ .find(|(held, _)| *held == property)
+ .map(|(_, value)| value),
+ None => self
+ .seeded_inheritance_dependent_values()
+ .iter()
+ .find(|held| held.property == property)
+ .map(|held| &held.value),
+ };
+ if let Some(recorded) = recorded
+ && crate::css::style_value::retained_value_depends_on_current_color(recorded)
+ {
+ return recorded;
+ }
+ }
+ self.value(property)
+ }
+
+ /// Writes `value` as the computed value of `property`, which the computation evaluated.
+ pub(crate) fn set(&mut self, property: u16, value: RetainedStyleValueData) {
+ self.flags.mark_evaluated(property);
+ self.put(property, std::borrow::Cow::Owned(value));
+ }
+
+ /// Writes `value` as the computed value of `property`, which the computation evaluated,
+ /// holding a reference to it only where it stays as a write.
+ pub(crate) fn set_borrowed(&mut self, property: u16, value: &RetainedStyleValueData) {
+ self.flags.mark_evaluated(property);
+ self.put(property, std::borrow::Cow::Borrowed(value));
+ }
+
+ /// Writes `value` as the computed value of `property`, keeping the value held where it is
+ /// equal, which the computation evaluated.
+ pub(crate) fn set_or_keep_equal(&mut self, property: u16, value: &RetainedStyleValueData) {
+ let held = self.value(property);
+ if held.pointer().is_null() || held != value {
+ self.put(property, std::borrow::Cow::Borrowed(value));
+ }
+ self.flags.mark_evaluated(property);
+ }
+
+ fn put(&mut self, property: u16, value: std::borrow::Cow<'_, RetainedStyleValueData>) {
+ // NB: A logical alias holding no value of its own computes as the physical longhand it
+ // maps to, which the computation writes.
+ if !GROUP_VALUE_LAYOUT.holds_value(LonghandID::new(property)) {
+ return;
+ }
+ let place = GROUP_VALUE_LAYOUT.place_of(property);
+ if let Some(field) = place.bit_field() {
+ self.bits = self.bits.with_value(field, &value);
+ return;
+ }
+ if let Some(write) = self.writes.iter_mut().find(|write| write.place == place) {
+ write.value = value.into_owned();
+ return;
+ }
+ if self.seeded[place.group()].value(place).pointer() == value.pointer() {
+ return;
+ }
+ self.written_groups |= 1 << place.group();
+ self.writes.push(ValueWrite {
+ place,
+ value: value.into_owned(),
+ });
+ }
+
+ /// Records `value` as the specified value of `property` where its computed value depends on
+ /// what the element inherits, or that it does not depend on it for none.
+ pub(crate) fn set_inheritance_dependent_value(&mut self, property: u16, value: Option<RetainedStyleValueData>) {
+ if self.inheritance_dependent_values.is_none() {
+ let seeded = self.seeded_inheritance_dependent_values();
+ match (seeded.iter().find(|held| held.property == property), &value) {
+ (None, None) => return,
+ (Some(held), Some(value)) if held.value.pointer() == value.pointer() => return,
+ _ => {}
+ }
+ self.inheritance_dependent_values =
+ Some(seeded.iter().map(|held| (held.property, held.value.clone())).collect());
+ }
+ let values = self
+ .inheritance_dependent_values
+ .as_mut()
+ .expect("the seeded values were just copied");
+ let existing = values.iter().position(|(held, _)| *held == property);
+ match (existing, value) {
+ (Some(index), Some(value)) => {
+ if values[index].1.pointer() != value.pointer() {
+ values[index].1 = value;
}
}
- masks[index(property)] |= alias_mask;
- logical_mapping_mask |= alias_mask;
+ (Some(index), None) => {
+ values.swap_remove(index);
+ }
+ (None, Some(value)) => values.push((property, value)),
+ (None, None) => {}
}
- masks[index(DIRECTION)] |= logical_mapping_mask;
- masks[index(WRITING_MODE)] |= logical_mapping_mask;
- // NB: The inherited UI group holds the used caret color, which `caret-color: auto` resolves against the
- // element's own color.
- masks[index(crate::css::property_metadata::property_id::COLOR)] |=
- 1 << crate::css::table_group_builder::group_index::INHERITED_UI;
- // NB: The box group holds the used containment flags implied by hidden content visibility.
- masks[index(crate::css::property_metadata::property_id::CONTENT_VISIBILITY)] |=
- 1 << crate::css::table_group_builder::group_index::BOX;
- // NB: The misc reset group holds whether an author declaration disables native appearance, which these
- // properties' winners decide.
- for &property in crate::css::style_compute::PROPERTIES_DISABLING_NATIVE_APPEARANCE {
- masks[index(property)] |= 1 << crate::css::table_group_builder::group_index::MISC_RESET;
+ }
+
+ /// The recorded specified values of the longhands whose computed values depend on what the
+ /// element inherits, each with whether a group build reads it: those of the first of `seeds`
+ /// holding the very same ones, shared, as the parent of an element writing none of them does.
+ fn finished_inheritance_dependent_values(
+ &self,
+ seeds: &[GroupSeed<'_>],
+ ) -> Option<std::sync::Arc<[InheritanceDependentValue]>> {
+ let read_by_groups = |property: u16, value: &RetainedStyleValueData| {
+ !self.was_written(property) && crate::css::style_value::retained_value_depends_on_current_color(value)
+ };
+ let seeded = self.seeded_inheritance_dependent_values();
+ let edited = self.inheritance_dependent_values.as_deref();
+ let length = edited.map_or(seeded.len(), <[_]>::len);
+ if length == 0 {
+ return None;
+ }
+ let entry = |index: usize| match edited {
+ Some(values) => (values[index].0, &values[index].1),
+ None => (seeded[index].property, &seeded[index].value),
+ };
+ let same = |held: &[InheritanceDependentValue]| {
+ held.len() == length
+ && held.iter().enumerate().all(|(index, held)| {
+ let (property, value) = entry(index);
+ held.property == property
+ && held.value.pointer() == value.pointer()
+ && held.read_by_groups == read_by_groups(property, value)
+ })
+ };
+ if let Some(shared) = seeds
+ .iter()
+ .filter_map(|seed| seed.facts.inheritance_dependent_values.as_ref())
+ .find(|held| same(held))
+ {
+ return Some(shared.clone());
}
- Self { masks, output_masks }
+ Some(
+ (0..length)
+ .map(|index| {
+ let (property, value) = entry(index);
+ InheritanceDependentValue {
+ property,
+ value: value.clone(),
+ read_by_groups: read_by_groups(property, value),
+ }
+ })
+ .collect(),
+ )
}
- fn longhand_index(property: u16) -> Option<usize> {
- use crate::css::property_metadata::FIRST_LONGHAND_PROPERTY_ID;
- property.checked_sub(FIRST_LONGHAND_PROPERTY_ID).map(usize::from)
+ pub(crate) fn set_display_before_box_type_transformation(&mut self, display: u32) {
+ self.display_before_box_type_transformation = display;
}
- /// The computed style groups which may change when `property`'s specified winner changes; none
- /// for a longhand that feeds no group of its own.
- pub(crate) fn dependencies(&self, property: u16) -> u32 {
- Self::longhand_index(property)
- .and_then(|index| self.masks.get(index))
- .copied()
- .unwrap_or(0)
+ pub(crate) fn effective_color_scheme(&self) -> i16 {
+ self.effective_color_scheme
}
-}
-/// The computed style group which directly owns one longhand's output.
-pub(crate) fn computed_group_output_mask(property: u16) -> Option<u32> {
- let masks = StyleGroupMasks::get();
- StyleGroupMasks::longhand_index(property)
- .and_then(|index| masks.output_masks.get(index))
- .copied()
- .filter(|mask| *mask != 0)
+ pub(crate) fn set_effective_color_scheme(&mut self, scheme: i16) {
+ self.effective_color_scheme = scheme;
+ }
+
+ pub(crate) fn set_effective_zoom(&mut self, zoom: f32) {
+ self.effective_zoom = zoom;
+ }
+
+ /// Writes `value` as the computed value of `property`, keeping the value held where it is
+ /// equal.
+ pub(crate) fn set_computed(&mut self, property: u16, value: StyleValueData) {
+ if self.value(property).optional_data() == Some(&value) {
+ self.flags.mark_evaluated(property);
+ return;
+ }
+ self.set(property, RetainedStyleValueData::from_owned(value));
+ }
+
+ pub(crate) fn note_viewport_dependency(&mut self) {
+ self.dependency_flags |= crate::css::computed_longhand_table::DEPENDS_ON_VIEWPORT_METRICS;
+ }
+
+ /// Adds `flags` to what the computed values depend on.
+ pub(crate) fn merge_dependency_flags(&mut self, flags: u8) {
+ self.dependency_flags |= flags;
+ }
+
+ /// Records whether an author declaration disables the element's native appearance.
+ pub(crate) fn set_native_appearance_disabled(&mut self, disabled: bool) {
+ use crate::css::computed_longhand_table::NATIVE_APPEARANCE_DISABLED;
+ if disabled {
+ self.dependency_flags |= NATIVE_APPEARANCE_DISABLED;
+ } else {
+ self.dependency_flags &= !NATIVE_APPEARANCE_DISABLED;
+ }
+ }
+
+ pub(crate) fn flags_mut(&mut self) -> &mut crate::css::computed_longhand_table::LonghandTableFlags {
+ &mut self.flags
+ }
+
+ pub(crate) fn set_overflow_before_adjustment(&mut self, overflow: [u16; 2]) {
+ self.flags.set_overflow_before_adjustment(overflow);
+ }
+
+ /// Records that the computed value of `property` is no longer important or inherited.
+ pub(crate) fn clear_flags(&mut self, property: u16) {
+ self.flags.set_important(property, false);
+ self.flags.set_inherited(property, false);
+ }
+
+ /// The values written, sharing each group of `seeds` that holds the same values. A group build
+ /// reads the recorded currentcolor-dependent specified value of a longhand the computation
+ /// did not write in place of its computed value. Also answers the flags and dependency flags
+ /// the computation settled beside the values.
+ pub(crate) fn finish(
+ self,
+ seeds: &[GroupSeed<'a>],
+ ) -> (
+ GroupValues<'a>,
+ crate::css::computed_longhand_table::LonghandTableFlags,
+ u8,
+ ) {
+ let inheritance_dependent_values = self.finished_inheritance_dependent_values(seeds);
+ let Self {
+ seeded,
+ writes,
+ written_groups,
+ bits,
+ effective_zoom,
+ display_before_box_type_transformation,
+ effective_color_scheme,
+ flags,
+ dependency_flags,
+ ..
+ } = self;
+ let mut seeded = seeded.map(Some);
+ let groups = std::array::from_fn(|group| {
+ let mut seeded = seeded[group].take().expect("each group is finished once");
+ if written_groups & (1 << group) == 0 {
+ return seeded;
+ }
+ let handle_writes: smallvec::SmallVec<[&ValueWrite; WRITES_INLINE]> = writes
+ .iter()
+ .filter(|write| write.place.group() == group && write.place.handle_offset().is_some())
+ .filter(|write| {
+ let held = seeded.value(write.place);
+ held.pointer() != write.value.pointer() && *held != write.value
+ })
+ .collect();
+ let base = seeded.values();
+ let group_writes: smallvec::SmallVec<[(usize, &RetainedStyleValueData); WRITES_INLINE]> = writes
+ .iter()
+ .filter(|write| write.place.group() == group && write.place.handle_offset().is_none())
+ .map(|write| (write.place.index(), &write.value))
+ .filter(|&(at, value)| base[at].pointer() != value.pointer() && base[at] != *value)
+ .collect();
+ if group_writes.is_empty() && handle_writes.is_empty() {
+ return seeded;
+ }
+ // NB: A group of the element's own takes the writes in place.
+ if let DraftValues::Own(own) = &mut seeded
+ && let Some(values) = own.values_mut()
+ {
+ for (at, value) in group_writes {
+ values[at] = value.clone();
+ }
+ for write in handle_writes {
+ own.set_handle(write.place, &write.value);
+ }
+ return seeded;
+ }
+ let base = seeded.values();
+ let written_value = |at: usize| {
+ group_writes
+ .iter()
+ .find(|&&(written, _)| written == at)
+ .map_or(&base[at], |&(_, value)| value)
+ };
+ // SAFETY: The seeded group is live while the draft is.
+ let base_group = unsafe { GroupPayloadRef::new(group, seeded.group()) }.expect("a draft has a group");
+ if handle_writes.is_empty() {
+ return DraftValues::shared_or_own(seeds, base_group, (0..base.len()).map(written_value));
+ }
+ // NB: A write to a payload handle gives the element a group of its own.
+ let mut own = HeldGroup::new_copy(base_group, (0..base.len()).map(written_value));
+ for write in handle_writes {
+ own.set_handle(write.place, &write.value);
+ }
+ DraftValues::Own(own)
+ });
+ let native_appearance_disabled =
+ dependency_flags & crate::css::computed_longhand_table::NATIVE_APPEARANCE_DISABLED != 0;
+ let values = GroupValues {
+ groups,
+ bits,
+ facts: GroupValueFacts {
+ inheritance_dependent_values,
+ effective_zoom,
+ display_before_box_type_transformation,
+ effective_color_scheme,
+ native_appearance_disabled,
+ },
+ };
+ (values, flags, dependency_flags)
+ }
}
/// One gathered value for the generic group builder: the computed value's
@@ -2573,6 +5357,7 @@ enum GroupFieldPoke<'a> {
I32(usize, i32),
U64(usize, u64),
U32(usize, u32),
+ HeldColor(usize, crate::css::computed_value_types::StyleColor),
Data(usize, &'a RetainedStyleValueData),
}
@@ -2664,14 +5449,19 @@ fn decode_group_field_pokes<'a>(
// Otherwise a color the generic decoder cannot resolve stays at the payload
// default; the Rust group builder owns the field.
}
- Kind::ColorOrKeyword(keyword) => match data {
- StyleValueData::Keyword { keyword: value_keyword } if *value_keyword == keyword => {}
- _ if value.has_resolved_color => pokes.push(Poke::U32(offset, value.resolved_color)),
- // As for Color, the Rust group builder owns colors the generic decoder cannot
- // resolve.
- _ if enforce_constraints => return None,
- _ => {}
- },
+ Kind::HeldColorOrKeyword(keyword) if matches!(data, StyleValueData::Keyword { keyword: value_keyword } if *value_keyword == keyword) =>
+ {}
+ Kind::HeldColor | Kind::HeldColorOrKeyword(_) => {
+ use crate::css::computed_value_types::StyleColor;
+ if matches!(data, StyleValueData::Keyword { keyword } if *keyword == crate::css::css_enums::keyword::CURRENTCOLOR)
+ {
+ pokes.push(Poke::HeldColor(offset, StyleColor::CURRENT_COLOR));
+ } else if value.has_resolved_color {
+ pokes.push(Poke::HeldColor(offset, StyleColor::rgba(value.resolved_color)));
+ } else if enforce_constraints {
+ return None;
+ }
+ }
Kind::ResolvedF32 => pokes.push(Poke::F32(offset, resolved_number()? as f32)),
Kind::ResolvedF64 => pokes.push(Poke::F64(offset, resolved_number()?)),
Kind::ResolvedU8 => pokes.push(Poke::U8(offset, resolved_number()? as u8)),
@@ -2730,6 +5520,9 @@ unsafe fn apply_group_field_pokes(scratch: *mut c_void, pokes: &[GroupFieldPoke]
Poke::I32(offset, value) => *(base.add(offset) as *mut i32) = value,
Poke::U64(offset, value) => *(base.add(offset) as *mut u64) = value,
Poke::U32(offset, value) => *(base.add(offset) as *mut u32) = value,
+ Poke::HeldColor(offset, value) => {
+ *(base.add(offset) as *mut crate::css::computed_value_types::StyleColor) = value;
+ }
Poke::Data(offset, data) => {
// The slot's constructor default is null, so nothing is released.
*(base.add(offset) as *mut *const StyleValueData) = data.clone().into_pointer();
@@ -2745,11 +5538,7 @@ unsafe fn apply_group_field_pokes(scratch: *mut c_void, pokes: &[GroupFieldPoke]
/// `scratch` must be a payload of the group, allocated by
/// `allocate_payload` and not shared.
unsafe fn free_scratch_payload(group: StyleGroup, scratch: *mut c_void) {
- unsafe {
- destruct(group, scratch);
- let allocation = (scratch as *mut u8).sub(header_size(payload_align(group)));
- dealloc(allocation, allocation_layout(group));
- }
+ unsafe { destroy_allocation(group, scratch) }
}
/// Builds a style group payload generically from its registered field
@@ -2760,7 +5549,7 @@ unsafe fn free_scratch_payload(group: StyleGroup, scratch: *mut c_void) {
pub(crate) fn build_style_group(
group_index: usize,
values: &[GroupValueEntry<'_>],
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
) -> *const c_void {
let build_or_reuse_group_payload = || {
let descriptors = group_field_descriptors(group_index);
@@ -2783,12 +5572,11 @@ pub(crate) fn build_style_group(
build_or_reuse_group_payload().unwrap_or(std::ptr::null())
}
-/// Shares one group's immortal default payload - or the parent payload when
+/// Shares one group's default payload - or the parent payload when
/// it equals the default, keeping the identity - for a build whose inputs are
/// all initial values.
-pub(crate) fn share_default_group_payload(group_index: usize, parent: Option<GroupPayloadRef<'_>>) -> *const c_void {
- let default_payload = GroupPayloadRef::default_payload(group_index);
- share_matching_group_payload(group_index, parent, |candidate| candidate.equals(default_payload))
+pub(crate) fn share_default_group_payload(group_index: usize, shares: GroupShares<'_>) -> *const c_void {
+ share_matching_group_payload(group_index, shares, |candidate| candidate.equals(shares.default))
.expect("the default payload equals itself")
}
@@ -2798,7 +5586,7 @@ pub(crate) fn build_group_payload_with_rust_fill<T: StyleGroupPayload>(
group_index: usize,
values: &[GroupValueEntry<'_>],
fill: impl FnOnce(&mut T),
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
) -> *const c_void {
let descriptors = group_field_descriptors(group_index);
assert_eq!(descriptors.len(), values.len());
@@ -2811,51 +5599,6 @@ pub(crate) fn build_group_payload_with_rust_fill<T: StyleGroupPayload>(
share_equal_group_payload(scratch.as_ref(), parent).unwrap_or_else(|| scratch.publish())
}
-/// Builds an inherited box group payload from the six computed keyword
-/// values, sharing instead of allocating whenever it can: the parent's
-/// payload when every field matches it, or the immortal default payload when
-/// every field holds its initial value. Every input is a canonical computed
-/// keyword.
-///
-/// The returned payload carries one reference for the caller; fresh payloads
-/// start at one, shared payloads are retained, and default payloads are
-/// intentionally leaked and never counted.
-#[allow(clippy::too_many_arguments)]
-pub(crate) fn build_inherited_box_group(
- group_index: usize,
- visibility: &RetainedStyleValueData,
- direction: &RetainedStyleValueData,
- writing_mode: &RetainedStyleValueData,
- content_visibility: &RetainedStyleValueData,
- image_rendering: &RetainedStyleValueData,
- text_orientation: &RetainedStyleValueData,
- effective_zoom: f32,
- parent: Option<GroupPayloadRef<'_>>,
-) -> *const c_void {
- use crate::css::style_value::StyleValueData;
-
- let keyword_code = |data: &RetainedStyleValueData, map: fn(u16) -> Option<u8>| -> u8 {
- match data.optional_data() {
- Some(StyleValueData::Keyword { keyword }) => map(*keyword).expect("computed keyword has a supported value"),
- _ => panic!("computed inherited box value is not a keyword"),
- }
- };
- let built = InheritedBoxValues {
- visibility: keyword_code(visibility, crate::css::style_compute::keyword_to_visibility),
- direction: keyword_code(direction, crate::css::style_compute::keyword_to_direction),
- writing_mode: keyword_code(writing_mode, crate::css::style_compute::keyword_to_writing_mode),
- content_visibility: keyword_code(
- content_visibility,
- crate::css::style_compute::keyword_to_content_visibility,
- ),
- image_rendering: keyword_code(image_rendering, crate::css::style_compute::keyword_to_image_rendering),
- text_orientation: keyword_code(text_orientation, crate::css::style_compute::keyword_to_text_orientation),
- effective_zoom_bits: effective_zoom.to_bits(),
- };
-
- share_or_publish_group_payload::<InheritedBoxValues>(group_index, built, parent)
-}
-
impl ComputedSize {
pub(crate) fn keyword(kind: ComputedSizeKind) -> Self {
Self {
@@ -2912,7 +5655,10 @@ impl ComputedSize {
};
Self::retained(kind, data)
}
- Some(StyleValueData::Function { value, .. }) => Self::retained(ComputedSizeKind::FitContent, value),
+ Some(StyleValueData::Function(function_payload)) => {
+ let FunctionPayload { value, .. } = &**function_payload;
+ Self::retained(ComputedSizeKind::FitContent, value)
+ }
Some(StyleValueData::Calculated { .. }) => Self::retained(ComputedSizeKind::Calculated, data),
Some(StyleValueData::Percentage { .. }) => Self::retained(ComputedSizeKind::Percentage, data),
Some(StyleValueData::Length { .. }) => Self::retained(ComputedSizeKind::Length, data),
@@ -3035,7 +5781,7 @@ fn anchor_function_calculated_handle(data: &RetainedStyleValueData) -> ComputedS
// SAFETY: The caller matched `data` as live anchor() or anchor-size() style value data.
let calculated = unsafe { crate::css::calc::create_anchor_function_calculated(data.pointer().cast()) };
ComputedStyleValueHandle {
- pointer: std::sync::Arc::into_raw(calculated).cast(),
+ pointer: StyleValueArc::into_raw(calculated).cast(),
}
}
@@ -3172,27 +5918,16 @@ impl ComputedAspectRatio {
impl BoxValues {
fn initial() -> Self {
- use crate::css::css_enums::{
- baseline_source, box_sizing, clear, field_sizing, float, overflow, positioning, resize, table_layout,
- text_overflow, unicode_bidi, vertical_align,
- };
+ use crate::css::css_enums::{baseline_source, field_sizing, resize, text_overflow, vertical_align};
use crate::css::display::FfiDisplay;
Self {
display: FfiDisplay::inline(),
display_before_box_type_transformation: FfiDisplay::inline(),
- float_: float::NONE,
- clear: clear::NONE,
- position: positioning::STATIC,
- overflow_x: overflow::VISIBLE,
- overflow_y: overflow::VISIBLE,
- box_sizing: box_sizing::CONTENT_BOX,
field_sizing: field_sizing::FIXED,
baseline_source: baseline_source::AUTO,
resize: resize::NONE,
text_overflow: text_overflow::CLIP,
- unicode_bidi: unicode_bidi::NORMAL,
- table_layout: table_layout::AUTO,
grid_auto_flow_row: true,
grid_auto_flow_dense: false,
column_width: ComputedSize::keyword(ComputedSizeKind::Auto),
@@ -3245,9 +5980,9 @@ impl SVGResetValues {
},
x: zero.clone(),
y: zero,
- stop_color: OPAQUE_BLACK_BGRA,
+ stop_color: crate::css::computed_value_types::StyleColor::rgba(OPAQUE_BLACK_BGRA),
stop_opacity: 1.0,
- flood_color: OPAQUE_BLACK_BGRA,
+ flood_color: crate::css::computed_value_types::StyleColor::rgba(OPAQUE_BLACK_BGRA),
flood_opacity: 1.0,
vector_effect: vector_effect::NONE,
}
@@ -3264,7 +5999,7 @@ impl TextResetValues {
text_decoration_thickness: ComputedStyleValueHandle::empty(),
text_decoration_style: keyword_to_text_decoration_style(keyword::SOLID)
.expect("solid maps to TextDecorationStyle"),
- text_decoration_color: 0xff00_0000,
+ text_decoration_color: crate::css::computed_value_types::StyleColor::CURRENT_COLOR,
white_space_trim_discard_before: false,
white_space_trim_discard_after: false,
white_space_trim_discard_inner: false,
@@ -3374,20 +6109,17 @@ impl InheritedUIValues {
Self {
caret_color: ComputedColorOrAuto {
is_auto: true,
- computed_color: 0xff00_0000,
- used_color: 0xff00_0000,
+ color: crate::css::computed_value_types::StyleColor::CURRENT_COLOR,
},
accent_color: ComputedColorOrAuto {
is_auto: true,
- computed_color: 0xff00_0000,
- used_color: 0xff00_0000,
+ color: crate::css::computed_value_types::StyleColor::rgba(0xff00_0000),
},
cursor: RetainedComputedCursorList::from_vec(vec![ComputedCursor {
is_cursor_value: false,
cursor: ComputedStyleValueHandle::empty(),
predefined: crate::css::css_enums::cursor_predefined::AUTO,
}]),
- pointer_events: crate::css::css_enums::pointer_events::AUTO,
forced_color_adjust: crate::css::css_enums::forced_color_adjust::AUTO,
interpolate_size: crate::css::css_enums::interpolate_size::NUMERIC_ONLY,
scrollbar_color: crate::css::computed_value_types::ComputedScrollbarColor {
@@ -3397,6 +6129,7 @@ impl InheritedUIValues {
},
color_scheme: 0,
color_schemes: RetainedUtf16FlyStringList::from_retained_strings(Vec::new()),
+ image_rendering: crate::css::css_enums::image_rendering::AUTO,
color_scheme_only: false,
}
}
@@ -3408,8 +6141,7 @@ impl InheritedSVGValues {
kind,
url: ComputedStyleValueHandle::empty(),
has_color: kind == crate::css::computed_value_types::SVG_PAINT_COLOR,
- color,
- color_is_currentcolor: false,
+ color: crate::css::computed_value_types::StyleColor::rgba(color),
}
}
@@ -3457,11 +6189,7 @@ impl InheritedTextValues {
let enum_value = |value: Option<u8>| value.expect("an initial inherited-text keyword maps to its enum");
Self {
- text_align: enum_value(css_enums::keyword_to_text_align(css_enums::keyword::START)),
text_justify: enum_value(css_enums::keyword_to_text_justify(css_enums::keyword::AUTO)),
- white_space_collapse: enum_value(css_enums::keyword_to_white_space_collapse(css_enums::keyword::COLLAPSE)),
- text_wrap_mode: enum_value(css_enums::keyword_to_text_wrap_mode(css_enums::keyword::WRAP)),
- word_break: enum_value(css_enums::keyword_to_word_break(css_enums::keyword::NORMAL)),
line_break: enum_value(css_enums::keyword_to_line_break(css_enums::keyword::AUTO)),
tab_size_is_number: true,
letter_spacing: CssPixels::default(),
@@ -3569,7 +6297,7 @@ impl BackgroundValues {
ComputedStyleValueHandle::from_retained(crate::css::style_compute::initial_value_handle(property))
};
Self {
- background_color: 0,
+ background_color: crate::css::computed_value_types::StyleColor::rgba(0),
background_color_style_value: initial(property_id::BACKGROUND_COLOR),
// BackgroundBox::BorderBox.
background_color_clip: 0,
@@ -3596,7 +6324,7 @@ impl BorderValues {
ComputedStyleValueHandle::from_retained(crate::css::style_compute::initial_value_handle(property))
};
let side = || ComputedBorderSide {
- color: 0,
+ color: crate::css::computed_value_types::StyleColor::rgba(0),
line_style: 0,
width: CssPixels::default(),
};
@@ -3653,9 +6381,10 @@ impl ContentValues {
let mut facts = 0;
for counters in [&self.counter_increment, &self.counter_reset, &self.counter_set] {
- let Some(StyleValueData::CounterDefinitions { counter_definitions }) = counters.data() else {
+ let Some(StyleValueData::CounterDefinitions(counter_definitions_payload)) = counters.data() else {
continue;
};
+ let CounterDefinitionsPayload { counter_definitions } = &**counter_definitions_payload;
let definitions = counter_definitions.as_slice();
if !definitions.is_empty() {
facts |= GENERATED_CONTENT_DEFINES_COUNTERS;
@@ -3667,9 +6396,10 @@ impl ContentValues {
facts |= GENERATED_CONTENT_DEFINES_LIST_ITEM_COUNTER;
}
}
- let Some(StyleValueData::Content { content, alt_text }) = self.content.data() else {
+ let Some(StyleValueData::Content(content_payload)) = self.content.data() else {
return facts;
};
+ let ContentPayload { content, alt_text } = &**content_payload;
fn items(
list: &crate::css::style_value::RetainedStyleValueData,
) -> &[crate::css::style_value::RetainedStyleValueData] {
@@ -3689,7 +6419,7 @@ impl ContentValues {
}
}
if items(content).iter().chain(items(alt_text)).any(|item| {
- matches!(item.data(), StyleValueData::Counter { counter_name, .. } if counter_name.units() == LIST_ITEM_COUNTER_NAME)
+ matches!(item.data(), StyleValueData::Counter(counter) if counter.counter_name.units() == LIST_ITEM_COUNTER_NAME)
}) {
facts |= GENERATED_CONTENT_SHOWS_LIST_ITEM_COUNTER;
}
@@ -3711,7 +6441,7 @@ pub extern "C" fn rust_content_group_generated_content_facts(content: &ContentVa
content.generated_content_facts()
}
-impl InheritedListValues {
+impl InheritedListTableValues {
fn initial() -> Self {
use crate::css::property_metadata::property_id;
@@ -3720,9 +6450,10 @@ impl InheritedListValues {
};
Self {
list_style_type: initial(property_id::LIST_STYLE_TYPE),
- list_style_position: 1,
list_style_image: initial(property_id::LIST_STYLE_IMAGE),
quotes: initial(property_id::QUOTES),
+ border_spacing_horizontal: 0,
+ border_spacing_vertical: 0,
}
}
}
@@ -3748,7 +6479,7 @@ impl ComputedOverflowClipMargin {
}
}
-impl MiscResetValues {
+impl MiscLayoutValues {
fn initial() -> Self {
use crate::css::css_pixels::CssPixels;
use crate::css::property_metadata::property_id;
@@ -3758,8 +6489,6 @@ impl MiscResetValues {
};
Self {
outline_offset_style_value: initial(property_id::OUTLINE_OFFSET),
- scroll_margin: ComputedLengthBox::zero(),
- scroll_padding: ComputedLengthBox::auto(),
overflow_clip_margin: ComputedOverflowClipMargin::initial(),
column_span: 0,
break_before: crate::css::css_enums::break_between::AUTO,
@@ -3774,14 +6503,32 @@ impl MiscResetValues {
outline_style: 1,
object_fit: 0,
column_height: ComputedSize::keyword(ComputedSizeKind::Auto),
- outline_color: 0xff000000,
+ outline_color: crate::css::computed_value_types::StyleColor::CURRENT_COLOR,
outline_width: CssPixels::from_integer(3),
- column_rule_color: 0xff000000,
+ column_rule_color: crate::css::computed_value_types::StyleColor::CURRENT_COLOR,
column_rule_width: CssPixels::from_integer(3),
outline_offset: CssPixels::from_raw(0),
- user_select: 1,
object_position_x: ComputedStyleValueHandle::percentage(50.0),
object_position_y: ComputedStyleValueHandle::percentage(50.0),
+ shape_image_threshold: 0.0,
+ shape_margin: initial(property_id::SHAPE_MARGIN),
+ shape_outside: initial(property_id::SHAPE_OUTSIDE),
+ content_visibility: crate::css::css_enums::content_visibility::VISIBLE,
+ }
+ }
+}
+
+impl MiscInteractionValues {
+ fn initial() -> Self {
+ use crate::css::property_metadata::property_id;
+
+ let initial = |property| {
+ ComputedStyleValueHandle::from_retained(crate::css::style_compute::initial_value_handle(property))
+ };
+ Self {
+ scroll_margin: ComputedLengthBox::zero(),
+ scroll_padding: ComputedLengthBox::auto(),
+ user_select: 1,
view_transition_name: initial(property_id::VIEW_TRANSITION_NAME),
scroll_behavior: 0,
scroll_snap_align_block: crate::css::css_enums::scroll_snap_align::NONE,
@@ -3793,9 +6540,6 @@ impl MiscResetValues {
scrollbar_width: 0,
overscroll_behavior_x: crate::css::css_enums::overscroll_behavior::AUTO,
overscroll_behavior_y: crate::css::css_enums::overscroll_behavior::AUTO,
- shape_image_threshold: 0.0,
- shape_margin: initial(property_id::SHAPE_MARGIN),
- shape_outside: initial(property_id::SHAPE_OUTSIDE),
will_change: initial(property_id::WILL_CHANGE),
implicit_will_change: RetainedWillChangePropertyList::from_vec(Vec::new()),
}
@@ -3812,13 +6556,13 @@ impl FontValues {
};
Self {
font_size: CssPixels::from_integer(16),
- line_height_used: CssPixels::from_raw(0),
+ resolved_line_height_used: CssPixels::from_raw(0),
font_variant_emoji: 0,
- font_ascent: 0.0,
- font_descent: 0.0,
- font_x_height: 0.0,
- font_zero_advance: 0.0,
- first_available_font: std::ptr::null(),
+ resolved_font_ascent: 0.0,
+ resolved_font_descent: 0.0,
+ resolved_font_x_height: 0.0,
+ resolved_font_zero_advance: 0.0,
+ resolved_first_available_font: std::ptr::null(),
font_cascade_list: libgfx_rust::font::FontCascadeListHandle::null(),
frozen_font_list: libgfx_rust::font::FrozenFontListRef::null(),
font_weight: 400.0,
@@ -3907,8 +6651,7 @@ fn alignment_overflow(data: &RetainedStyleValueData) -> u8 {
/// Builds the complete alignment group from its computed property values.
///
/// The returned payload carries one reference for the caller; fresh payloads
-/// start at one, shared payloads are retained, and default payloads are
-/// intentionally leaked and never counted.
+/// start at one, and shared payloads are retained.
#[allow(clippy::too_many_arguments)]
pub(crate) fn rust_build_alignment_group(
group_index: usize,
@@ -3927,7 +6670,7 @@ pub(crate) fn rust_build_alignment_group(
justify_self: &RetainedStyleValueData,
column_gap: &RetainedStyleValueData,
row_gap: &RetainedStyleValueData,
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
) -> *const c_void {
use crate::css::css_enums;
use crate::css::style_value::StyleValueData;
@@ -3980,12 +6723,11 @@ pub(crate) fn rust_build_alignment_group(
/// Interns a complete non-inherited SVG geometry and painting group.
///
/// The returned payload carries one reference for the caller; fresh payloads
-/// start at one, shared payloads are retained, and default payloads are
-/// intentionally leaked and never counted.
+/// start at one, and shared payloads are retained.
pub(crate) fn build_svg_reset_group_payload(
group_index: usize,
built: SVGResetValues,
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
) -> *const c_void {
abort_on_panic(|| share_or_publish_group_payload::<SVGResetValues>(group_index, built, parent))
}
@@ -3998,11 +6740,11 @@ pub(crate) fn rust_build_text_reset_group(
text_decoration_thickness_kind: u8,
text_decoration_thickness: &RetainedStyleValueData,
text_decoration_style: u8,
- text_decoration_color: u32,
+ text_decoration_color: crate::css::computed_value_types::StyleColor,
white_space_trim_discard_before: bool,
white_space_trim_discard_after: bool,
white_space_trim_discard_inner: bool,
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
) -> *const c_void {
let built = TextResetValues {
text_decoration_lines: RetainedTextDecorationLineList::from_vec(lines.to_vec()),
@@ -4042,7 +6784,7 @@ pub(crate) fn rust_build_surround_group(
padding_bottom: &RetainedStyleValueData,
padding_left: &RetainedStyleValueData,
position_anchor: Option<&RetainedStyleValueData>,
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
) -> *const c_void {
use crate::css::style_value::StyleValueData;
@@ -4086,7 +6828,7 @@ pub(crate) fn rust_build_surround_group(
// SAFETY: The handle retains anchor style value data.
let calculated = unsafe { crate::css::calc::create_anchor_function_calculated(handle.pointer.cast()) };
ComputedStyleValueHandle {
- pointer: std::sync::Arc::into_raw(calculated).cast(),
+ pointer: StyleValueArc::into_raw(calculated).cast(),
}
};
built.top_anchor_inset_wrapper = wrapper(&built.top_anchor_inset);
@@ -4106,23 +6848,14 @@ pub(crate) fn rust_build_surround_group(
/// every outcome.
///
/// The returned payload carries one reference for the caller; fresh payloads
-/// start at one, shared payloads are retained, and default payloads are
-/// intentionally leaked and never counted.
+/// start at one, and shared payloads are retained.
#[allow(clippy::too_many_arguments)]
-pub(crate) fn rust_build_box_group(
- group_index: usize,
- built: BoxValues,
- parent: Option<GroupPayloadRef<'_>>,
-) -> *const c_void {
+pub(crate) fn rust_build_box_group(group_index: usize, built: BoxValues, parent: GroupShares<'_>) -> *const c_void {
share_or_publish_group_payload::<BoxValues>(group_index, built, parent)
}
#[allow(clippy::too_many_arguments)]
-pub(crate) fn rust_build_grid_group(
- group_index: usize,
- built: GridValues,
- parent: Option<GroupPayloadRef<'_>>,
-) -> *const c_void {
+pub(crate) fn rust_build_grid_group(group_index: usize, built: GridValues, parent: GroupShares<'_>) -> *const c_void {
share_or_publish_group_payload::<GridValues>(group_index, built, parent)
}
@@ -4168,7 +6901,7 @@ pub(crate) fn build_sizing_group(
height: &RetainedStyleValueData,
min_height: &RetainedStyleValueData,
max_height: &RetainedStyleValueData,
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
) -> *const c_void {
let built = SizingValues {
width: ComputedSize::from_data(width),
@@ -4182,99 +6915,6 @@ pub(crate) fn build_sizing_group(
share_or_publish_group_payload::<SizingValues>(group_index, built, parent)
}
-/// Builds an inherited table group payload from the computed values, with the
-/// same sharing rules as the inherited box builder. Computed border-spacing
-/// is a pair of absolute pixel lengths.
-pub(crate) fn build_inherited_table_group(
- group_index: usize,
- border_collapse: &RetainedStyleValueData,
- caption_side: &RetainedStyleValueData,
- empty_cells: &RetainedStyleValueData,
- border_spacing: &RetainedStyleValueData,
- parent: Option<GroupPayloadRef<'_>>,
-) -> *const c_void {
- use crate::css::style_value::StyleValueData;
-
- let keyword_code = |data: &RetainedStyleValueData, map: fn(u16) -> Option<u8>| -> u8 {
- match data.optional_data() {
- Some(StyleValueData::Keyword { keyword }) => map(*keyword).expect("computed keyword has a supported value"),
- _ => panic!("computed inherited table value is not a keyword"),
- }
- };
- let spacing_component = |data: &StyleValueData| -> i32 {
- match data {
- StyleValueData::Length { value, unit } if *unit == crate::css::style_compute::px_length_unit() => {
- crate::css::css_pixels::CssPixels::nearest_value_for(*value).raw_value()
- }
- _ => panic!("computed border-spacing component is not an absolute pixel length"),
- }
- };
- let components = match border_spacing.optional_data() {
- Some(StyleValueData::ValueList { values, .. }) if values.as_slice().len() == 2 => values.as_slice(),
- _ => panic!("computed border-spacing is not a pair"),
- };
- let built = InheritedTableValues {
- border_collapse: keyword_code(border_collapse, crate::css::style_compute::keyword_to_border_collapse),
- caption_side: keyword_code(caption_side, crate::css::style_compute::keyword_to_caption_side),
- empty_cells: keyword_code(empty_cells, crate::css::style_compute::keyword_to_empty_cells),
- border_spacing_horizontal: spacing_component(components[0].data()),
- border_spacing_vertical: spacing_component(components[1].data()),
- };
-
- share_or_publish_group_payload::<InheritedTableValues>(group_index, built, parent)
-}
-
-/// Layout of the inherited table style value group.
-///
-/// The enum fields follow the opaque-byte convention; the border spacings are
-/// raw CSSPixels fixed-point values.
-#[repr(C)]
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub struct InheritedTableValues {
- pub border_collapse: u8,
- pub caption_side: u8,
- pub empty_cells: u8,
- pub border_spacing_horizontal: i32,
- pub border_spacing_vertical: i32,
-}
-
-impl InheritedTableValues {
- fn initial() -> Self {
- use crate::css::css_enums::{border_collapse, caption_side, empty_cells};
-
- Self {
- border_collapse: border_collapse::SEPARATE,
- caption_side: caption_side::TOP,
- empty_cells: empty_cells::SHOW,
- border_spacing_horizontal: 0,
- border_spacing_vertical: 0,
- }
- }
-}
-
-impl InheritedBoxValues {
- fn initial() -> Self {
- use crate::css::css_enums::{
- content_visibility, direction, image_rendering, text_orientation, visibility, writing_mode,
- };
-
- Self {
- visibility: visibility::VISIBLE,
- direction: direction::LTR,
- writing_mode: writing_mode::HORIZONTAL_TB,
- content_visibility: content_visibility::VISIBLE,
- image_rendering: image_rendering::AUTO,
- text_orientation: text_orientation::MIXED,
- effective_zoom_bits: 1.0f32.to_bits(),
- }
- }
-
- /// https://drafts.csswg.org/css-viewport/#effective-zoom
- pub(crate) fn effective_zoom(&self) -> f32 {
- f32::from_bits(self.effective_zoom_bits)
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -4296,44 +6936,203 @@ mod tests {
}
}
+ #[test]
+ fn every_longhand_has_one_place_among_the_group_values() {
+ use crate::css::computed_longhand_table::LONGHAND_COUNT;
+ use crate::css::property_metadata::property_id;
+
+ let layout = GroupValueLayout::get();
+ let mut held = 0;
+ for group in 0..group_index::COUNT {
+ for (index, &property) in layout.longhands_of(group).iter().enumerate() {
+ let place = layout.place(LonghandID::new(property));
+ assert_eq!((place.group(), place.index()), (group, index));
+ assert!(GroupValueLayout::reads(layout.reads_of(group), place));
+ held += 1;
+ }
+ for (_, place) in GroupValueLayout::handles_of(group) {
+ assert_eq!(place.group(), group);
+ assert!(GroupValueLayout::reads(layout.reads_of(group), place));
+ held += 1;
+ }
+ }
+ let slotless = (crate::css::property_metadata::FIRST_LONGHAND_PROPERTY_ID
+ ..=crate::css::property_metadata::LAST_LONGHAND_PROPERTY_ID)
+ .filter(|&property| !layout.holds_value(LonghandID::new(property)))
+ .count();
+ assert!(slotless > 0);
+ let bits = StyleBitField::ALL
+ .iter()
+ .filter(|field| layout.place(LonghandID::new(field.property())).bit_field() == Some(**field))
+ .count();
+ assert_eq!(bits, StyleBitField::ALL.len());
+ assert_eq!(held + slotless + bits, LONGHAND_COUNT);
+ assert_eq!(
+ layout.place(LonghandID::new(property_id::WIDTH)).group(),
+ group_index::SIZING
+ );
+ assert_eq!(
+ layout.place(LonghandID::new(property_id::ZOOM)).group(),
+ group_index::BOX
+ );
+ }
+
+ #[test]
+ fn group_values_share_the_seed_groups_holding_the_same_values() {
+ use crate::css::computed_longhand_table::LonghandTableFlags;
+ use crate::css::property_metadata::property_id;
+
+ let number = |value| RetainedStyleValueData::from_owned(StyleValueData::Number { value });
+ let (color, initial_width) = (number(1.0), number(2.0));
+ let defaults = DefaultGroups::default();
+ let mut initial_groups: [*const c_void; group_index::COUNT] = std::array::from_fn(|group| {
+ // SAFETY: The default payload is a live payload of its group.
+ unsafe { clone_group_payload(group, defaults.groups()[group].as_ptr()) }.cast_const()
+ });
+ let initial_facts = with_default_seed(&defaults, |nothing| {
+ let mut writer = GroupValuesWriter::seeded_for_child(
+ nothing,
+ nothing,
+ std::iter::empty(),
+ LonghandTableFlags::empty(),
+ 0,
+ );
+ writer.set(property_id::COLOR, color.clone());
+ writer.set(property_id::WIDTH, initial_width.clone());
+ let (initial_values, ..) = writer.finish(&[]);
+ // SAFETY: Each group holds one reference to a fresh payload of its group.
+ unsafe { initial_values.put_into(&mut initial_groups) };
+ initial_values.into_facts()
+ });
+ // SAFETY: The groups stay live until the end of the test.
+ let initial_style_groups = unsafe { StyleGroups::retained(&initial_groups, StyleBits::INITIAL) };
+ let seed = GroupSeed::new(&initial_style_groups, &initial_facts);
+ let sizing = group_index::SIZING;
+
+ // Only the group whose values the element changes holds its own.
+ let width = number(3.0);
+ let mut writer =
+ GroupValuesWriter::seeded_for_child(seed, seed, std::iter::empty(), LonghandTableFlags::empty(), 0);
+ writer.set(property_id::COLOR, color.clone());
+ writer.set(property_id::WIDTH, width.clone());
+ let (values, ..) = writer.finish(&[seed]);
+ for group in 0..group_index::COUNT {
+ assert_eq!(values.groups[group].seed().is_some(), group != sizing);
+ }
+ assert_eq!(values.value(property_id::WIDTH).pointer(), width.pointer());
+
+ // A writer writing the same value holds the same values, and one writing the seed's value
+ // back shares the seed's group again.
+ let mut writer = GroupValuesWriter::seeded_for_child(
+ seed,
+ seed,
+ std::iter::empty(),
+ crate::css::computed_longhand_table::LonghandTableFlags::empty(),
+ 0,
+ );
+ writer.set(property_id::WIDTH, width.clone());
+ let (written, ..) = writer.finish(&[seed]);
+ assert!(written.groups[sizing].seed().is_none());
+ assert_eq!(written.value(property_id::WIDTH).pointer(), width.pointer());
+ let mut writer = GroupValuesWriter::seeded_for_child(
+ seed,
+ seed,
+ std::iter::empty(),
+ crate::css::computed_longhand_table::LonghandTableFlags::empty(),
+ 0,
+ );
+ writer.set(property_id::WIDTH, number(7.0));
+ writer.set(property_id::WIDTH, initial_width.clone());
+ let (restored, ..) = writer.finish(&[seed]);
+ assert_eq!(restored.groups[sizing].seed(), Some(initial_groups[sizing]));
+
+ for (group, payload) in initial_groups.into_iter().enumerate() {
+ release_group_payload(group, payload);
+ }
+ }
+
+ #[test]
+ fn computed_groups_release_what_no_style_adopted() {
+ let defaults = DefaultGroups::default();
+ let references = |pointers: &[*const c_void; group_index::COUNT]| -> Vec<usize> {
+ pointers
+ .iter()
+ .enumerate()
+ .map(|(group, &pointer)| {
+ refcount_of(pointer, payload_align(style_group(group))).load(Ordering::Relaxed)
+ })
+ .collect()
+ };
+ // SAFETY: Each default payload is a live payload of its group.
+ let held: [*const c_void; group_index::COUNT] = std::array::from_fn(|group| {
+ unsafe { clone_group_payload(group, defaults.groups()[group].as_ptr()) }.cast_const()
+ });
+ let before = references(&held);
+ let borrowed = BorrowedGroups::of_groups_where(|group| INHERITED_SET_GROUPS.contains(&group));
+
+ // A computation thrown away releases the references it took, and none of the groups it
+ // borrowed.
+ for (group, &pointer) in held.iter().enumerate() {
+ if !borrowed.contains(group) {
+ retain_group_payload(group, pointer);
+ }
+ }
+ // SAFETY: Each group holds a reference for these groups but the borrowed ones.
+ drop(unsafe { ComputedGroups::new(held, StyleBits::INITIAL, 0, borrowed) });
+ assert_eq!(references(&held), before);
+
+ // A computation a style adopts hands its references to the style.
+ for (group, &pointer) in held.iter().enumerate() {
+ if !borrowed.contains(group) {
+ retain_group_payload(group, pointer);
+ }
+ }
+ // SAFETY: Each group holds a reference for these groups but the borrowed ones.
+ let adopted = unsafe { ComputedGroups::new(held, StyleBits::INITIAL, 0, borrowed) }.adopt_sharing(&[]);
+ assert!(
+ references(&held)
+ .iter()
+ .zip(&before)
+ .all(|(after, before)| after == &(before + 1))
+ );
+ drop(adopted);
+ assert_eq!(references(&held), before);
+
+ for (group, payload) in held.into_iter().enumerate() {
+ release_group_payload(group, payload);
+ }
+ }
+
#[test]
fn payload_lifecycle() {
- // The contract a payload's content hash owes its equality: two payloads that compare
- // equal hash equal, whoever built them and wherever they live. That is what lets a
- // group's identity be its content instead of the address of the first payload to
- // carry it.
+ let defaults = DefaultGroups::default();
for group_index in 0..group_index::COUNT {
- let default = default_group_payload(group_index);
+ let default = defaults.groups()[group_index].as_ptr();
// SAFETY: The default payload is a live payload of its group.
let clone = unsafe { rust_style_group_clone(group_index, default) };
// SAFETY: The payloads are live defaults and clones of this group.
assert!(unsafe { style_group_payloads_equal(group_index, default, clone) });
- assert_eq!(
- // SAFETY: The payloads are live defaults and clones of this group.
- unsafe { style_group_payloads_hash(group_index, default) },
- // SAFETY: The payloads are live defaults and clones of this group.
- unsafe { style_group_payloads_hash(group_index, clone) },
- "a clone must hash like the payload it was copied from"
- );
refcount_of(clone, payload_align(style_group(group_index))).store(0, Ordering::Relaxed);
// SAFETY: The clone holds the last reference and is a payload of this group.
unsafe { rust_style_group_free(group_index, clone) };
}
- // A field the hash skipped would be a difference equality has to separate every time,
- // so every field equality reads is a field the hash reads too.
- let mut changed = InheritedTableValues::initial();
- changed.border_spacing_horizontal = 17;
- let changed_payload = (&raw const changed).cast::<c_void>();
- let table_default = default_group_payload(group_index::INHERITED_TABLE);
- // SAFETY: The payloads are live defaults and clones of this group.
- assert!(!unsafe { style_group_payloads_equal(group_index::INHERITED_TABLE, table_default, changed_payload) });
- assert_ne!(
- // SAFETY: The payloads are live defaults and clones of this group.
- unsafe { style_group_payloads_hash(group_index::INHERITED_TABLE, table_default) },
- // SAFETY: The payloads are live defaults and clones of this group.
- unsafe { style_group_payloads_hash(group_index::INHERITED_TABLE, changed_payload) }
- );
+ let table_default = defaults.groups()[group_index::INHERITED_LIST_TABLE].as_ptr();
+ // SAFETY: The default payload is a live payload of its group.
+ let changed_payload = unsafe { rust_style_group_clone(group_index::INHERITED_LIST_TABLE, table_default) };
+ // SAFETY: The clone is uniquely owned and a list and table group.
+ unsafe { &mut *changed_payload.cast::<InheritedListTableValues>() }.border_spacing_horizontal = 17;
+ // SAFETY: The payloads are live payloads of this group.
+ assert!(!unsafe {
+ style_group_payloads_equal(group_index::INHERITED_LIST_TABLE, table_default, changed_payload)
+ });
+ refcount_of(
+ changed_payload,
+ payload_align(style_group(group_index::INHERITED_LIST_TABLE)),
+ )
+ .store(0, Ordering::Relaxed);
+ // SAFETY: The clone holds the last reference and is a payload of this group.
+ unsafe { rust_style_group_free(group_index::INHERITED_LIST_TABLE, changed_payload) };
}
}
diff --git a/Libraries/LibWeb/Rust/src/css/counter_representation.rs b/Libraries/LibWeb/Rust/src/css/counter_representation.rs
index ff6e7b6aeb7..1cac705129b 100644
--- a/Libraries/LibWeb/Rust/src/css/counter_representation.rs
+++ b/Libraries/LibWeb/Rust/src/css/counter_representation.rs
@@ -14,6 +14,7 @@
use crate::css::css_enums::symbols_type;
use crate::css::css_string::CssString;
use crate::css::ffi_support::OwnedArc;
+use crate::css::style_value::CounterStylePayload;
use crate::css::style_value::StyleValueData;
use std::collections::HashMap;
use std::ffi::c_void;
@@ -252,15 +253,15 @@ pub(crate) fn resolve_counter_style_value(
tree_scope: u32,
value: Option<&StyleValueData>,
) -> Option<Arc<CounterStyle>> {
- let Some(StyleValueData::CounterStyle {
+ let Some(StyleValueData::CounterStyle(counter_style_payload)) = value else {
+ return None;
+ };
+ let CounterStylePayload {
is_symbols,
name,
symbols_type,
symbols,
- }) = value
- else {
- return None;
- };
+ } = &**counter_style_payload;
if *is_symbols {
return Some(symbols_function_counter_style(*symbols_type, symbols.as_slice()));
}
@@ -1007,15 +1008,16 @@ pub unsafe extern "C" fn rust_list_style_type_depends_on_counter_value(
match list_style_type {
// `none`, and a string marker, are the same for every item.
StyleValueData::Keyword { .. } | StyleValueData::String { .. } => false,
- StyleValueData::CounterStyle {
- is_symbols: true,
- symbols_type,
- symbols,
- ..
- } => symbols_function_counter_style(*symbols_type, symbols.as_slice()).representation_depends_on_value(),
+ StyleValueData::CounterStyle(counter_style) if counter_style.is_symbols => {
+ symbols_function_counter_style(counter_style.symbols_type, counter_style.symbols.as_slice())
+ .representation_depends_on_value()
+ }
// A name no scope registers counts in decimal.
- StyleValueData::CounterStyle { name, .. } => RegisteredCounterStyles::lookup(scopes, name.units())
- .is_none_or(|style| style.representation_depends_on_value()),
+ StyleValueData::CounterStyle(counter_style) => {
+ RegisteredCounterStyles::lookup(scopes, counter_style.name.units())
+ .is_none_or(|style| style.representation_depends_on_value())
+ }
+
_ => true,
}
}
diff --git a/Libraries/LibWeb/Rust/src/css/counter_style.rs b/Libraries/LibWeb/Rust/src/css/counter_style.rs
index f8cbbb1a361..6cac9989ae9 100644
--- a/Libraries/LibWeb/Rust/src/css/counter_style.rs
+++ b/Libraries/LibWeb/Rust/src/css/counter_style.rs
@@ -17,6 +17,7 @@ use crate::css::ffi_support::{FfiUtf16View, ascii_lowercase};
use crate::css::parser::descriptor_parser::resolve_descriptor_integer;
use crate::css::parser::value_parser::equals_ascii_case_insensitive;
use crate::css::style_compute::FfiLengthResolutionContext;
+use crate::css::style_value::CounterStyleSystemPayload;
use crate::css::style_value::{RetainedStyleValueData, StyleValueData};
use std::cell::RefCell;
use std::collections::HashMap;
@@ -151,14 +152,14 @@ fn list(value: &StyleValueData) -> &[RetainedStyleValueData] {
/// `extends`, which must have neither.
/// https://drafts.csswg.org/css-counter-styles-3/#counter-style-symbols
fn symbol_counts_needed(system: Option<&StyleValueData>) -> Option<(usize, usize)> {
- match system {
- Some(StyleValueData::CounterStyleSystem { kind: 2, .. }) => None,
- Some(StyleValueData::CounterStyleSystem {
+ match system.and_then(StyleValueData::as_counter_style_system) {
+ Some(CounterStyleSystemPayload { kind: 2, .. }) => None,
+ Some(CounterStyleSystemPayload {
kind: 0,
system: counter_style_system::ADDITIVE,
..
}) => Some((0, 1)),
- Some(StyleValueData::CounterStyleSystem {
+ Some(CounterStyleSystemPayload {
kind: 0,
system: counter_style_system::ALPHABETIC | counter_style_system::NUMERIC,
..
@@ -199,10 +200,10 @@ impl Definition {
.collect::<Option<Vec<_>>>()?;
(symbols.len() >= symbols_needed).then_some(symbols)
};
- let system = match descriptor("system") {
- Some(StyleValueData::CounterStyleSystem { kind: 2, name, .. }) => System::Extends(name.units().into()),
+ let system = match descriptor("system").and_then(StyleValueData::as_counter_style_system) {
+ Some(CounterStyleSystemPayload { kind: 2, name, .. }) => System::Extends(name.units().into()),
// https://drafts.csswg.org/css-counter-styles-3/#fixed-system
- Some(StyleValueData::CounterStyleSystem {
+ Some(CounterStyleSystemPayload {
kind: 1, first_symbol, ..
}) => System::Algorithm(Algorithm::Fixed {
// If it is omitted, the first symbol value is 1.
@@ -213,7 +214,7 @@ impl Definition {
symbols: symbols()?,
}),
// https://drafts.csswg.org/css-counter-styles-3/#additive-system
- Some(StyleValueData::CounterStyleSystem {
+ Some(CounterStyleSystemPayload {
system: counter_style_system::ADDITIVE,
..
}) => System::Algorithm(Algorithm::Additive(
@@ -226,7 +227,7 @@ impl Definition {
// The initial value of system is symbolic.
system => {
let system = match system {
- Some(StyleValueData::CounterStyleSystem { system, .. }) => *system,
+ Some(CounterStyleSystemPayload { system, .. }) => *system,
_ => counter_style_system::SYMBOLIC,
};
let system = match system {
@@ -558,19 +559,21 @@ pub extern "C" fn rust_counter_style_system_accepts_symbols(
/// system itself, the first symbol of a fixed one or the style an extending one extends.
#[unsafe(no_mangle)]
pub extern "C" fn rust_counter_style_system_changes_algorithm(current: &StyleValueData, new: &StyleValueData) -> bool {
- use StyleValueData::CounterStyleSystem;
+ let (Some(current), Some(new)) = (current.as_counter_style_system(), new.as_counter_style_system()) else {
+ return true;
+ };
match (current, new) {
(
- CounterStyleSystem { kind: 0, system, .. },
- CounterStyleSystem {
+ CounterStyleSystemPayload { kind: 0, system, .. },
+ CounterStyleSystemPayload {
kind: 0, system: new, ..
},
) => system != new,
(
- CounterStyleSystem {
+ CounterStyleSystemPayload {
kind: 1, first_symbol, ..
},
- CounterStyleSystem {
+ CounterStyleSystemPayload {
kind: 1,
first_symbol: new,
..
@@ -580,7 +583,9 @@ pub extern "C" fn rust_counter_style_system_changes_algorithm(current: &StyleVal
let one = StyleValueData::Integer { value: 1 };
first_symbol.optional_data().unwrap_or(&one) != new.optional_data().unwrap_or(&one)
}
- (CounterStyleSystem { kind: 2, name, .. }, CounterStyleSystem { kind: 2, name: new, .. }) => name != new,
+ (CounterStyleSystemPayload { kind: 2, name, .. }, CounterStyleSystemPayload { kind: 2, name: new, .. }) => {
+ name != new
+ }
_ => true,
}
}
diff --git a/Libraries/LibWeb/Rust/src/css/css_string.rs b/Libraries/LibWeb/Rust/src/css/css_string.rs
index 915fcf7640d..2e09fc6f673 100644
--- a/Libraries/LibWeb/Rust/src/css/css_string.rs
+++ b/Libraries/LibWeb/Rust/src/css/css_string.rs
@@ -8,32 +8,48 @@
use crate::css::css_tokenizer::TokenizerInput;
use crate::css::retained_fly_string::RetainedUtf16FlyString;
-use std::sync::Arc;
+use std::sync::atomic::{AtomicU32, Ordering};
-// Prefix the Arc slice with its length so each string owns one allocation while
-// retaining the one-word handle used throughout parsed and bound selector trees.
-const LENGTH_PREFIX_UNITS: usize = size_of::<usize>() / size_of::<u16>();
+/// The header of a string's one allocation, which its UTF-16 code units follow: a count of its
+/// handles and its length, in 8 bytes.
+#[repr(C)]
+struct StringHeader {
+ references: AtomicU32,
+ length: u32,
+}
-fn allocate_string(units: &[u16]) -> Arc<[u16]> {
- let length = units
- .len()
- .checked_add(LENGTH_PREFIX_UNITS)
+const HEADER_BYTES: usize = size_of::<StringHeader>();
+
+fn layout(length: usize) -> std::alloc::Layout {
+ let bytes = length
+ .checked_mul(size_of::<u16>())
+ .and_then(|bytes| bytes.checked_add(HEADER_BYTES))
.expect("CSS string size overflow");
- let mut data = Arc::<[u16]>::new_uninit_slice(length);
- let pointer = Arc::get_mut(&mut data).unwrap().as_mut_ptr().cast::<u16>();
- // SAFETY: The prefix occupies exactly one usize, and the remaining slice has
- // room for every source unit. Both writes initialize valid u16 bit patterns.
- // The Arc's data is only guaranteed to have u16 alignment.
+ std::alloc::Layout::from_size_align(bytes, align_of::<StringHeader>()).expect("CSS string size overflow")
+}
+
+fn allocate_string(units: &[u16]) -> usize {
+ let length = u32::try_from(units.len()).expect("CSS string size overflow");
+ let layout = layout(units.len());
+ // SAFETY: The layout is nonzero; the header and every code unit are written before any read.
unsafe {
- pointer.cast::<usize>().write_unaligned(units.len());
- std::ptr::copy_nonoverlapping(units.as_ptr(), pointer.add(LENGTH_PREFIX_UNITS), units.len());
- data.assume_init()
+ let base = std::alloc::alloc(layout);
+ if base.is_null() {
+ std::alloc::handle_alloc_error(layout);
+ }
+ base.cast::<StringHeader>().write(StringHeader {
+ references: AtomicU32::new(1),
+ length,
+ });
+ std::ptr::copy_nonoverlapping(units.as_ptr(), base.add(HEADER_BYTES).cast::<u16>(), units.len());
+ base as usize
}
}
#[repr(C)]
pub struct CssString {
- // An owned length-prefixed Arc<[u16]>, or zero for an absent optional string.
+ // One handle to a counted allocation of a `StringHeader` and the code units, or zero for an
+ // absent optional string.
raw: usize,
}
@@ -43,17 +59,14 @@ impl CssString {
return Self::default();
}
Self {
- raw: Arc::into_raw(allocate_string(units)).cast::<u16>() as usize,
+ raw: allocate_string(units),
}
}
- fn data_pointer(&self) -> *const [u16] {
+ fn header(&self) -> &StringHeader {
debug_assert_ne!(self.raw, 0);
- let pointer = self.raw as *const u16;
- // SAFETY: Every nonzero handle owns an Arc created by allocate_string.
- // Its initialized prefix records the slice metadata discarded by the handle.
- let length = unsafe { pointer.cast::<usize>().read_unaligned() };
- std::ptr::slice_from_raw_parts(pointer, LENGTH_PREFIX_UNITS + length)
+ // SAFETY: Every nonzero handle refers to a live allocation `allocate_string` made.
+ unsafe { &*(self.raw as *const StringHeader) }
}
pub(crate) fn none() -> Self {
@@ -64,13 +77,21 @@ impl CssString {
if self.raw == 0 { std::ptr::null() } else { self }
}
+ /// The bytes of the string's counted allocation, the first time `sizer` reaches it.
+ pub(crate) fn heap_size(&self, sizer: &mut crate::heap_size::HeapSizer) -> usize {
+ if !sizer.first_sight(self.raw as *const u8) {
+ return 0;
+ }
+ HEADER_BYTES + size_of_val::<[u16]>(self.units())
+ }
+
pub(crate) fn units(&self) -> &[u16] {
if self.raw == 0 {
return &[];
}
- // SAFETY: The handle owns the reconstructed Arc slice for this borrow.
- let data = unsafe { &*self.data_pointer() };
- &data[LENGTH_PREFIX_UNITS..]
+ let length = self.header().length as usize;
+ // SAFETY: The code units follow the header, `length` of them.
+ unsafe { ak::slice_from_raw_parts((self.raw + HEADER_BYTES) as *const u16, length) }
}
/// Copy a borrowed AK string into Rust-owned storage at the host boundary.
@@ -113,11 +134,12 @@ impl CssString {
// An empty string is present, unlike the null handle used for an absent optional string.
impl Default for CssString {
fn default() -> Self {
- static EMPTY: std::sync::OnceLock<Arc<[u16]>> = std::sync::OnceLock::new();
- let data = EMPTY.get_or_init(|| allocate_string(&[]));
- Self {
- raw: Arc::into_raw(Arc::clone(data)).cast::<u16>() as usize,
- }
+ static EMPTY: std::sync::OnceLock<CssString> = std::sync::OnceLock::new();
+ EMPTY
+ .get_or_init(|| Self {
+ raw: allocate_string(&[]),
+ })
+ .clone()
}
}
@@ -150,7 +172,8 @@ impl AsRef<[u16]> for CssString {
impl Clone for CssString {
fn clone(&self) -> Self {
if self.raw != 0 {
- unsafe { Arc::increment_strong_count(self.data_pointer()) };
+ let previous = self.header().references.fetch_add(1, Ordering::Relaxed);
+ assert!(previous < u32::MAX / 2, "CSS string reference count overflow");
}
Self { raw: self.raw }
}
@@ -158,9 +181,13 @@ impl Clone for CssString {
impl Drop for CssString {
fn drop(&mut self) {
- if self.raw != 0 {
- unsafe { Arc::decrement_strong_count(self.data_pointer()) };
+ if self.raw == 0 || self.header().references.fetch_sub(1, Ordering::Release) != 1 {
+ return;
}
+ std::sync::atomic::fence(Ordering::Acquire);
+ let length = self.header().length as usize;
+ // SAFETY: The last handle frees the allocation `allocate_string` made.
+ unsafe { std::alloc::dealloc(self.raw as *mut u8, layout(length)) };
}
}
diff --git a/Libraries/LibWeb/Rust/src/css/css_tokenizer.rs b/Libraries/LibWeb/Rust/src/css/css_tokenizer.rs
index db5ed14c9c4..8ac5b8e2517 100644
--- a/Libraries/LibWeb/Rust/src/css/css_tokenizer.rs
+++ b/Libraries/LibWeb/Rust/src/css/css_tokenizer.rs
@@ -693,12 +693,26 @@ impl PartialEq for ParserSource {
impl Eq for ParserSource {}
pub(crate) fn tokenize_for_parser<'a>(input: impl Into<TokenizerInput<'a>>) -> Vec<ParserToken> {
- let input = input.into();
+ tokenize_for_parser_with_comments(input.into(), Comments::AsWhitespace)
+}
+
+/// The tokens of `input`, whose comments tokenize as `comments` says.
+pub(crate) fn tokenize_for_parser_with_comments(input: TokenizerInput<'_>, comments: Comments) -> Vec<ParserToken> {
let mut tokens = Vec::with_capacity(input.len() / 3);
- ParserTokenFeed::new(input).fill(&mut tokens, usize::MAX);
+ ParserTokenFeed::with_comments(input, comments).fill(&mut tokens, usize::MAX);
tokens
}
+/// What a comment between two tokens tokenizes as.
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(crate) enum Comments {
+ /// A whitespace token, as in text an author wrote, for serializing custom properties as written.
+ AsWhitespace,
+ /// Nothing: in text the engine serialized from tokens, a comment only keeps two tokens apart
+ /// that would otherwise tokenize as one.
+ Separating,
+}
+
pub(crate) fn tokenize_for_parser_without_source<'a>(input: impl Into<TokenizerInput<'a>>) -> SmallParserTokenList {
tokenize_for_parser_without_source_internal(input)
}
@@ -847,8 +861,14 @@ pub(crate) struct ParserTokenFeed {
impl ParserTokenFeed {
pub(crate) fn new(input: TokenizerInput<'_>) -> Self {
+ Self::with_comments(input, Comments::AsWhitespace)
+ }
+
+ fn with_comments(input: TokenizerInput<'_>, comments: Comments) -> Self {
let source = Arc::new(SourceStorage::from_input(filter_code_points(input).as_input()));
- let cursor = Tokenizer::new(source.as_input()).cursor();
+ let mut tokenizer = Tokenizer::new(source.as_input());
+ tokenizer.comments = comments;
+ let cursor = tokenizer.cursor();
Self {
source,
cursor: Some(cursor),
@@ -1028,6 +1048,7 @@ struct Tokenizer<'a> {
current_code_point: u32,
position: SourcePosition,
prev_position: SourcePosition,
+ comments: Comments,
}
// The state a tokenizer resumes from, at the start of its next token.
@@ -1038,6 +1059,7 @@ struct TokenizerCursor {
current_code_point: u32,
position: SourcePosition,
prev_position: SourcePosition,
+ comments: Comments,
}
impl<'a> Tokenizer<'a> {
@@ -1049,6 +1071,7 @@ impl<'a> Tokenizer<'a> {
current_code_point: TOKENIZER_EOF,
position: SourcePosition::default(),
prev_position: SourcePosition::default(),
+ comments: Comments::AsWhitespace,
}
}
@@ -1060,6 +1083,7 @@ impl<'a> Tokenizer<'a> {
current_code_point: cursor.current_code_point,
position: cursor.position,
prev_position: cursor.prev_position,
+ comments: cursor.comments,
}
}
@@ -1070,6 +1094,7 @@ impl<'a> Tokenizer<'a> {
current_code_point: self.current_code_point,
position: self.position,
prev_position: self.prev_position,
+ comments: self.comments,
}
}
@@ -1712,7 +1737,7 @@ impl<'a> Tokenizer<'a> {
// This section describes how to consume a token from a stream of code points.
// It will return a single token of any type.
- let start_byte_offset = self.current_byte_offset();
+ let mut start_byte_offset = self.current_byte_offset();
// Consume comments.
self.consume_comments();
@@ -1720,7 +1745,12 @@ impl<'a> Tokenizer<'a> {
// AD-HOC: Preserve comments as whitespace tokens, for serializing custom properties.
let after_comments_byte_offset = self.current_byte_offset();
if after_comments_byte_offset != start_byte_offset {
- return Token::create(TokenType::Whitespace, start_byte_offset..self.current_byte_offset());
+ match self.comments {
+ Comments::AsWhitespace => {
+ return Token::create(TokenType::Whitespace, start_byte_offset..self.current_byte_offset());
+ }
+ Comments::Separating => start_byte_offset = after_comments_byte_offset,
+ }
}
// Consume the next input code point.
diff --git a/Libraries/LibWeb/Rust/src/css/custom_properties.rs b/Libraries/LibWeb/Rust/src/css/custom_properties.rs
index 74649403869..007b0766f61 100644
--- a/Libraries/LibWeb/Rust/src/css/custom_properties.rs
+++ b/Libraries/LibWeb/Rust/src/css/custom_properties.rs
@@ -7,6 +7,7 @@
//! Rust-owned custom-property data with the same structurally shared parent shape as the C++
//! `CustomPropertyData` shell.
+use crate::css::style_value::{RandomValueSharingPayload, UnresolvedPayload};
use std::borrow::Cow;
use std::cell::Cell;
use std::cell::RefCell;
@@ -15,6 +16,9 @@ use std::ffi::c_void;
use std::rc::Rc;
use std::sync::Arc;
+use crate::css::thin_slice::ThinSlice;
+use smallvec::SmallVec;
+
use ak::{ScopeGuard, Utf16FlyString};
use crate::css::calc::CanonicalNumericType;
@@ -35,9 +39,7 @@ use crate::css::parser::query_parser::{
FeatureComparison, FfiMediaEnvironment, MatchResult, StyleFeature, StyleRangeValue as ParsedStyleRangeValue,
parse_and_evaluate_media_if_condition, parse_and_evaluate_supports_if_condition, parse_style_range,
};
-use crate::css::parser::syntax::{
- SyntaxNode, SyntaxType, clone_syntax_handle, parse_syntax_values, parse_with_syntax_component_values,
-};
+use crate::css::parser::syntax::{SyntaxNode, SyntaxType, parse_syntax_values, parse_with_syntax_component_values};
use crate::css::parser::value_parser::{
FfiValueParsingContext, FfiValueParsingContextKind, ParseContext, RandomFunctionIndex, is_css_wide_keyword,
};
@@ -45,14 +47,13 @@ use crate::css::property_metadata::property_id;
use crate::css::serialize::{
normalized_component_values_equal, serialize_component_values_to_utf16, serialize_resolved_style_value_to_utf16,
};
+use crate::css::style_value::RetainedString;
use crate::css::style_value::RetainedStyleValueData;
use crate::css::style_value::StyleValueData;
use crate::fast_hash::FastMap;
include!(concat!(env!("OUT_DIR"), "/environment_variables_generated.rs"));
-// NB: Mirrors the lookup that Meta/Generators/generate_libweb_css_environment_variables.py
-// emitted before this series removed that generator.
pub(crate) fn environment_variable_is_known(name: &[u16]) -> bool {
ENVIRONMENT_VARIABLES
.iter()
@@ -109,16 +110,160 @@ pub(crate) struct CustomPropertyEntry {
pub(crate) name: Utf16FlyString,
pub(crate) value: RetainedStyleValueData,
pub(crate) important: bool,
+ /// Where the store holding the entry declared it among its own declarations, from one, or none
+ /// for a value it took in from the chain above it.
+ pub(crate) declared: Option<std::num::NonZeroU32>,
+}
+
+const _: () = assert!(size_of::<CustomPropertyEntry>() == 24);
+
+impl CustomPropertyEntry {
+ /// The entry, as one its store took in rather than declared.
+ fn taken_in(&self) -> Self {
+ Self {
+ declared: None,
+ ..self.clone()
+ }
+ }
+}
+
+/// A store's own entries, sorted by the identities of their names, which a lookup binary-searches:
+/// as small as the entries themselves, where a hash table holds a key beside each and room for
+/// more. A store holds a few entries.
+#[derive(Clone, Default)]
+pub(crate) struct CustomPropertyEntries(ThinSlice<CustomPropertyEntry>);
+
+/// The entries of a store being built, which [`Self::finished`] makes the store's.
+#[derive(Default)]
+struct CustomPropertyEntriesBuilder(Vec<CustomPropertyEntry>);
+
+impl CustomPropertyEntriesBuilder {
+ fn position(&self, name_raw: usize) -> Result<usize, usize> {
+ self.0
+ .binary_search_by_key(&name_raw, |entry| entry.name.raw_identity())
+ }
+
+ /// Enters `entry` under its name, `name_raw`, in place of the one there.
+ fn insert(&mut self, name_raw: usize, entry: CustomPropertyEntry) {
+ debug_assert_eq!(name_raw, entry.name.raw_identity());
+ match self.position(name_raw) {
+ Ok(index) => self.0[index] = entry,
+ Err(index) => self.0.insert(index, entry),
+ }
+ }
+
+ /// Enters `entries` in order as the store's declarations, each in place of one of its name.
+ fn declare(&mut self, entries: impl IntoIterator<Item = (usize, CustomPropertyEntry)>) {
+ for (position, (name_raw, mut entry)) in entries.into_iter().enumerate() {
+ let position = u32::try_from(position + 1).expect("a store declares fewer than 2^32 custom properties");
+ entry.declared = std::num::NonZeroU32::new(position);
+ self.insert(name_raw, entry);
+ }
+ }
+
+ /// Enters a copy of `entry`, as taken in, where no entry of its name is.
+ fn insert_if_vacant(&mut self, entry: &CustomPropertyEntry) {
+ if let Err(index) = self.position(entry.name.raw_identity()) {
+ self.0.insert(index, entry.taken_in());
+ }
+ }
+
+ fn finished(self) -> CustomPropertyEntries {
+ CustomPropertyEntries(self.0.into_iter().collect())
+ }
+}
+
+impl CustomPropertyEntries {
+ fn position(&self, name_raw: usize) -> Result<usize, usize> {
+ self.0
+ .binary_search_by_key(&name_raw, |entry| entry.name.raw_identity())
+ }
+
+ pub(crate) fn get(&self, name_raw: &usize) -> Option<&CustomPropertyEntry> {
+ self.position(*name_raw).ok().map(|index| &self.0[index])
+ }
+
+ pub(crate) fn len(&self) -> usize {
+ self.0.len()
+ }
+
+ pub(crate) fn is_empty(&self) -> bool {
+ self.0.is_empty()
+ }
+
+ pub(crate) fn iter(&self) -> impl Iterator<Item = (usize, &CustomPropertyEntry)> {
+ self.0.iter().map(|entry| (entry.name.raw_identity(), entry))
+ }
+
+ pub(crate) fn keys(&self) -> impl Iterator<Item = usize> + '_ {
+ self.0.iter().map(|entry| entry.name.raw_identity())
+ }
+
+ pub(crate) fn values(&self) -> impl Iterator<Item = &CustomPropertyEntry> {
+ self.0.iter()
+ }
+
+ /// A builder holding these entries, as taken in where `taken_in`.
+ fn to_builder(&self, taken_in: bool) -> CustomPropertyEntriesBuilder {
+ CustomPropertyEntriesBuilder(
+ self.0
+ .iter()
+ .map(|entry| if taken_in { entry.taken_in() } else { entry.clone() })
+ .collect(),
+ )
+ }
+}
+
+impl std::ops::Index<&usize> for CustomPropertyEntries {
+ type Output = CustomPropertyEntry;
+
+ fn index(&self, name_raw: &usize) -> &CustomPropertyEntry {
+ self.get(name_raw).expect("a store holds the entry asked for")
+ }
+}
+
+impl FromIterator<(usize, CustomPropertyEntry)> for CustomPropertyEntries {
+ fn from_iter<I: IntoIterator<Item = (usize, CustomPropertyEntry)>>(entries: I) -> Self {
+ let mut collected = CustomPropertyEntriesBuilder::default();
+ for (name_raw, entry) in entries {
+ collected.insert(name_raw, entry);
+ }
+ collected.finished()
+ }
}
pub struct CustomPropertyStore {
- pub(crate) own_values: FastMap<usize, CustomPropertyEntry>,
- pub(crate) declared_names: Vec<usize>,
+ /// The values the store holds itself: those it declares, each knowing where among its
+ /// declarations, and those it took in from the chain above it.
+ pub(crate) own_values: CustomPropertyEntries,
parent: Option<Arc<CustomPropertyStore>>,
inheritance_parent: Option<Arc<CustomPropertyStore>>,
+ /// For the values an element's animations sample, the store of the environment they lie over,
+ /// whose values this one copies.
+ animation_overlay_base: Option<Arc<CustomPropertyStore>>,
ancestor_count: u8,
}
+// NB: The host holds a store as its custom-property environment itself, so this is all an
+// environment takes.
+const _: () = assert!(size_of::<CustomPropertyStore>() == 40);
+
+impl crate::heap_size::HeapSize for CustomPropertyStore {
+ /// The store's table, its names and the stores it lies over, each counted once. A name's text
+ /// belongs to the process's fly strings and is not counted.
+ fn heap_size(&self, sizer: &mut crate::heap_size::HeapSizer) -> usize {
+ self.own_values.0.heap_bytes()
+ + self
+ .own_values
+ .values()
+ .map(|entry| entry.value.heap_size(sizer))
+ .sum::<usize>()
+ + self.parent.heap_size(sizer)
+ + self.inheritance_parent.heap_size(sizer)
+ + self.animation_overlay_base.heap_size(sizer)
+ }
+}
+
// SAFETY: Store nodes and their entries are immutable after construction. Style workers only
// borrow the graph while resolving substitution text; the C++-owned raw Arc reference remains
// alive until every worker in the blocking batch has joined, so destruction stays on the main
@@ -166,10 +311,7 @@ impl CustomPropertyValueToFinalize<'_> {
match self {
Self::StyleValue(value) => matches!(
value.data(),
- StyleValueData::Unresolved {
- contains_attr_tainted_values: true,
- ..
- }
+ StyleValueData::Unresolved(unresolved) if unresolved.contains_attr_tainted_values
),
Self::SubstitutedComponents {
contains_attr_tainted_values,
@@ -184,9 +326,10 @@ const MAX_REGISTERED_VALUE_PARSES: usize = 4096;
#[derive(PartialEq)]
struct RegisteredCustomProperty {
- syntax: SyntaxNode,
+ /// The syntax the registration's rule or call parsed, shared with it.
+ syntax: Arc<SyntaxNode>,
inherits: bool,
- initial_source: Option<Vec<u16>>,
+ initial_source: Option<RetainedString>,
/// The initial value as it computes, against the document rather than any element: the host
/// computes it, memoizes it on the registration for every reader, and publishes it with the
/// registration. The guaranteed-invalid value for a registration without one.
@@ -263,7 +406,8 @@ pub struct FfiCustomPropertyRegistryContext {
/// One of an element's attributes an `attr()` reads: its local name, and its value's text.
pub(crate) struct SubstitutionAttribute<'a> {
pub(crate) name: &'a [u16],
- pub(crate) value: &'a [u16],
+ /// The host's string of the value, which the element's attribute holds.
+ pub(crate) value: &'a crate::css::retained_fly_string::RetainedUtf16FlyString,
}
/// One declaration in the body of a custom function, as its conditions select it.
@@ -273,6 +417,12 @@ pub(crate) struct SubstitutionFunctionDeclaration {
includes_substitution: bool,
}
+impl SubstitutionFunctionDeclaration {
+ pub(crate) fn tokens(&self) -> &[ComponentValue] {
+ self.tokens.as_ref()
+ }
+}
+
/// A definition visible to a caller scope, indexed in the prepared definition list.
#[derive(Clone, Copy)]
pub(crate) struct CustomFunctionVisibility {
@@ -282,9 +432,8 @@ pub(crate) struct CustomFunctionVisibility {
/// That a call from a scope names a function: the definition its name dereferences to there, as
/// a tree-scoped reference.
-#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub struct FfiSubstitutionFunctionVisibility {
+pub struct SubstitutionFunctionVisibility {
pub caller_scope_identity: usize,
pub function_identity: u64,
}
@@ -326,8 +475,9 @@ impl CustomPropertyRegistry {
self.registrations.get(&Utf16FlyString::from_utf16(name))
}
- pub(crate) fn name_is_registered(&self, name: &[u16]) -> bool {
- self.registration(name).is_some()
+ /// Whether the custom property `name` names is registered.
+ pub(crate) fn is_registered(&self, name: &Utf16FlyString) -> bool {
+ self.registrations.contains_key(name)
}
/// Whether a name has the same effective registration in two document registries.
@@ -335,6 +485,26 @@ impl CustomPropertyRegistry {
self.registration(name) == other.registration(name)
}
+ /// The names whose effective registration differs between `previous` and this registry: those
+ /// registered, unregistered or registered otherwise since.
+ pub(crate) fn names_registered_otherwise_than(&self, previous: &Self) -> Vec<Utf16FlyString> {
+ let moved_in = |registry: &Self, other: &Self| {
+ registry
+ .registrations
+ .iter()
+ .filter(|(name, registration)| other.registrations.get(*name) != Some(*registration))
+ .map(|(name, _)| name.clone())
+ .collect::<Vec<_>>()
+ };
+ let mut names = moved_in(self, previous);
+ names.extend(
+ moved_in(previous, self)
+ .into_iter()
+ .filter(|name| !self.registrations.contains_key(name)),
+ );
+ names
+ }
+
/// Whether a custom property of this name inherits: only a registration can say it does not.
pub(crate) fn name_inherits(&self, name: &Utf16FlyString) -> bool {
self.registrations
@@ -346,7 +516,14 @@ impl CustomPropertyRegistry {
/// one, which its values compute against.
pub(crate) fn name_has_syntax(&self, name: &[u16]) -> bool {
self.registration(name)
- .is_some_and(|registration| !matches!(registration.syntax, SyntaxNode::Universal))
+ .is_some_and(|registration| !matches!(*registration.syntax, SyntaxNode::Universal))
+ }
+
+ /// [`Self::name_has_syntax`], for the custom property `name` names.
+ pub(crate) fn has_syntax(&self, name: &Utf16FlyString) -> bool {
+ self.registrations
+ .get(name)
+ .is_some_and(|registration| !matches!(*registration.syntax, SyntaxNode::Universal))
}
/// Whether a registration's syntax permits smooth interpolation.
@@ -367,6 +544,26 @@ impl CustomPropertyRegistry {
.is_some_and(|registration| is_interpolable(&registration.syntax))
}
+ /// https://drafts.csswg.org/css-variables-2/#invalid-at-computed-value-time
+ /// What a custom property computes to where it is invalid at computed-value time: as `unset`, what it
+ /// inherits from `inherited` where its registration inherits, and otherwise its initial value.
+ pub(crate) fn invalid_at_computed_value_time(
+ &self,
+ name: &crate::css::retained_fly_string::RetainedUtf16FlyString,
+ inherited: Option<&CustomPropertyStore>,
+ ) -> RetainedStyleValueData {
+ let inherits = self
+ .registration(name.to_utf16().as_ref())
+ .is_none_or(|registration| registration.inherits);
+ inherited
+ .filter(|_| inherits)
+ .and_then(|inherited| inherited.get(name.raw()))
+ .map_or_else(
+ || self.initial_value(name.to_utf16().as_ref()),
+ |entry| entry.value.clone(),
+ )
+ }
+
/// A custom property's initial value: what its registration's initial value computes to, and
/// the guaranteed-invalid value for an unregistered name or a registration without one.
pub(crate) fn initial_value(&self, name: &[u16]) -> RetainedStyleValueData {
@@ -414,13 +611,17 @@ pub(crate) struct CustomPropertyFinalization<'a> {
pub(crate) type DrawRandomBaseValue<'a> = dyn Fn(&[u16], bool) -> f64 + 'a;
/// What computing registered values read of their element beyond the fonts of its lengths: the
-/// viewport, its place among its siblings, and the container-relative units it resolved against
-/// its query containers, as a `container_relative_length_unit_mask`.
+/// viewport, its place among its siblings, the container-relative units it resolved against its
+/// query containers, as a `container_relative_length_unit_mask`, the root element's font, and the
+/// used color scheme.
#[derive(Clone, Copy, Default)]
pub(crate) struct RegisteredValueReads {
pub(crate) viewport: bool,
pub(crate) sibling_position: bool,
pub(crate) container_unit_mask: u8,
+ pub(crate) root_font: crate::css::style_compute::RootFontReads,
+ pub(crate) font_metrics: bool,
+ pub(crate) color_scheme: bool,
}
impl std::ops::BitOrAssign for RegisteredValueReads {
@@ -428,6 +629,9 @@ impl std::ops::BitOrAssign for RegisteredValueReads {
self.viewport |= other.viewport;
self.sibling_position |= other.sibling_position;
self.container_unit_mask |= other.container_unit_mask;
+ self.root_font = self.root_font.max(other.root_font);
+ self.font_metrics |= other.font_metrics;
+ self.color_scheme |= other.color_scheme;
}
}
@@ -463,8 +667,8 @@ impl CustomPropertyRegistry {
}
let parsed = match value.data() {
- StyleValueData::Unresolved { components, .. } => {
- self.parse_registered_value(registration, components.as_slice())
+ StyleValueData::Unresolved(unresolved_payload) => {
+ self.parse_registered_value(registration, &unresolved_payload.components())
}
_ => {
let source = serialize_resolved_style_value_to_utf16(value.data());
@@ -511,7 +715,9 @@ impl CustomPropertyRegistry {
) => Some(parse_substituted_value(
parse_context,
property_id::CUSTOM,
- &serialize_tokens(&components),
+ // NB: The value keeps this text alone and tokenizes it where it is read, so it is the
+ // serialization that tokenizes back to the components.
+ &serialize_component_values_to_utf16(&components, ComponentSerializationMode::Retokenize),
&components,
contains_attr_tainted_values,
)),
@@ -578,7 +784,7 @@ impl CustomPropertyRegistry {
// guaranteed-invalid value; any other to its inherited value or its initial value, as if
// its value had been specified as unset.
let syntax_registration =
- registration.filter(|registration| !matches!(registration.syntax, SyntaxNode::Universal));
+ registration.filter(|registration| !matches!(*registration.syntax, SyntaxNode::Universal));
let invalid_fallback = || match syntax_registration {
Some(registration) if registration.inherits => inherited_value(),
Some(_) => initial(),
@@ -598,7 +804,10 @@ impl CustomPropertyRegistry {
// Without the element's lengths the value stays as parsed, as the host leaves one it has
// no computed style to compute against.
let Some(length) = finalization.length else {
- return Ok((parsed, RegisteredValueReads::default()));
+ return Ok((
+ attr_tainted(parsed, contains_attr_tainted_values),
+ RegisteredValueReads::default(),
+ ));
};
let dependencies = crate::css::style_compute::collect_external_value_dependencies(parsed.data());
let random_base_values = random_base_values_for_registered_value(parsed.data(), finalization);
@@ -621,30 +830,36 @@ impl CustomPropertyRegistry {
viewport: context.resolved_viewport_relative_length.get(),
sibling_position: dependencies.uses_tree_counting_function,
container_unit_mask: dependencies.container_relative_length_unit_mask,
+ root_font: dependencies.root_font_reads,
+ font_metrics: dependencies.font_metric_relative_length,
+ color_scheme: dependencies.color_scheme_dependent,
};
- if !contains_attr_tainted_values {
- return Ok((computed, reads));
- }
+ Ok((attr_tainted(computed, contains_attr_tainted_values), reads))
+ }
+}
- // A value an attr() substituted into stays tainted, as an unresolved value carrying what
- // it computed to.
- let source = crate::css::serialize::serialize_resolved_style_value_to_utf16(computed.data());
- let mut wrapped = crate::css::parser::value_parser::unresolved_value_from_string(
- &source,
- crate::css::parser::arbitrary_substitution::SubstitutionFunctionsPresence::default(),
- );
- let StyleValueData::Unresolved {
- contains_attr_tainted_values,
- parsed_value,
- ..
- } = &mut wrapped
- else {
- unreachable!("an unresolved value is built");
- };
- *contains_attr_tainted_values = true;
- *parsed_value = computed;
- Ok((RetainedStyleValueData::from_owned(wrapped), reads))
+/// A registered value an attr() substituted into, where `tainted` says it did, which stays
+/// tainted as an unresolved value carrying what it computed to.
+fn attr_tainted(value: RetainedStyleValueData, tainted: bool) -> RetainedStyleValueData {
+ if !tainted {
+ return value;
}
+ let source = crate::css::serialize::serialize_resolved_style_value_to_utf16(value.data());
+ let mut wrapped = crate::css::parser::value_parser::unresolved_value_from_string(
+ &source,
+ crate::css::parser::arbitrary_substitution::SubstitutionFunctionsPresence::default(),
+ );
+ let StyleValueData::Unresolved(unresolved_payload) = &mut wrapped else {
+ unreachable!("an unresolved value is built");
+ };
+ let UnresolvedPayload {
+ contains_attr_tainted_values,
+ parsed_value,
+ ..
+ } = unresolved_payload.payload_mut();
+ *contains_attr_tainted_values = true;
+ *parsed_value = value;
+ RetainedStyleValueData::from_owned(wrapped)
}
/// The random base values a registered value draws from once parsed after substitution. Its random
@@ -657,12 +872,15 @@ fn random_base_values_for_registered_value(
) -> Vec<crate::css::style_compute::FfiRandomBaseValue> {
let published = finalization.random_base_values;
let kind = |sharing: *const StyleValueData| match unsafe { &*sharing } {
- StyleValueData::RandomValueSharing {
- is_auto,
- name,
- element_shared,
- ..
- } => Some((*is_auto, name, *element_shared)),
+ StyleValueData::RandomValueSharing(random_value_sharing_payload) => {
+ let RandomValueSharingPayload {
+ is_auto,
+ name,
+ element_shared,
+ ..
+ } = &**random_value_sharing_payload;
+ Some((*is_auto, name, *element_shared))
+ }
_ => None,
};
let mut sharings = Vec::new();
@@ -691,47 +909,83 @@ impl CustomPropertyStore {
/// An element's animated custom property values laid over its own environment, `base`.
fn animation_overlay(
animated: impl ExactSizeIterator<Item = (usize, CustomPropertyEntry)>,
- base: Option<&Self>,
+ base: Option<Arc<Self>>,
) -> Self {
- let (mut own_values, parent, inheritance_parent, ancestor_count) = match base {
+ let (mut own_values, parent, inheritance_parent, ancestor_count) = match base.as_deref() {
Some(base) => (
- base.own_values.clone(),
+ base.own_values.to_builder(true),
base.parent.clone(),
base.inheritance_parent.clone(),
base.ancestor_count,
),
- None => (FastMap::default(), None, None, 0),
+ None => (CustomPropertyEntriesBuilder::default(), None, None, 0),
};
- let mut declared_names = Vec::with_capacity(animated.len());
- for (name_raw, entry) in animated {
- declared_names.push(name_raw);
- own_values.insert(name_raw, entry);
- }
+ own_values.declare(animated);
Self {
- own_values,
- declared_names,
+ own_values: own_values.finished(),
ancestor_count,
parent,
inheritance_parent,
+ animation_overlay_base: base,
}
}
- /// The values `overlay`, an animation overlay, laid over its base, laid over `base` instead.
- pub(crate) fn animated_values_over(overlay: &Self, base: Option<&Self>) -> Self {
- let animated = overlay
- .declared_names
+ /// This animation overlay's animated values over `base`, the custom properties a pass resolved
+ /// beneath the element's animations, which the host sampled over the ones before: the names the
+ /// element inherits read what the pass resolved.
+ pub(crate) fn animation_overlay_over(self: &Arc<Self>, base: Option<&Arc<Self>>) -> Arc<Self> {
+ let sampled_over = self.animation_overlay_base.as_ref();
+ let moved = match (sampled_over, base) {
+ (None, None) => false,
+ (Some(sampled_over), Some(base)) => {
+ !Arc::ptr_eq(sampled_over, base) && !sampled_over.holds_same_values_as(base)
+ }
+ _ => true,
+ };
+ if !moved {
+ return self.clone();
+ }
+ let animated: SmallVec<[(usize, CustomPropertyEntry); 8]> = self
+ .own_values
.iter()
- .map(|name_raw| (*name_raw, overlay.own_values[name_raw].clone()));
- Self::animation_overlay(animated, base)
+ .filter(|(name_raw, entry)| {
+ !sampled_over.is_some_and(|sampled_over| {
+ sampled_over.value_is_identical(*name_raw, entry.value.pointer().cast())
+ })
+ })
+ .map(|(name_raw, entry)| (name_raw, entry.clone()))
+ .collect();
+ Arc::new(Self::animation_overlay(animated.into_iter(), base.cloned()))
}
pub(crate) fn parent(&self) -> Option<&Arc<CustomPropertyStore>> {
self.parent.as_ref()
}
- /// The store this one was built over, whichever of its values it took in.
- pub(crate) fn inheritance_parent(&self) -> Option<&Arc<CustomPropertyStore>> {
- self.inheritance_parent.as_ref()
+ /// The names of the custom properties the store declares itself, in declaration order.
+ pub(crate) fn declared_names(&self) -> SmallVec<[usize; 8]> {
+ let mut declared: SmallVec<[(std::num::NonZeroU32, usize); 8]> = self
+ .own_values
+ .iter()
+ .filter_map(|(name_raw, entry)| Some((entry.declared?, name_raw)))
+ .collect();
+ declared.sort_unstable();
+ declared.into_iter().map(|(_, name_raw)| name_raw).collect()
+ }
+
+ /// How many custom properties the store declares itself.
+ pub(crate) fn declared_count(&self) -> usize {
+ self.own_values
+ .values()
+ .filter(|entry| entry.declared.is_some())
+ .count()
+ }
+
+ /// Whether the store declares `name_raw` itself.
+ pub(crate) fn declares(&self, name_raw: usize) -> bool {
+ self.own_values
+ .get(&name_raw)
+ .is_some_and(|entry| entry.declared.is_some())
}
pub(crate) fn get(&self, name_raw: usize) -> Option<&CustomPropertyEntry> {
@@ -740,6 +994,26 @@ impl CustomPropertyStore {
.or_else(|| self.parent.as_ref()?.get(name_raw))
}
+ /// Whether the store, or a store it is built over, holds a value of `name`.
+ pub(crate) fn holds(&self, name: &Utf16FlyString) -> bool {
+ self.get_by_name_with_owner(name).is_some()
+ }
+
+ /// The identity of the value `name` resolves to in this store, zero for a name it holds no
+ /// value of, or none where the value says more than its identity: a lone CSS-wide keyword,
+ /// which resolves against the store holding it, or a value still waiting on a substitution.
+ pub(crate) fn resolved_value_identity(&self, name: &Utf16FlyString) -> Option<usize> {
+ let Some((entry, _)) = self.get_by_name_with_owner(name) else {
+ return Some(0);
+ };
+ if let Some(StyleValueData::Unresolved(unresolved)) = entry.value.optional_data()
+ && (unresolved.presence().has_any() || unresolved.facts().is_lone_css_wide_keyword())
+ {
+ return None;
+ }
+ Some(entry.value.pointer() as usize)
+ }
+
fn get_by_name_with_owner(&self, name: &Utf16FlyString) -> Option<(&CustomPropertyEntry, &CustomPropertyStore)> {
self.own_values
.get(&name.raw_identity())
@@ -758,22 +1032,17 @@ impl CustomPropertyStore {
return None;
}
let inherits = |entry: &CustomPropertyEntry| registry.name_inherits(&entry.name);
- let own_values: FastMap<usize, CustomPropertyEntry> = self
+ let own_values: CustomPropertyEntries = self
.own_values
.iter()
.filter(|(_, entry)| inherits(entry))
- .map(|(&name_raw, entry)| (name_raw, entry.clone()))
+ .map(|(name_raw, entry)| (name_raw, entry.clone()))
.collect();
Some(Arc::new(Self {
- declared_names: self
- .declared_names
- .iter()
- .copied()
- .filter(|name_raw| own_values.contains_key(name_raw))
- .collect(),
own_values,
parent: self.parent.clone(),
inheritance_parent: self.inheritance_parent.clone(),
+ animation_overlay_base: None,
ancestor_count: self.ancestor_count,
}))
}
@@ -781,21 +1050,32 @@ impl CustomPropertyStore {
/// Whether the store holds the same values as `other`, built over the same store and chained to
/// the same parent.
pub(crate) fn holds_same_values_as(&self, other: &Self) -> bool {
- let same = |first: &Option<Arc<Self>>, second: &Option<Arc<Self>>| match (first, second) {
+ let same_inheritance = match (&self.inheritance_parent, &other.inheritance_parent) {
(None, None) => true,
- (Some(first), Some(second)) => Arc::ptr_eq(first, second),
+ (Some(first), Some(second)) => Arc::ptr_eq(first, second) || first.holds_same_values_as(second),
_ => false,
};
- same(&self.parent, &other.parent)
- && same(&self.inheritance_parent, &other.inheritance_parent)
- && self.declared_names == other.declared_names
- && self.own_values.len() == other.own_values.len()
- && self.own_values.iter().all(|(name_raw, entry)| {
- other.own_values.get(name_raw).is_some_and(|other_entry| {
- other_entry.important == entry.important
- && crate::css::style_value::retained_style_values_equal(&other_entry.value, &entry.value)
+ if !same_inheritance || self.declared_names() != other.declared_names() {
+ return false;
+ }
+ // NB: What a store took in from the chain above it, and which stores stand there, depends on how it was built:
+ // stores hold the same where every name reads the same, down to a store their chains share.
+ fn chain(store: &CustomPropertyStore) -> impl Iterator<Item = &CustomPropertyStore> {
+ std::iter::successors(Some(store), |store| store.parent.as_deref())
+ }
+ let reads_alike_in_both = |from: &Self, shared_with: &Self| {
+ chain(from)
+ .take_while(|store| !chain(shared_with).any(|shared| std::ptr::eq(*store, shared)))
+ .flat_map(|store| store.own_values.iter())
+ .all(|(name_raw, _)| match (self.get(name_raw), other.get(name_raw)) {
+ (Some(first), Some(second)) => {
+ first.important == second.important
+ && crate::css::style_value::retained_style_values_equal(&first.value, &second.value)
+ }
+ _ => false,
})
- })
+ };
+ reads_alike_in_both(self, other) && reads_alike_in_both(other, self)
}
/// Whether a child inherits every entry of this store.
@@ -818,32 +1098,24 @@ impl CustomPropertyStore {
mut parent: Option<Arc<CustomPropertyStore>>,
entries: Vec<(usize, CustomPropertyEntry)>,
) -> Arc<CustomPropertyStore> {
- let mut own_values = FastMap::with_capacity_and_hasher(entries.len(), Default::default());
- let mut declared_names = Vec::with_capacity(entries.len());
- for (name_raw, entry) in entries {
- declared_names.push(name_raw);
- own_values.insert(name_raw, entry);
- }
+ let mut own_values = CustomPropertyEntriesBuilder(Vec::with_capacity(entries.len()));
+ own_values.declare(entries);
let inheritance_parent = parent.clone();
let ancestor_count = if let Some(current_parent) = parent.clone() {
if current_parent.ancestor_count >= MAX_ANCESTOR_COUNT - 1 {
let mut ancestor = Some(current_parent.as_ref());
while let Some(current) = ancestor {
- for (&name_raw, entry) in &current.own_values {
- if let std::collections::hash_map::Entry::Vacant(slot) = own_values.entry(name_raw) {
- slot.insert(entry.clone());
- }
+ for entry in current.own_values.values() {
+ own_values.insert_if_vacant(entry);
}
ancestor = current.parent.as_deref();
}
parent = None;
0
} else if current_parent.own_values.len() <= ABSORB_THRESHOLD {
- for (&name_raw, entry) in &current_parent.own_values {
- if let std::collections::hash_map::Entry::Vacant(slot) = own_values.entry(name_raw) {
- slot.insert(entry.clone());
- }
+ for entry in current_parent.own_values.values() {
+ own_values.insert_if_vacant(entry);
}
parent = current_parent.parent.clone();
parent.as_ref().map_or(0, |parent| parent.ancestor_count + 1)
@@ -855,10 +1127,10 @@ impl CustomPropertyStore {
};
Arc::new(CustomPropertyStore {
- own_values,
- declared_names,
+ own_values: own_values.finished(),
inheritance_parent,
parent,
+ animation_overlay_base: None,
ancestor_count,
})
}
@@ -881,6 +1153,7 @@ impl CustomPropertyStore {
name: source.name.clone(),
value,
important: source.important,
+ declared: None,
},
)
})
@@ -907,6 +1180,7 @@ impl CustomPropertyStore {
)
},
important,
+ declared: None,
},
)
})
@@ -920,6 +1194,8 @@ const MAX_SUBSTITUTION_RECURSION_DEPTH: u32 = 64;
pub(crate) enum NativeVarResolution {
Resolved {
+ /// The substituted components, serialized to tokenize back to them where comments only keep
+ /// tokens apart.
source: Vec<u16>,
contains_attr_tainted_values: bool,
},
@@ -1025,7 +1301,7 @@ struct ASFResolutionContext<'a> {
/// The queried element's sibling count and index, which tree-counting functions in a style
/// query resolve against, where they are known.
style_query_tree_counting: Option<(u64, u64)>,
- /// Where the custom properties and sibling position a style query reads are noted, for the host to record.
+ /// Where whether a style query reads the sibling position is noted.
style_query_dependencies: Option<&'a mut Option<Box<StyleQueryDependencies>>>,
custom_property_finalization: CustomPropertyFinalization<'a>,
registered_value_reads: Option<&'a mut RegisteredValueReads>,
@@ -1037,12 +1313,6 @@ struct ASFResolutionContext<'a> {
}
impl ASFResolutionContext<'_> {
- fn note_style_query_dependency(&mut self, name: &[u16]) {
- if let Some(dependencies) = self.style_query_dependencies.as_deref_mut() {
- dependencies.get_or_insert_default().note(name);
- }
- }
-
fn note_style_query_sibling_position_dependency(&mut self) {
if let Some(reads) = self.registered_value_reads.as_deref_mut() {
reads.sibling_position = true;
@@ -1053,54 +1323,16 @@ impl ASFResolutionContext<'_> {
}
}
-/// The custom properties and sibling position style queries read in one resolution.
+/// What the style queries of one resolution read beside the custom properties: whether they
+/// read the element's sibling position.
#[derive(Clone, Default)]
pub(crate) struct StyleQueryDependencies {
- names: Vec<Vec<u16>>,
pub(crate) sibling_position: bool,
}
-impl StyleQueryDependencies {
- fn note(&mut self, name: &[u16]) {
- if !self.names.iter().any(|noted| noted == name) {
- self.names.push(name.to_vec());
- }
- }
-
- pub(crate) fn extend(&mut self, other: &Self) {
- self.sibling_position |= other.sibling_position;
- for name in other.names() {
- self.note(name);
- }
- }
-
- pub(crate) fn names(&self) -> impl Iterator<Item = &[u16]> {
- self.names.iter().map(Vec::as_slice)
- }
-}
-
-/// Visits each custom property the style queries of a resolution read, and frees them.
-///
-/// # Safety
-/// `dependencies` must be null or what a resolution left in its `style_query_dependencies`.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_style_query_dependencies_take(
- dependencies: *mut c_void,
- context: *mut c_void,
- visit: unsafe extern "C" fn(*mut c_void, FfiUtf16View),
-) {
- if dependencies.is_null() {
- return;
- }
- let dependencies = unsafe { Box::from_raw(dependencies.cast::<StyleQueryDependencies>()) };
- for name in dependencies.names() {
- unsafe {
- visit(context, FfiUtf16View::from_utf16(name));
- }
- }
-}
-
-type CustomPropertyTokenCache = HashMap<*const StyleValueData, Arc<ComponentValueList>>;
+/// The tokens of each value by its address, with the value where nothing else keeps it for as long as the cache.
+type CustomPropertyTokenCache =
+ HashMap<*const StyleValueData, (Option<RetainedStyleValueData>, Arc<ComponentValueList>)>;
pub(crate) struct VarResolutionEnvironment<'a> {
attributes: HashMap<Vec<u16>, Vec<u16>>,
@@ -1121,7 +1353,7 @@ fn source_ends_with_comment(source: crate::css::css_tokenizer::TokenizerInput<'_
}
}
-fn single_css_wide_keyword(tokens: &[ComponentValue]) -> Option<&[u16]> {
+pub(crate) fn single_css_wide_keyword(tokens: &[ComponentValue]) -> Option<&[u16]> {
let [value] = trim_whitespace(tokens) else {
return None;
};
@@ -1134,75 +1366,90 @@ fn single_css_wide_keyword(tokens: &[ComponentValue]) -> Option<&[u16]> {
.then_some(keyword)
}
-fn tokens_for_unresolved_custom_property_value(data: &StyleValueData) -> (ComponentValueSlice<'_>, bool, bool) {
- let StyleValueData::Unresolved {
- components,
- presence_attr,
- presence_dashed_function,
- presence_env,
- presence_if,
- presence_inherit,
- presence_var,
- contains_attr_tainted_values,
- source_text,
- ..
- } = data
- else {
- unreachable!("expected an unresolved custom property value");
- };
+/// The tokens of an unresolved custom property value as one read has them.
+struct CustomPropertyTokens {
+ components: ComponentValueList,
+ /// Whether the text ends with a comment, after which trailing whitespace is discarded.
+ trims_trailing_whitespace: bool,
+}
+
+impl CustomPropertyTokens {
+ fn slice(&self) -> ComponentValueSlice<'_> {
+ let values = ComponentValueSlice::from(&self.components);
+ if self.trims_trailing_whitespace {
+ values.trim_end_whitespace()
+ } else {
+ values
+ }
+ }
- let mut values = components.as_counted_slice();
+ fn into_list(self) -> ComponentValueList {
+ if self.trims_trailing_whitespace {
+ self.slice().to_owned()
+ } else {
+ self.components
+ }
+ }
+}
- // Discard trailing comments
- if source_ends_with_comment(TokenizerInput::from(source_text)) {
- values = values.trim_end_whitespace();
+fn tokens_for_unresolved_custom_property_value(unresolved_payload: &UnresolvedPayload) -> CustomPropertyTokens {
+ CustomPropertyTokens {
+ components: unresolved_payload.components(),
+ // Discard trailing comments
+ trims_trailing_whitespace: source_ends_with_comment(unresolved_payload.source_text()),
}
+}
- (
- values,
- *presence_var
- || *presence_attr
- || *presence_dashed_function
- || *presence_env
- || *presence_if
- || *presence_inherit,
- *contains_attr_tainted_values,
- )
+/// The tokens of a value a resolution reads, which it tokenizes once however often it reads them.
+/// The value must outlive the resolution's token cache.
+fn cached_value_tokens(data: &StyleValueData, context: &mut ASFResolutionContext<'_>) -> Arc<ComponentValueList> {
+ cached_tokens(data, None, context)
}
-fn resolve_typed_custom_property_value(
+/// The tokens of `value`, which the resolution's token cache holds as long as it holds them.
+fn cached_held_value_tokens(
+ value: &RetainedStyleValueData,
+ context: &mut ASFResolutionContext<'_>,
+) -> Arc<ComponentValueList> {
+ cached_tokens(value.data(), Some(value), context)
+}
+
+fn cached_tokens(
data: &StyleValueData,
+ held: Option<&RetainedStyleValueData>,
context: &mut ASFResolutionContext<'_>,
-) -> TokenResolution {
+) -> Arc<ComponentValueList> {
let key = std::ptr::from_ref(data);
- if let Some(tokens) = context.token_cache.as_deref().and_then(|cache| cache.get(&key)) {
- return TokenResolution::Resolved(tokens.as_ref().clone());
+ if let Some((_, tokens)) = context.token_cache.as_deref().and_then(|cache| cache.get(&key)) {
+ return Arc::clone(tokens);
}
- let source = crate::css::serialize::serialize_style_value_to_utf16(data);
- let tokens: Arc<ComponentValueList> = parse_substitution_values(&source)
- .expect("serialized style values tokenize correctly")
- .into();
+ let tokens: Arc<ComponentValueList> = match data {
+ StyleValueData::Unresolved(unresolved_payload) => {
+ tokens_for_unresolved_custom_property_value(unresolved_payload).into_list()
+ }
+ _ => parse_substitution_values(&crate::css::serialize::serialize_style_value_to_utf16(data))
+ .expect("serialized style values tokenize correctly"),
+ }
+ .into();
if let Some(cache) = context.token_cache.as_deref_mut() {
- cache.insert(key, Arc::clone(&tokens));
+ cache.insert(key, (held.cloned(), Arc::clone(&tokens)));
}
- TokenResolution::Resolved(tokens.as_ref().clone())
+ tokens
}
/// Tokens, substitution-function presence, and attribute reads for a function value.
fn tokens_for_function_value(data: &StyleValueData) -> (ComponentValueList, bool, bool) {
- if let StyleValueData::Unresolved {
- components,
- presence_attr,
- presence_dashed_function,
- presence_env,
- presence_if,
- presence_inherit,
- presence_var,
- ..
- } = data
- {
+ if let StyleValueData::Unresolved(unresolved_payload) = data {
+ let presence_attr = &unresolved_payload.presence().attr;
+ let presence_dashed_function = &unresolved_payload.presence().dashed_function;
+ let presence_env = &unresolved_payload.presence().env;
+ let presence_if = &unresolved_payload.presence().if_;
+ let presence_inherit = &unresolved_payload.presence().inherit;
+ let presence_var = &unresolved_payload.presence().var;
return (
- components.as_counted_slice().trim_whitespace().to_owned(),
+ ComponentValueSlice::from(&unresolved_payload.components())
+ .trim_whitespace()
+ .to_owned(),
*presence_var
|| *presence_attr
|| *presence_dashed_function
@@ -1265,7 +1512,7 @@ pub(crate) fn prepare_var_resolution_environment<'a>(
) -> VarResolutionEnvironment<'a> {
let attributes = attributes
.iter()
- .map(|attribute| (attribute.name.to_vec(), attribute.value.to_vec()))
+ .map(|attribute| (attribute.name.to_vec(), attribute.value.to_utf16().into_owned()))
.collect();
VarResolutionEnvironment {
attributes,
@@ -1315,12 +1562,16 @@ fn compute_element_custom_property(
CUSTOM_PROPERTY_COMPUTATIONS.with(|count| count.set(count.get() + 1));
let entry = &store.own_values[&name_raw];
- let (tokens, includes_substitution, tainted) = match entry.value.data() {
- data @ StyleValueData::Unresolved { .. } => tokens_for_unresolved_custom_property_value(data),
- _ => (ComponentValueSlice::new(&[]), false, false),
+ let substituted = match entry.value.data() {
+ StyleValueData::Unresolved(unresolved_payload) if unresolved_payload.presence().has_any() => {
+ Some(unresolved_payload)
+ }
+ _ => None,
};
- let value = if includes_substitution {
+ let value = if let Some(unresolved_payload) = substituted {
+ let tokens = tokens_for_unresolved_custom_property_value(unresolved_payload);
+ let tainted = unresolved_payload.contains_attr_tainted_values;
let guarded_contexts = GuardedSubstitutionContexts {
contexts: Rc::new(RefCell::new(
context
@@ -1350,7 +1601,7 @@ fn compute_element_custom_property(
let result = substitute_arbitrary_substitution_functions(
Some(store),
Some(registry),
- tokens,
+ tokens.slice(),
&mut property_context,
recursion_depth,
Some(SubstitutionContextDependency::Property(name.clone(), None)),
@@ -1429,9 +1680,9 @@ pub(crate) fn resolve_element_custom_properties(
.unwrap_or_else(|| CustomPropertyRegistry::shared_empty());
let values = store
- .declared_names
- .iter()
- .map(|&name_raw| {
+ .declared_names()
+ .into_iter()
+ .map(|name_raw| {
let name = &store.own_values[&name_raw].name;
match compute_element_custom_property(store, registry, name, &mut context, 0) {
Ok(value) => value,
@@ -1456,12 +1707,13 @@ pub(crate) fn resolve_element_custom_properties(
fn computed_property_tokens(value: &RetainedStyleValueData, context: &mut ASFResolutionContext) -> TokenResolution {
match value.data() {
StyleValueData::GuaranteedInvalid => TokenResolution::Invalid,
- data @ StyleValueData::Unresolved { .. } => {
- let (tokens, _, tainted) = tokens_for_unresolved_custom_property_value(data);
- context.contains_attr_tainted_values |= tainted;
- TokenResolution::Resolved(tokens.to_owned())
+ // NB: A computed value can be one the element computed just now, which need not outlive the
+ // resolution, so its tokens are not cached by its address, or the cache holds it.
+ StyleValueData::Unresolved(unresolved_payload) => {
+ context.contains_attr_tainted_values |= unresolved_payload.contains_attr_tainted_values;
+ TokenResolution::Resolved(tokens_for_unresolved_custom_property_value(unresolved_payload).into_list())
}
- data => resolve_typed_custom_property_value(data, context),
+ _ => TokenResolution::Resolved(cached_held_value_tokens(value, context).as_ref().clone()),
}
}
@@ -1470,7 +1722,7 @@ fn registration_accepts_tokens(
registration: &RegisteredCustomProperty,
tokens: &[ComponentValue],
) -> bool {
- matches!(registration.syntax, SyntaxNode::Universal)
+ matches!(*registration.syntax, SyntaxNode::Universal)
|| registry.parse_registered_value(registration, tokens).is_some()
}
@@ -1496,6 +1748,7 @@ fn registered_property_fallback(
registration
.initial_source
.as_ref()
+ .map(RetainedString::units)
.map_or(TokenResolution::Invalid, TokenResolution::from_source)
}
@@ -1513,6 +1766,7 @@ fn resolve_css_wide_keyword(
if keyword.eq_ignore_ascii_case("initial") {
return registration
.and_then(|registration| registration.initial_source.as_ref())
+ .map(RetainedString::units)
.map_or(TokenResolution::Invalid, TokenResolution::from_source);
}
// FIXME: Roll `revert` and `revert-layer` back to a declaration of the custom property from a lower cascade layer
@@ -1538,6 +1792,7 @@ fn resolve_css_wide_keyword(
}
registration
.and_then(|registration| registration.initial_source.as_ref())
+ .map(RetainedString::units)
.map_or(TokenResolution::Invalid, TokenResolution::from_source)
}
@@ -1724,13 +1979,14 @@ fn resolve_custom_property_with_lookup(
let Some((entry, owner)) = entry_and_owner else {
return registration
.and_then(|registration| registration.initial_source.as_ref())
+ .map(RetainedString::units)
.map_or(TokenResolution::Invalid, TokenResolution::from_source);
};
// Declared names are unique keys from own_values; equal counts mean the owner lookup proves membership.
if lookup == CustomPropertyLookup::Normal
&& context.element_store.is_some_and(|store| std::ptr::eq(store, owner))
&& store.is_some_and(|store| std::ptr::eq(store, owner))
- && (owner.declared_names.len() == owner.own_values.len() || owner.declared_names.contains(&name.raw_identity()))
+ && owner.declares(name.raw_identity())
{
let computed_value = compute_element_custom_property(
owner,
@@ -1758,23 +2014,23 @@ fn resolve_custom_property_with_lookup(
{
return computed_property_tokens(&entry.value, context);
}
- let result = if matches!(data, StyleValueData::Unresolved { .. }) {
- let (source, includes_var, contains_attr_tainted_values) = tokens_for_unresolved_custom_property_value(data);
- context.contains_attr_tainted_values |= contains_attr_tainted_values;
- if includes_var {
+ let result = if let StyleValueData::Unresolved(unresolved_payload) = data {
+ context.contains_attr_tainted_values |= unresolved_payload.contains_attr_tainted_values;
+ let tokens = cached_value_tokens(data, context);
+ if unresolved_payload.presence().has_any() {
substitute_arbitrary_substitution_functions(
store,
registry,
- source,
+ tokens.as_ref(),
context,
recursion_depth + 1,
Some(substitution_context),
)
} else {
- TokenResolution::Resolved(source.to_owned())
+ TokenResolution::Resolved(tokens.as_ref().clone())
}
} else {
- resolve_typed_custom_property_value(data, context)
+ TokenResolution::Resolved(cached_value_tokens(data, context).as_ref().clone())
};
if let TokenResolution::Resolved(tokens) = &result
&& let Some(keyword) = single_css_wide_keyword(tokens)
@@ -2223,7 +2479,6 @@ fn evaluate_style_range_value(
) -> Result<Option<StyleRangeValue>, ConditionEvaluation> {
let resolution = match operand {
ParsedStyleRangeValue::Property(name) => {
- context.note_style_query_dependency(name);
let name = name.fly_string();
resolve_custom_property(store, registry, &name, context, recursion_depth + 1)
}
@@ -2364,7 +2619,6 @@ fn evaluate_named_style_feature(
return ConditionEvaluation::Match(false);
}
- context.note_style_query_dependency(name);
let name = name.fly_string();
let name = name.as_ref();
let local_registration = context
@@ -2396,7 +2650,7 @@ fn evaluate_named_style_feature(
registry,
&registration.syntax,
computed,
- &parse_substitution_values(initial).expect("registered initial value has valid components"),
+ &parse_substitution_values(initial.units()).expect("registered initial value has valid components"),
context,
));
};
@@ -2414,7 +2668,10 @@ fn evaluate_named_style_feature(
.and_then(|registration| registration.initial_tokens.clone())
.or_else(|| {
registration.and_then(|registration| {
- registration.initial_source.as_ref().and_then(parse_substitution_values)
+ registration
+ .initial_source
+ .as_ref()
+ .and_then(|initial| parse_substitution_values(initial.units()))
})
})
} else {
@@ -2462,7 +2719,7 @@ fn evaluate_named_style_feature(
local_registration
.as_ref()
.map(|registration| registration.syntax)
- .or_else(|| registration.map(|registration| &registration.syntax)),
+ .or_else(|| registration.map(|registration| &*registration.syntax)),
) {
return ConditionEvaluation::Match(registered_style_query_values_are_equal(
registry, syntax, &computed, query, context,
@@ -2472,8 +2729,7 @@ fn evaluate_named_style_feature(
}
/// Evaluate a container query's style feature against a container's retained style: its
-/// custom-property environment, and lengths and colors as its record computes them. The custom
-/// properties the feature reads are noted in `dependencies`.
+/// custom-property environment, and lengths and colors as its record computes them.
pub(crate) fn evaluate_retained_container_style_feature(
store: Option<&CustomPropertyStore>,
registry: &CustomPropertyRegistry,
@@ -2481,14 +2737,12 @@ pub(crate) fn evaluate_retained_container_style_feature(
length_resolution_context: &crate::css::style_compute::FfiLengthResolutionContext,
color_resolution_input: crate::css::color_resolution::ColorResolutionInput<'_>,
tree_counting: Option<(u64, u64)>,
- dependencies: &mut Option<Box<StyleQueryDependencies>>,
) -> MatchResult {
let mut context = ASFResolutionContext {
inheritance_store: store.and_then(|store| store.inheritance_parent.as_deref()),
style_query_length_resolution_context: Some(length_resolution_context),
style_query_color_resolution_input: Some(color_resolution_input),
style_query_tree_counting: tree_counting,
- style_query_dependencies: Some(dependencies),
..Default::default()
};
let registry = Some(registry);
@@ -3084,8 +3338,8 @@ fn parse_attr_value_with_syntax(
let random_function_index = RandomFunctionIndex::default();
let parsed =
parse_with_syntax_component_values(&registry.parse_context(&random_function_index), values, syntax, None)?;
- if let StyleValueData::Unresolved { components, .. } = parsed {
- return Some(components.as_counted_slice().to_owned());
+ if let StyleValueData::Unresolved(unresolved_payload) = &parsed {
+ return Some(unresolved_payload.components());
}
let serialized = crate::css::serialize::serialize_style_value_to_utf16(&parsed);
parse_substitution_values(&serialized)
@@ -3424,7 +3678,7 @@ pub(crate) struct VarResolutionInputs<'a> {
pub(crate) parse_context: Option<&'a ParseContext<'a>>,
pub(crate) media_environment: Option<&'a FfiMediaEnvironment<'a>>,
pub(crate) attribute_names_are_ascii_case_insensitive: bool,
- pub(crate) style_query_inputs: Option<&'a crate::css::cascaded_properties::FfiStyleQueryInputs>,
+ pub(crate) style_query_inputs: Option<&'a crate::css::cascaded_properties::StyleQueryInputs>,
}
pub(crate) fn resolve_vars(
@@ -3479,24 +3733,29 @@ pub(crate) fn resolve_vars(
token_cache: Some(token_cache),
..Default::default()
};
- if !matches!(value_data, StyleValueData::Unresolved { .. }) {
+ let StyleValueData::Unresolved(unresolved_payload) = value_data else {
return NativeVarResolution::NotHandled;
- }
- let (source, includes_substitution, contains_attr_tainted_values) =
- tokens_for_unresolved_custom_property_value(value_data);
+ };
// A value holding no substitution function has nothing to resolve: it is invalid at
// computed-value time, as every caller takes an unresolved value it cannot substitute.
- if !includes_substitution {
+ if !unresolved_payload.presence().has_any() {
return NativeVarResolution::Invalid;
}
- context.contains_attr_tainted_values = contains_attr_tainted_values;
- let result =
- substitute_arbitrary_substitution_functions(store, registry, source, &mut context, 0, substitution_context);
+ context.contains_attr_tainted_values = unresolved_payload.contains_attr_tainted_values;
+ let tokens = cached_value_tokens(value_data, &mut context);
+ let result = substitute_arbitrary_substitution_functions(
+ store,
+ registry,
+ tokens.as_ref(),
+ &mut context,
+ 0,
+ substitution_context,
+ );
match result {
// A custom property carries its taint to the values that substitute it; another property is invalid where a
// tainted value reaches a URL.
TokenResolution::Resolved(tokens) => NativeVarResolution::Resolved {
- source: serialize_tokens(&tokens),
+ source: serialize_component_values_to_utf16(&tokens, ComponentSerializationMode::Retokenize),
contains_attr_tainted_values: if property_id == crate::css::property_metadata::property_id::CUSTOM {
context.contains_attr_tainted_values
} else {
@@ -3549,20 +3808,56 @@ mod tests {
}
}
+ #[test]
+ fn stores_built_apart_hold_the_same_values_where_every_name_reads_the_same() {
+ fn store(
+ parent: Option<Arc<CustomPropertyStore>>,
+ names: std::ops::Range<u32>,
+ value: f64,
+ ) -> Arc<CustomPropertyStore> {
+ let entries = names
+ .map(|index| {
+ let name = Utf16FlyString::from_utf16(&utf16(&format!("--name-{index}")));
+ let entry = CustomPropertyEntry {
+ name: name.clone(),
+ value: RetainedStyleValueData::from_owned(StyleValueData::Number { value }),
+ important: false,
+ declared: None,
+ };
+ (name.raw_identity(), entry)
+ })
+ .collect();
+ CustomPropertyStore::child(parent, entries)
+ }
+ // NB: A parent of more names than a child takes in stays a store of the child's chain.
+ let child_over = |value| store(Some(store(None, 0..20, value)), 20..22, 2.0);
+ let (first, second) = (child_over(1.0), child_over(1.0));
+ assert!(!Arc::ptr_eq(first.parent().unwrap(), second.parent().unwrap()));
+ assert!(first.holds_same_values_as(&second));
+ assert!(!first.holds_same_values_as(&child_over(3.0)));
+ // NB: A name only the other chain holds differs too, whichever store is asked.
+ let wider = store(Some(store(None, 0..21, 1.0)), 21..22, 2.0);
+ assert!(!first.holds_same_values_as(&wider));
+ assert!(!wider.holds_same_values_as(&first));
+ }
+
#[test]
fn custom_property_values_outlive_their_store() {
+ let name = Utf16FlyString::default();
+ let name_raw = name.raw_identity();
let store = CustomPropertyStore::child(
None,
vec![(
- 0,
+ name_raw,
CustomPropertyEntry {
- name: Utf16FlyString::default(),
+ name,
value: RetainedStyleValueData::from_owned(StyleValueData::Number { value: 1.0 }),
important: false,
+ declared: None,
},
)],
);
- let value = store.get(0).unwrap().value.clone();
+ let value = store.get(name_raw).unwrap().value.clone();
drop(store);
assert!(matches!(value.data(), StyleValueData::Number { value } if *value == 1.0));
}
@@ -3941,6 +4236,7 @@ mod tests {
name,
value: RetainedStyleValueData::from_arc(value),
important: false,
+ declared: None,
},
)
})
@@ -4048,17 +4344,22 @@ pub unsafe extern "C" fn rust_custom_property_registry_update(
.to_utf16()
.expect("invalid registered custom property name");
let initial_source = if registration.has_initial_value {
- Some(
- registration
- .initial_value
- .to_utf16()
- .expect("invalid registered custom property initial value"),
- )
+ let units = registration
+ .initial_value
+ .to_utf16()
+ .expect("invalid registered custom property initial value");
+ Some(RetainedString::from_utf16(&units).expect("invalid registered custom property initial value"))
} else {
None
};
- let Some(syntax) = (unsafe { clone_syntax_handle(registration.syntax) }) else {
+ if registration.syntax.is_null() {
continue;
+ }
+ // SAFETY: The host lends its counted reference to the parsed syntax for the call.
+ let syntax = unsafe {
+ let syntax = registration.syntax.cast::<SyntaxNode>();
+ Arc::increment_strong_count(syntax);
+ Arc::from_raw(syntax)
};
// SAFETY: The host lends a live style value for the call; the registry keeps a reference of
// its own for as long as it holds the registration.
@@ -4086,7 +4387,7 @@ pub extern "C" fn rust_custom_property_registry_destroy(registry: OwnedArc<Custo
drop(registry);
}
-/// Takes a reference of its own to the document registry `registry`, for a style transaction that
+/// Takes a reference of its own to the document registry `registry`, for a style update that
/// reads it beside the document, which may make the document's registry anew meanwhile.
///
/// # Safety
@@ -4138,25 +4439,29 @@ pub unsafe extern "C" fn rust_custom_property_store_create(
unsafe { Arc::increment_strong_count(inheritance_parent) };
Some(unsafe { Arc::from_raw(inheritance_parent) })
};
- let own_values = entries
- .iter()
- .map(|entry| {
- (
- entry.name_raw,
- CustomPropertyEntry {
- name: unsafe { Utf16FlyString::from_raw_owned(entry.name_raw) },
- value: unsafe { RetainedStyleValueData::from_retained_pointer(entry.data.cast()) },
- important: entry.important,
- },
- )
- })
- .collect();
+ let entry_of = |entry: &FfiCustomPropertyStoreEntry| {
+ (
+ entry.name_raw,
+ CustomPropertyEntry {
+ name: unsafe { Utf16FlyString::from_raw_owned(entry.name_raw) },
+ value: unsafe { RetainedStyleValueData::from_retained_pointer(entry.data.cast()) },
+ important: entry.important,
+ declared: None,
+ },
+ )
+ };
+ let (declared, taken_in) = entries.split_at(declared_count);
+ let mut own_values = CustomPropertyEntriesBuilder::default();
+ own_values.declare(declared.iter().map(entry_of));
+ for (name_raw, entry) in taken_in.iter().map(entry_of) {
+ own_values.insert(name_raw, entry);
+ }
Arc::into_raw(Arc::new(CustomPropertyStore {
- own_values,
- declared_names: entries[..declared_count].iter().map(|entry| entry.name_raw).collect(),
+ own_values: own_values.finished(),
ancestor_count: parent.as_ref().map_or(0, |parent| parent.ancestor_count + 1),
parent,
inheritance_parent,
+ animation_overlay_base: None,
}))
.cast()
}
@@ -4179,7 +4484,14 @@ pub unsafe extern "C" fn rust_custom_property_store_create_animation_overlay(
} else {
unsafe { ak::slice_from_raw_parts(entries, entry_count) }
};
- let base = unsafe { base.cast::<CustomPropertyStore>().as_ref() };
+ let base = (!base.is_null()).then(|| {
+ let base = base.cast::<CustomPropertyStore>();
+ // SAFETY: Guaranteed by the caller.
+ unsafe {
+ Arc::increment_strong_count(base);
+ Arc::from_raw(base)
+ }
+ });
let animated = entries.iter().map(|entry| {
(
entry.name_raw,
@@ -4187,6 +4499,7 @@ pub unsafe extern "C" fn rust_custom_property_store_create_animation_overlay(
name: unsafe { Utf16FlyString::from_raw_owned(entry.name_raw) },
value: unsafe { RetainedStyleValueData::from_retained_pointer(entry.data.cast()) },
important: entry.important,
+ declared: None,
},
)
});
@@ -4199,6 +4512,167 @@ pub extern "C" fn rust_custom_property_store_destroy(store: OwnedArc<CustomPrope
drop(store);
}
+/// Takes another reference to `store`, which the host holds as an environment.
+///
+/// # Safety
+/// `store` must be a live store pointer.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_custom_property_store_retain(store: *const c_void) {
+ // SAFETY: Guaranteed by the caller.
+ unsafe { Arc::increment_strong_count(store.cast::<CustomPropertyStore>()) };
+}
+
+/// How many references to `store` there are.
+///
+/// # Safety
+/// `store` must be a live store pointer.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_custom_property_store_reference_count(store: *const c_void) -> usize {
+ // SAFETY: Guaranteed by the caller: the store lives in an Arc another reference keeps.
+ let store = std::mem::ManuallyDrop::new(unsafe { Arc::from_raw(store.cast::<CustomPropertyStore>()) });
+ Arc::strong_count(&store)
+}
+
+/// How many stores `store` lies over, as its chain counts them.
+///
+/// # Safety
+/// `store` must be a live store pointer.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_custom_property_store_ancestor_count(store: *const c_void) -> u8 {
+ unsafe { &*store.cast::<CustomPropertyStore>() }.ancestor_count
+}
+
+/// The store `store` lies over in its chain, or, for the values an element's animations sample,
+/// the store of the environment they lie over; borrowed, or null.
+///
+/// # Safety
+/// `store` must be a live store pointer.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_custom_property_store_chain_parent(store: *const c_void) -> *const c_void {
+ let store = unsafe { &*store.cast::<CustomPropertyStore>() };
+ store
+ .animation_overlay_base
+ .as_ref()
+ .or(store.parent.as_ref())
+ .map_or(std::ptr::null(), |parent| Arc::as_ptr(parent).cast())
+}
+
+/// The value `name_raw` takes in `store`, or in a store it lies over, borrowed, with whether it
+/// is important in `important`; null where none of them holds a value of it.
+///
+/// # Safety
+/// `store` must be a live store pointer.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_custom_property_store_get(
+ store: *const c_void,
+ name_raw: usize,
+ important: &mut bool,
+) -> *const c_void {
+ let store = unsafe { &*store.cast::<CustomPropertyStore>() };
+ match store.get(name_raw) {
+ Some(entry) => {
+ *important = entry.important;
+ entry.value.pointer().cast()
+ }
+ None => std::ptr::null(),
+ }
+}
+
+/// Hands every custom property `store` holds a value of, its own or one of a store it lies over,
+/// to `callback`, each name once with the value the nearest store holds.
+///
+/// # Safety
+/// As for [`rust_custom_property_store_for_each_own_entry`].
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_custom_property_store_for_each_entry(
+ store: *const c_void,
+ context: *mut c_void,
+ callback: unsafe extern "C" fn(*mut c_void, usize, bool, *const c_void),
+) {
+ let mut seen = crate::fast_hash::FastSet::default();
+ let mut current = Some(unsafe { &*store.cast::<CustomPropertyStore>() });
+ while let Some(store) = current {
+ for (name_raw, entry) in store.own_values.iter() {
+ if seen.insert(name_raw) {
+ unsafe { callback(context, name_raw, entry.important, entry.value.pointer().cast()) };
+ }
+ }
+ current = store.parent.as_deref();
+ }
+}
+
+/// Hands every custom property `store` holds a value of itself to `callback`: the ones it
+/// declares in declaration order, then the ones it took in from the stores it lies over.
+///
+/// # Safety
+/// As for [`rust_custom_property_store_for_each_own_entry`].
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_custom_property_store_for_each_own_value(
+ store: *const c_void,
+ context: *mut c_void,
+ callback: unsafe extern "C" fn(*mut c_void, usize, bool, *const c_void),
+) {
+ let store = unsafe { &*store.cast::<CustomPropertyStore>() };
+ unsafe { rust_custom_property_store_for_each_own_entry(std::ptr::from_ref(store).cast(), context, callback) };
+ for (name_raw, entry) in store.own_values.iter() {
+ if entry.declared.is_none() {
+ unsafe { callback(context, name_raw, entry.important, entry.value.pointer().cast()) };
+ }
+ }
+}
+
+/// How many custom properties `store` declares itself.
+///
+/// # Safety
+/// `store` must be a live store pointer.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_custom_property_store_declared_count(store: *const c_void) -> usize {
+ unsafe { &*store.cast::<CustomPropertyStore>() }.declared_count()
+}
+
+/// How many custom properties `store` holds a value of itself.
+///
+/// # Safety
+/// `store` must be a live store pointer.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_custom_property_store_own_count(store: *const c_void) -> usize {
+ unsafe { &*store.cast::<CustomPropertyStore>() }.own_values.len()
+}
+
+/// Whether neither `store` nor any store it lies over holds a value.
+///
+/// # Safety
+/// `store` must be a live store pointer.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_custom_property_store_is_empty(store: *const c_void) -> bool {
+ let mut current = Some(unsafe { &*store.cast::<CustomPropertyStore>() });
+ while let Some(store) = current {
+ if !store.own_values.is_empty() {
+ return false;
+ }
+ current = store.parent.as_deref();
+ }
+ true
+}
+
+/// Whether `store` declares `name_raw` itself with a value equal to `data`.
+///
+/// # Safety
+/// `store` must be a live store pointer and `data` a live style value.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_custom_property_store_declares_value(
+ store: *const c_void,
+ name_raw: usize,
+ data: *const c_void,
+) -> bool {
+ let store = unsafe { &*store.cast::<CustomPropertyStore>() };
+ let data = unsafe { &*data.cast::<StyleValueData>() };
+ store
+ .own_values
+ .get(&name_raw)
+ .is_some_and(|entry| entry.declared.is_some() && entry.value.data() == data)
+}
+
/// Hands every custom property a store declares itself to `callback`, in declaration order, with
/// the fly string it is named by and a borrowed value.
///
@@ -4212,13 +4686,10 @@ pub unsafe extern "C" fn rust_custom_property_store_for_each_own_entry(
callback: unsafe extern "C" fn(*mut c_void, usize, bool, *const c_void),
) {
let store = unsafe { &*store.cast::<CustomPropertyStore>() };
- for name_raw in &store.declared_names {
- let entry = store
- .own_values
- .get(name_raw)
- .expect("declared custom property must be an own value");
+ for name_raw in store.declared_names() {
+ let entry = &store.own_values[&name_raw];
unsafe {
- callback(context, *name_raw, entry.important, entry.value.pointer().cast());
+ callback(context, name_raw, entry.important, entry.value.pointer().cast());
}
}
}
diff --git a/Libraries/LibWeb/Rust/src/css/declaration_block.rs b/Libraries/LibWeb/Rust/src/css/declaration_block.rs
index fb4f3f06397..2d246975422 100644
--- a/Libraries/LibWeb/Rust/src/css/declaration_block.rs
+++ b/Libraries/LibWeb/Rust/src/css/declaration_block.rs
@@ -5,21 +5,64 @@
*/
use crate::css::css_string::CssString;
-use crate::css::ffi_support::{FfiUtf16View, OwnedArc, OwnedBox};
-use crate::css::property_metadata::{property_is_logical_alias_including_shorthands, property_logical_group};
+use crate::css::ffi_support::{FfiUtf16View, OwnedBox};
+use crate::css::property_metadata::{
+ property_is_logical_alias_including_shorthands, property_is_shorthand, property_logical_group,
+ shorthand_has_leaf_longhand,
+};
+use crate::css::style::cascade::CascadeOperator;
+use crate::css::style::pipeline::rule_store::BlockCascadeData;
use crate::css::style_compute::expand_shorthands_with;
+use crate::css::style_value::ContentPayload;
use crate::css::style_value::StyleValueData;
+use crate::css::style_value_arc::StyleValueArc;
+use std::alloc::{Layout, alloc, dealloc, handle_alloc_error};
use std::cell::RefCell;
use std::ffi::c_void;
+use std::ptr::NonNull;
use std::rc::Rc;
-use std::sync::Arc;
-use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::atomic::{AtomicPtr, AtomicU64, AtomicUsize, Ordering, fence};
#[derive(Clone)]
pub(crate) struct DeclaredProperty {
pub(crate) property_id: u16,
pub(crate) important: bool,
- pub(crate) value: Arc<StyleValueData>,
+ pub(crate) value: StyleValueArc,
+}
+
+impl DeclaredProperty {
+ pub(crate) fn borrowed(&self) -> DeclarationRef<'_> {
+ DeclarationRef {
+ property_id: self.property_id,
+ important: self.important,
+ operator: declaration_operator(&self.value),
+ value: &self.value,
+ }
+ }
+}
+
+/// How a declaration of `value` takes part in the cascade: as a value, or as the CSS-wide keyword
+/// it is.
+pub(crate) fn declaration_operator(value: &StyleValueData) -> CascadeOperator {
+ use crate::css::style_compute::keyword;
+ match value {
+ StyleValueData::Keyword {
+ keyword: keyword::INHERIT,
+ } => CascadeOperator::Inherit,
+ StyleValueData::Keyword {
+ keyword: keyword::INITIAL,
+ } => CascadeOperator::Initial,
+ StyleValueData::Keyword {
+ keyword: keyword::UNSET,
+ } => CascadeOperator::Unset,
+ StyleValueData::Keyword {
+ keyword: keyword::REVERT,
+ } => CascadeOperator::Revert,
+ StyleValueData::Keyword {
+ keyword: keyword::REVERT_LAYER,
+ } => CascadeOperator::RevertLayer,
+ _ => CascadeOperator::Declared,
+ }
}
#[derive(Clone)]
@@ -28,30 +71,526 @@ pub(crate) struct CustomProperty {
pub(crate) declaration: DeclaredProperty,
}
-#[derive(Clone, Default)]
-pub struct DeclarationBlockData {
- pub(crate) properties: Vec<DeclaredProperty>,
- pub(crate) custom_properties: Vec<CustomProperty>,
+/// A declaration's property id in bits 0-10, whether it is important in bit 11, and its cascade
+/// operator in bits 12-14.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+#[repr(transparent)]
+pub(crate) struct DeclarationEntry(u16);
+
+const _: () = assert!(size_of::<DeclarationEntry>() == 2);
+const _: () = assert!(crate::css::property_metadata::LAST_LONGHAND_PROPERTY_ID < DeclarationEntry::IMPORTANT);
+const _: () = assert!(crate::css::property_metadata::property_id::CUSTOM < DeclarationEntry::IMPORTANT);
+const _: () = assert!((CascadeOperator::LAST as u16) < (1 << (16 - DeclarationEntry::OPERATOR_SHIFT)));
+
+impl DeclarationEntry {
+ const IMPORTANT: u16 = 1 << 11;
+ const OPERATOR_SHIFT: u16 = 12;
+
+ pub(crate) fn new(property_id: u16, important: bool, operator: CascadeOperator) -> Self {
+ assert!(property_id < Self::IMPORTANT, "property id out of range");
+ Self(property_id | if important { Self::IMPORTANT } else { 0 } | ((operator as u16) << Self::OPERATOR_SHIFT))
+ }
+
+ /// The property the declaration declares.
+ pub(crate) fn property(self) -> u16 {
+ self.0 & (Self::IMPORTANT - 1)
+ }
+
+ pub(crate) fn important(self) -> bool {
+ self.0 & Self::IMPORTANT != 0
+ }
+
+ /// How the declaration takes part in the cascade.
+ pub(crate) fn operator(self) -> CascadeOperator {
+ CascadeOperator::from_bits((self.0 >> Self::OPERATOR_SHIFT) as u8)
+ }
+
+ fn declaration(self, value: &StyleValueArc) -> DeclarationRef<'_> {
+ DeclarationRef {
+ property_id: self.property(),
+ important: self.important(),
+ operator: self.operator(),
+ value,
+ }
+ }
}
+/// A declaration of a block, borrowed from the arrays it is kept in.
+#[derive(Clone, Copy)]
+pub(crate) struct DeclarationRef<'a> {
+ pub(crate) property_id: u16,
+ pub(crate) important: bool,
+ pub(crate) operator: CascadeOperator,
+ pub(crate) value: &'a StyleValueArc,
+}
+
+impl DeclarationRef<'_> {
+ pub(crate) fn to_declared(self) -> DeclaredProperty {
+ DeclaredProperty {
+ property_id: self.property_id,
+ important: self.important,
+ value: self.value.clone(),
+ }
+ }
+
+ fn view(self, name: FfiUtf16View<'_>) -> FfiDeclaredProperty<'_> {
+ FfiDeclaredProperty {
+ property_id: self.property_id,
+ important: self.important,
+ value: StyleValueArc::as_ptr(self.value).cast(),
+ name,
+ }
+ }
+}
+
+pub(crate) type DeclaredPropertiesIter<'a> = std::iter::Map<
+ std::iter::Zip<std::slice::Iter<'a, DeclarationEntry>, std::slice::Iter<'a, StyleValueArc>>,
+ fn((&'a DeclarationEntry, &'a StyleValueArc)) -> DeclarationRef<'a>,
+>;
+
+/// The properties of a block: their values in one contiguous array, and their ids and
+/// importance in another.
+#[derive(Clone, Copy, Default)]
+pub(crate) struct DeclaredProperties<'a> {
+ values: &'a [StyleValueArc],
+ entries: &'a [DeclarationEntry],
+}
+
+impl<'a> DeclaredProperties<'a> {
+ #[cfg(test)]
+ pub(crate) fn len(self) -> usize {
+ self.values.len()
+ }
+
+ #[cfg(test)]
+ pub(crate) fn is_empty(self) -> bool {
+ self.values.is_empty()
+ }
+
+ #[cfg(test)]
+ pub(crate) fn get(self, index: usize) -> Option<DeclarationRef<'a>> {
+ Some(self.entries.get(index)?.declaration(&self.values[index]))
+ }
+
+ pub(crate) fn iter(self) -> DeclaredPropertiesIter<'a> {
+ fn declaration<'a>((entry, value): (&'a DeclarationEntry, &'a StyleValueArc)) -> DeclarationRef<'a> {
+ entry.declaration(value)
+ }
+ self.entries.iter().zip(self.values).map(declaration)
+ }
+}
+
+impl<'a> IntoIterator for DeclaredProperties<'a> {
+ type Item = DeclarationRef<'a>;
+ type IntoIter = DeclaredPropertiesIter<'a>;
+
+ fn into_iter(self) -> Self::IntoIter {
+ self.iter()
+ }
+}
+
+impl<'a> DeclaredProperties<'a> {
+ /// The entries of the properties, in their order.
+ pub(crate) fn entries(self) -> &'a [DeclarationEntry] {
+ self.entries
+ }
+
+ /// The values of the properties, in their order.
+ pub(crate) fn values(self) -> &'a [StyleValueArc] {
+ self.values
+ }
+}
+
+/// A custom property of a block, borrowed from the arrays it is kept in.
+#[derive(Clone, Copy)]
+pub(crate) struct CustomPropertyRef<'a> {
+ pub(crate) name: &'a CssString,
+ pub(crate) declaration: DeclarationRef<'a>,
+}
+
+/// The custom properties of a block: their values, names and entries, each in an array of its
+/// own.
+#[derive(Clone, Copy, Default)]
+pub(crate) struct CustomProperties<'a> {
+ values: &'a [StyleValueArc],
+ names: &'a [CssString],
+ entries: &'a [DeclarationEntry],
+}
+
+impl<'a> CustomProperties<'a> {
+ pub(crate) fn len(self) -> usize {
+ self.names.len()
+ }
+
+ pub(crate) fn is_empty(self) -> bool {
+ self.names.is_empty()
+ }
+
+ /// The values of the custom properties, in their order.
+ pub(crate) fn values(self) -> &'a [StyleValueArc] {
+ self.values
+ }
+
+ #[cfg(test)]
+ pub(crate) fn get(self, index: usize) -> Option<CustomPropertyRef<'a>> {
+ Some(CustomPropertyRef {
+ name: self.names.get(index)?,
+ declaration: self.entries[index].declaration(&self.values[index]),
+ })
+ }
+
+ pub(crate) fn iter(self) -> impl ExactSizeIterator<Item = CustomPropertyRef<'a>> + Clone + 'a {
+ (0..self.len()).map(move |index| CustomPropertyRef {
+ name: &self.names[index],
+ declaration: self.entries[index].declaration(&self.values[index]),
+ })
+ }
+}
+
+/// The start of a declaration block's one allocation: its reference count and the lengths of its
+/// arrays. The values of its properties follow it, then those of its custom properties, then the
+/// names of its custom properties, then the entries of both, last so that the arrays of pointers
+/// need no padding: 16 + 10 bytes per property and 18 per custom property. C++ holds a block by a
+/// pointer at this header, as an opaque type.
+pub struct DeclarationBlockHeader {
+ references: AtomicUsize,
+ property_count: u32,
+ custom_property_count: u32,
+ /// What the style engine derives from the block, made by the first engine that publishes it,
+ /// and null until then. It depends on the block's content alone.
+ cascade: AtomicPtr<BlockCascadeData>,
+}
+
+const _: () = assert!(size_of::<DeclarationBlockHeader>() == 24);
+
+/// Where the arrays of a block's allocation start.
+struct BlockLayout {
+ layout: Layout,
+ values: usize,
+ names: usize,
+ entries: usize,
+}
+
+fn block_layout(property_count: usize, custom_property_count: usize) -> BlockLayout {
+ let too_large = "declaration block too large";
+ let declaration_count = property_count.checked_add(custom_property_count).expect(too_large);
+ let (layout, values) = Layout::new::<DeclarationBlockHeader>()
+ .extend(Layout::array::<StyleValueArc>(declaration_count).expect(too_large))
+ .expect(too_large);
+ let (layout, names) = layout
+ .extend(Layout::array::<CssString>(custom_property_count).expect(too_large))
+ .expect(too_large);
+ let (layout, entries) = layout
+ .extend(Layout::array::<DeclarationEntry>(declaration_count).expect(too_large))
+ .expect(too_large);
+ BlockLayout {
+ layout,
+ values,
+ names,
+ entries,
+ }
+}
+
+impl DeclarationBlockHeader {
+ fn layout(&self) -> BlockLayout {
+ block_layout(self.property_count as usize, self.custom_property_count as usize)
+ }
+
+ fn array<T>(&self, offset: usize, start: u32, length: u32) -> &[T] {
+ // SAFETY: A header is only reached through a block, whose allocation holds the arrays
+ // after it at the offsets its layout gives.
+ unsafe {
+ ak::slice_from_raw_parts(
+ std::ptr::from_ref(self)
+ .cast::<u8>()
+ .add(offset)
+ .cast::<T>()
+ .add(start as usize),
+ length as usize,
+ )
+ }
+ }
+
+ pub(crate) fn properties(&self) -> DeclaredProperties<'_> {
+ let layout = self.layout();
+ DeclaredProperties {
+ values: self.array(layout.values, 0, self.property_count),
+ entries: self.array(layout.entries, 0, self.property_count),
+ }
+ }
+
+ pub(crate) fn custom_properties(&self) -> CustomProperties<'_> {
+ let layout = self.layout();
+ CustomProperties {
+ values: self.array(layout.values, self.property_count, self.custom_property_count),
+ names: self.array(layout.names, 0, self.custom_property_count),
+ entries: self.array(layout.entries, self.property_count, self.custom_property_count),
+ }
+ }
+
+ pub(crate) fn is_empty(&self) -> bool {
+ self.property_count == 0 && self.custom_property_count == 0
+ }
+
+ /// What the style engine derives from the block, once an engine published it.
+ pub(crate) fn cascade_data(&self) -> Option<&BlockCascadeData> {
+ // SAFETY: The data, once made, lives as long as the block.
+ unsafe { self.cascade.load(Ordering::Acquire).as_ref() }
+ }
+
+ /// What the style engine derives from the block, which `make` makes where no engine did yet,
+ /// and whether it did.
+ pub(crate) fn make_cascade_data(&self, make: impl FnOnce(&Self) -> NonNull<BlockCascadeData>) -> bool {
+ if self.cascade_data().is_some() {
+ return false;
+ }
+ let made = make(self);
+ match self
+ .cascade
+ .compare_exchange(std::ptr::null_mut(), made.as_ptr(), Ordering::AcqRel, Ordering::Acquire)
+ {
+ Ok(_) => true,
+ Err(_) => {
+ // SAFETY: Another engine made the block's data first, and this copy is no one's.
+ unsafe { BlockCascadeData::free(made) };
+ false
+ }
+ }
+ }
+
+ /// The bytes of the block's allocation and of the names of its custom properties.
+ pub(crate) fn heap_bytes(&self) -> usize {
+ let mut size = self.layout().layout.size();
+ for property in self.custom_properties().iter() {
+ size = size.saturating_add(size_of_val(property.name.units()));
+ }
+ size
+ }
+
+ pub(crate) fn to_builder(&self) -> DeclarationBlockBuilder {
+ DeclarationBlockBuilder {
+ properties: self.properties().iter().map(DeclarationRef::to_declared).collect(),
+ custom_properties: self
+ .custom_properties()
+ .iter()
+ .map(|property| CustomProperty {
+ name: property.name.clone(),
+ declaration: property.declaration.to_declared(),
+ })
+ .collect(),
+ }
+ }
+}
+
+/// An immutable declaration block shared by the parse, the CSSOM and the style engine: one counted
+/// allocation holding its header and both arrays of declarations.
+#[repr(transparent)]
+pub struct SharedDeclarationBlock {
+ header: NonNull<DeclarationBlockHeader>,
+}
+
+const _: () = assert!(size_of::<SharedDeclarationBlock>() == 8);
+const _: () = assert!(size_of::<Option<SharedDeclarationBlock>>() == 8);
+
+// SAFETY: The block is immutable while shared, its count is atomic, and its declarations are
+// Send and Sync.
+unsafe impl Send for SharedDeclarationBlock {}
+unsafe impl Sync for SharedDeclarationBlock {}
+
const _: () = {
const fn assert_send_sync<T: Send + Sync>() {}
- assert_send_sync::<DeclarationBlockData>();
+ assert_send_sync::<DeclaredProperty>();
+ assert_send_sync::<CustomProperty>();
};
-impl DeclarationBlockData {
- pub(crate) fn external_memory_size(&self) -> usize {
- let mut size = size_of::<Self>()
- .saturating_add(self.properties.capacity().saturating_mul(size_of::<DeclaredProperty>()))
- .saturating_add(
- self.custom_properties
- .capacity()
- .saturating_mul(size_of::<CustomProperty>()),
- );
- for property in &self.custom_properties {
- size = size.saturating_add(size_of_val(property.name.units()));
+/// The most references a block may have, beyond which counting aborts.
+const MAXIMUM_BLOCK_REFERENCES: usize = isize::MAX as usize;
+
+impl SharedDeclarationBlock {
+ pub(crate) fn as_ptr(&self) -> *const DeclarationBlockHeader {
+ self.header.as_ptr()
+ }
+
+ #[cfg(test)]
+ pub(crate) fn ptr_eq(first: &Self, second: &Self) -> bool {
+ first.header == second.header
+ }
+
+ /// Hands the reference over as a pointer at the header, which `from_raw` takes back.
+ pub(crate) fn into_raw(this: Self) -> *const DeclarationBlockHeader {
+ let pointer = this.header.as_ptr();
+ std::mem::forget(this);
+ pointer
+ }
+
+ /// Takes back a reference `into_raw` handed over.
+ ///
+ /// # Safety
+ /// `pointer` must come from `into_raw`, or carry a reference `increment_count` added.
+ pub(crate) unsafe fn from_raw(pointer: *const DeclarationBlockHeader) -> Self {
+ assert!(!pointer.is_null(), "a declaration block pointer is never null");
+ Self {
+ // SAFETY: Checked non-null above.
+ header: unsafe { NonNull::new_unchecked(pointer.cast_mut()) },
+ }
+ }
+
+ /// Adds a reference to the block `pointer` points at.
+ ///
+ /// # Safety
+ /// `pointer` must point at the header of a live block.
+ pub(crate) unsafe fn increment_count(pointer: *const DeclarationBlockHeader) {
+ let previous = unsafe { &*pointer }.references.fetch_add(1, Ordering::Relaxed);
+ if previous > MAXIMUM_BLOCK_REFERENCES {
+ std::process::abort();
+ }
+ }
+
+ /// A reference of its own to the live block `pointer` points at.
+ ///
+ /// # Safety
+ /// `pointer` must point at the header of a live block.
+ pub(crate) unsafe fn retain(pointer: *const DeclarationBlockHeader) -> Self {
+ unsafe {
+ Self::increment_count(pointer);
+ Self::from_raw(pointer)
+ }
+ }
+
+ /// Whether this is the only reference to the block.
+ pub(crate) fn is_unique(&self) -> bool {
+ self.references.load(Ordering::Acquire) == 1
+ }
+
+ #[cfg(test)]
+ pub(crate) fn reference_count(&self) -> usize {
+ self.references.load(Ordering::Relaxed)
+ }
+}
+
+impl std::ops::Deref for SharedDeclarationBlock {
+ type Target = DeclarationBlockHeader;
+
+ fn deref(&self) -> &DeclarationBlockHeader {
+ // SAFETY: The reference keeps the block alive.
+ unsafe { self.header.as_ref() }
+ }
+}
+
+impl Clone for SharedDeclarationBlock {
+ fn clone(&self) -> Self {
+ // SAFETY: This reference keeps the block alive.
+ unsafe { Self::increment_count(self.as_ptr()) };
+ Self { header: self.header }
+ }
+}
+
+impl Drop for SharedDeclarationBlock {
+ fn drop(&mut self) {
+ if self.references.fetch_sub(1, Ordering::Release) != 1 {
+ return;
+ }
+ fence(Ordering::Acquire);
+ if let Some(cascade) = NonNull::new(self.cascade.load(Ordering::Acquire)) {
+ // SAFETY: The block held the data, which it frees once.
+ unsafe { BlockCascadeData::free(cascade) };
+ }
+ let layout = self.layout();
+ let base = self.header.as_ptr().cast::<u8>();
+ // SAFETY: The last reference owns the declarations and the allocation `finish` made.
+ unsafe {
+ std::ptr::drop_in_place(std::ptr::slice_from_raw_parts_mut(
+ base.add(layout.values).cast::<StyleValueArc>(),
+ self.property_count as usize + self.custom_property_count as usize,
+ ));
+ std::ptr::drop_in_place(std::ptr::slice_from_raw_parts_mut(
+ base.add(layout.names).cast::<CssString>(),
+ self.custom_property_count as usize,
+ ));
+ dealloc(base, layout.layout);
+ }
+ }
+}
+
+impl Default for SharedDeclarationBlock {
+ fn default() -> Self {
+ DeclarationBlockBuilder::default().finish()
+ }
+}
+
+impl std::fmt::Debug for SharedDeclarationBlock {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter.write_str("SharedDeclarationBlock")
+ }
+}
+
+/// Whether `value` is a pending-substitution value naming the shorthand `declaration` declares, as
+/// written there, through any shorthand nested in it.
+fn value_pends_shorthand(value: &StyleValueData, declaration: &DeclaredProperty) -> bool {
+ let StyleValueData::PendingSubstitution {
+ original_shorthand,
+ original_shorthand_value,
+ } = value
+ else {
+ return false;
+ };
+ (*original_shorthand == declaration.property_id && original_shorthand_value.data() == &*declaration.value)
+ || value_pends_shorthand(original_shorthand_value.data(), declaration)
+}
+
+/// What a block is built from and edited as, frozen into a `SharedDeclarationBlock`.
+#[derive(Clone, Default)]
+pub(crate) struct DeclarationBlockBuilder {
+ pub(crate) properties: Vec<DeclaredProperty>,
+ pub(crate) custom_properties: Vec<CustomProperty>,
+}
+
+impl DeclarationBlockBuilder {
+ pub(crate) fn finish(self) -> SharedDeclarationBlock {
+ let property_count = u32::try_from(self.properties.len()).expect("declaration block too large");
+ let custom_property_count = u32::try_from(self.custom_properties.len()).expect("declaration block too large");
+ let layout = block_layout(self.properties.len(), self.custom_properties.len());
+ // SAFETY: The layout is never zero-sized, and the header and each array element are
+ // written once.
+ unsafe {
+ let base = alloc(layout.layout);
+ if base.is_null() {
+ handle_alloc_error(layout.layout);
+ }
+ base.cast::<DeclarationBlockHeader>().write(DeclarationBlockHeader {
+ references: AtomicUsize::new(1),
+ property_count,
+ custom_property_count,
+ cascade: AtomicPtr::new(std::ptr::null_mut()),
+ });
+ let values = base.add(layout.values).cast::<StyleValueArc>();
+ let names = base.add(layout.names).cast::<CssString>();
+ let entries = base.add(layout.entries).cast::<DeclarationEntry>();
+ let custom_properties = self
+ .custom_properties
+ .into_iter()
+ .map(|property| (Some(property.name), property.declaration));
+ let declarations = self
+ .properties
+ .into_iter()
+ .map(|property| (None, property))
+ .chain(custom_properties);
+ for (index, (name, declaration)) in declarations.enumerate() {
+ let operator = declaration_operator(&declaration.value);
+ entries.add(index).write(DeclarationEntry::new(
+ declaration.property_id,
+ declaration.important,
+ operator,
+ ));
+ values.add(index).write(declaration.value);
+ if let Some(name) = name {
+ names.add(index - property_count as usize).write(name);
+ }
+ }
+ SharedDeclarationBlock {
+ header: NonNull::new_unchecked(base.cast()),
+ }
}
- size
}
// https://drafts.csswg.org/cssom/#concept-declarations-specified-order
@@ -73,37 +612,55 @@ impl DeclarationBlockData {
);
}
- /// Drops the growth slack of a block that is done growing. Shrinking in place may keep the whole allocation: the
- /// allocator reuses a block for any size above half of it.
- pub(crate) fn compact(&mut self) {
- if self.properties.capacity() > self.properties.len() {
- self.properties = self.properties.to_vec();
- }
- if self.custom_properties.capacity() > self.custom_properties.len() {
- self.custom_properties = self.custom_properties.to_vec();
- }
- }
-
fn append_normalized_property(&mut self, declaration: DeclaredProperty) {
+ let property_id = declaration.property_id;
if let Some(index) = self
.properties
.iter()
- .position(|property| property.property_id == declaration.property_id)
+ .position(|property| property.property_id == property_id)
{
if self.properties[index].important && !declaration.important {
+ self.drop_shorthands_no_longer_pending_in(property_id);
return;
}
self.properties.remove(index);
}
self.properties.push(declaration);
+ self.drop_shorthands_no_longer_pending_in(property_id);
+ }
+
+ /// AD-HOC: The spec keeps only longhands in a block, where we also keep a shorthand written with an arbitrary
+ /// substitution function, for the longhands pending it to name. That declaration stands for the shorthand
+ /// only while each of its longhands pends it, so a change to `longhand` that ends this drops it.
+ fn drop_shorthands_no_longer_pending_in(&mut self, longhand: u16) {
+ if property_is_shorthand(longhand)
+ || !self
+ .properties
+ .iter()
+ .any(|property| property_is_shorthand(property.property_id))
+ {
+ return;
+ }
+ let value = self
+ .properties
+ .iter()
+ .find(|property| property.property_id == longhand)
+ .map(|property| property.value.clone());
+ self.properties.retain(|property| {
+ !property_is_shorthand(property.property_id)
+ || !shorthand_has_leaf_longhand(property.property_id, longhand)
+ || value
+ .as_deref()
+ .is_some_and(|value| value_pends_shorthand(value, property))
+ });
}
- pub(crate) fn append_block(&mut self, other: &Self) {
- for declaration in &other.properties {
- self.append_normalized_property(declaration.clone());
+ pub(crate) fn append_block(&mut self, other: &DeclarationBlockHeader) {
+ for declaration in other.properties() {
+ self.append_normalized_property(declaration.to_declared());
}
- for property in &other.custom_properties {
- self.set_custom_property(property.name.clone(), property.declaration.clone());
+ for property in other.custom_properties().iter() {
+ self.set_custom_property(property.name.clone(), property.declaration.to_declared());
}
}
@@ -168,7 +725,14 @@ impl DeclarationBlockData {
}
// 2. Append a new CSS declaration with property name property, value component value list, and important flag set
// if important flag is set to declarations.
- self.properties.push(declaration);
+ // AD-HOC: A shorthand written with an arbitrary substitution function comes before the longhands pending it,
+ // where it serializes for them.
+ let position = self
+ .properties
+ .iter()
+ .position(|property| shorthand_has_leaf_longhand(declaration.property_id, property.property_id))
+ .unwrap_or(self.properties.len());
+ self.properties.insert(position, declaration);
// 3. Return true
true
}
@@ -182,19 +746,8 @@ pub struct FfiDeclaredProperty<'a> {
pub name: FfiUtf16View<'a>,
}
-impl DeclaredProperty {
- fn view<'a>(&'a self, name: FfiUtf16View<'a>) -> FfiDeclaredProperty<'a> {
- FfiDeclaredProperty {
- property_id: self.property_id,
- important: self.important,
- value: Arc::as_ptr(&self.value).cast(),
- name,
- }
- }
-}
-
struct DeclarationBlockOwner {
- data: Arc<DeclarationBlockData>,
+ data: SharedDeclarationBlock,
identity: u64,
revision: u64,
}
@@ -207,7 +760,7 @@ thread_local! {
}
enum DeclarationBlockState {
- Immutable(Arc<DeclarationBlockData>),
+ Immutable(SharedDeclarationBlock),
Mutable(Rc<RefCell<DeclarationBlockOwner>>),
}
@@ -227,7 +780,7 @@ impl Clone for DeclarationBlock {
}
impl DeclarationBlock {
- pub(crate) fn new(data: Arc<DeclarationBlockData>) -> Self {
+ pub(crate) fn new(data: SharedDeclarationBlock) -> Self {
Self {
state: RefCell::new(DeclarationBlockState::Immutable(data)),
}
@@ -252,7 +805,7 @@ impl DeclarationBlock {
owner.clone()
}
- pub(crate) fn data(&self) -> Arc<DeclarationBlockData> {
+ pub(crate) fn data(&self) -> SharedDeclarationBlock {
match &*self.state.borrow() {
DeclarationBlockState::Immutable(data) => data.clone(),
DeclarationBlockState::Mutable(owner) => owner.borrow().data.clone(),
@@ -282,7 +835,7 @@ impl DeclarationBlock {
pub(crate) fn remove(&mut self, property_id: u16) -> bool {
let Some(index) = self
.data()
- .properties
+ .properties()
.iter()
.position(|property| property.property_id == property_id)
else {
@@ -290,17 +843,19 @@ impl DeclarationBlock {
};
self.mutate(|data| {
data.properties.remove(index);
+ data.drop_shorthands_no_longer_pending_in(property_id);
true
})
}
- fn mutate(&mut self, mutation: impl FnOnce(&mut DeclarationBlockData) -> bool) -> bool {
+ fn mutate(&mut self, mutation: impl FnOnce(&mut DeclarationBlockBuilder) -> bool) -> bool {
let owner = self.owner();
let mut owner = owner.borrow_mut();
- let data = Arc::make_mut(&mut owner.data);
- if !mutation(data) {
+ let mut builder = owner.data.to_builder();
+ if !mutation(&mut builder) {
return false;
}
+ owner.data = builder.finish();
owner.revision = owner
.revision
.checked_add(1)
@@ -311,17 +866,18 @@ impl DeclarationBlock {
// Resource registration belongs to stylesheet attachment on the document thread,
// not parsing. Keep the traversal native and expose only image-bearing values.
-pub(crate) fn visit_declaration_images(data: &DeclarationBlockData, visit: &mut impl FnMut(&StyleValueData)) {
+pub(crate) fn visit_declaration_images(data: &DeclarationBlockHeader, visit: &mut impl FnMut(&StyleValueData)) {
fn visit_images(value: &StyleValueData, visit: &mut impl FnMut(&StyleValueData)) {
match value {
// Leave image-set type filtering to the document's image decoder support.
StyleValueData::Image { .. } | StyleValueData::ImageSet { .. } => visit(value),
- StyleValueData::ValueList { values, .. } | StyleValueData::Shorthand { values, .. } => {
- for value in values.as_slice() {
+ StyleValueData::ValueList { .. } | StyleValueData::Shorthand(_) => {
+ for value in value.child_values().unwrap().as_slice() {
visit_images(value.data(), visit);
}
}
- StyleValueData::Content { content, alt_text } => {
+ StyleValueData::Content(content_payload) => {
+ let ContentPayload { content, alt_text } = &**content_payload;
visit_images(content.data(), visit);
if let Some(alt_text) = alt_text.optional_data() {
visit_images(alt_text, visit);
@@ -330,15 +886,14 @@ pub(crate) fn visit_declaration_images(data: &DeclarationBlockData, visit: &mut
_ => {}
}
}
- for property in &data.properties {
- visit_images(&property.value, visit);
+ for value in data.properties().values() {
+ visit_images(value, visit);
}
}
#[unsafe(no_mangle)]
pub extern "C" fn rust_declaration_block_is_empty(block: &DeclarationBlock) -> bool {
- let data = block.data();
- data.properties.is_empty() && data.custom_properties.is_empty()
+ block.data().is_empty()
}
/// Whether a declaration of the block holds an image or a gradient, as its value or as an item of its list.
@@ -355,7 +910,7 @@ pub extern "C" fn rust_declaration_block_has_abstract_image_values(block: &Decla
| StyleValueData::RadialGradient { .. }
)
};
- block.data().properties.iter().any(|property| match &*property.value {
+ block.data().properties().values().iter().any(|value| match &**value {
StyleValueData::ValueList { values, .. } => values
.as_slice()
.iter()
@@ -387,12 +942,12 @@ pub extern "C" fn rust_declaration_block_replace(block: &mut DeclarationBlock, s
block.replace(source);
}
-unsafe fn retain_value(value: *const c_void) -> Arc<StyleValueData> {
+unsafe fn retain_value(value: *const c_void) -> StyleValueArc {
let value = value.cast::<StyleValueData>();
assert!(!value.is_null());
unsafe {
- Arc::increment_strong_count(value);
- Arc::from_raw(value)
+ StyleValueArc::increment_strong_count(value);
+ StyleValueArc::from_raw(value)
}
}
@@ -411,7 +966,7 @@ pub unsafe extern "C" fn rust_declaration_block_create(
custom_properties: *const FfiDeclaredProperty,
custom_property_count: usize,
) -> *mut DeclarationBlock {
- let mut data = DeclarationBlockData::default();
+ let mut data = DeclarationBlockBuilder::default();
for index in 0..property_count {
data.append_in_specified_order(unsafe { declaration_from_view(&*properties.add(index)) });
}
@@ -421,7 +976,7 @@ pub unsafe extern "C" fn rust_declaration_block_create(
declaration_from_view(property)
});
}
- Box::into_raw(Box::new(DeclarationBlock::new(Arc::new(data))))
+ Box::into_raw(Box::new(DeclarationBlock::new(data.finish())))
}
#[unsafe(no_mangle)]
@@ -431,35 +986,42 @@ pub extern "C" fn rust_declaration_block_share(block: &DeclarationBlock) -> *mut
/// Pin the current declarations without creating a mutable owner or property views.
#[unsafe(no_mangle)]
-pub extern "C" fn rust_declaration_block_snapshot(block: &DeclarationBlock) -> *const DeclarationBlockData {
- Arc::into_raw(block.data())
+pub extern "C" fn rust_declaration_block_snapshot(block: &DeclarationBlock) -> *const DeclarationBlockHeader {
+ SharedDeclarationBlock::into_raw(block.data())
}
/// Retain an immutable declaration snapshot without creating a live declaration owner.
+///
+/// # Safety
+/// `data` must point at the header of a live block.
#[unsafe(no_mangle)]
-pub extern "C" fn rust_declaration_data_retain(
- data: crate::css::ffi_support::ArcRef<'_, DeclarationBlockData>,
-) -> *const DeclarationBlockData {
- Arc::into_raw(data.to_arc())
+pub unsafe extern "C" fn rust_declaration_data_retain(
+ data: *const DeclarationBlockHeader,
+) -> *const DeclarationBlockHeader {
+ unsafe { SharedDeclarationBlock::increment_count(data) };
+ data
}
/// Release an immutable declaration snapshot returned by the style engine or retained from a view.
+///
+/// # Safety
+/// `data` must carry a reference to a live block that the caller gives up.
#[unsafe(no_mangle)]
-pub extern "C" fn rust_declaration_data_release(data: OwnedArc<DeclarationBlockData>) {
- drop(data);
+pub unsafe extern "C" fn rust_declaration_data_release(data: *const DeclarationBlockHeader) {
+ drop(unsafe { SharedDeclarationBlock::from_raw(data) });
}
/// Visit borrowed declaration values without materializing mutable owners or FFI arrays.
#[unsafe(no_mangle)]
pub extern "C" fn rust_declaration_data_visit(
- data: &DeclarationBlockData,
+ data: &DeclarationBlockHeader,
context: *mut c_void,
visit: extern "C" fn(*mut c_void, &FfiDeclaredProperty),
) {
- for property in &data.properties {
+ for property in data.properties() {
visit(context, &property.view(FfiUtf16View::default()));
}
- for property in &data.custom_properties {
+ for property in data.custom_properties().iter() {
visit(
context,
&property
@@ -489,16 +1051,24 @@ pub unsafe extern "C" fn rust_declaration_block_set(
property: &FfiDeclaredProperty,
) -> bool {
let declaration = unsafe { declaration_from_view(property) };
- block.mutate(|data| data.set_declaration(declaration))
+ let property_id = declaration.property_id;
+ block.mutate(|data| {
+ let updated = data.set_declaration(declaration);
+ if updated {
+ data.drop_shorthands_no_longer_pending_in(property_id);
+ }
+ updated
+ })
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_declaration_block_append(block: &mut DeclarationBlock, property: &FfiDeclaredProperty) {
let declaration = unsafe { declaration_from_view(property) };
block.mutate(|data| {
- data.properties
- .retain(|existing| existing.property_id != declaration.property_id);
+ let property_id = declaration.property_id;
+ data.properties.retain(|existing| existing.property_id != property_id);
data.properties.push(declaration);
+ data.drop_shorthands_no_longer_pending_in(property_id);
true
});
}
@@ -526,7 +1096,7 @@ pub extern "C" fn rust_declaration_block_remove_custom(block: &mut DeclarationBl
let name = name.to_utf16().unwrap();
let Some(index) = block
.data()
- .custom_properties
+ .custom_properties()
.iter()
.position(|property| property.name.units() == name)
else {
@@ -541,7 +1111,7 @@ pub extern "C" fn rust_declaration_block_remove_custom(block: &mut DeclarationBl
#[unsafe(no_mangle)]
pub extern "C" fn rust_declaration_block_external_memory_size(block: &DeclarationBlock) -> usize {
let data = block.data();
- let mut size = size_of::<DeclarationBlock>().saturating_add(data.external_memory_size());
+ let mut size = size_of::<DeclarationBlock>().saturating_add(data.heap_bytes());
if matches!(*block.state.borrow(), DeclarationBlockState::Mutable(_)) {
size = size.saturating_add(size_of::<DeclarationBlockOwner>());
}
@@ -556,7 +1126,7 @@ mod tests {
use crate::css::property_metadata::property_id;
use crate::css::rule::rust_rule_payload;
- fn parsed_declarations(text: &str) -> Arc<DeclarationBlockData> {
+ fn parsed_declarations(text: &str) -> SharedDeclarationBlock {
let units: Vec<_> = format!(".target {{ {text} }}").encode_utf16().collect();
let input = crate::css::css_tokenizer::TokenizerInput::Utf16(&units);
// All context fields are booleans, integers, or nullable pointers.
@@ -573,23 +1143,23 @@ mod tests {
let snapshot = data.clone();
std::thread::spawn(move || {
let mut block = DeclarationBlock::new(data);
- let property = &block.data().properties[0];
- let mut view = property.view(FfiUtf16View::default());
+ let current = block.data();
+ let mut view = current.properties().get(0).unwrap().view(FfiUtf16View::default());
view.important = true;
assert!(unsafe { rust_declaration_block_set(&mut block, &view) });
- let name = block.data().custom_properties[0].name.clone();
+ let name = block.data().custom_properties().get(0).unwrap().name.clone();
assert!(rust_declaration_block_remove_custom(
&mut block,
FfiUtf16View::from_utf16(name.units())
));
- assert!(block.data().properties[0].important);
- assert!(block.data().custom_properties.is_empty());
+ assert!(block.data().properties().get(0).unwrap().important);
+ assert!(block.data().custom_properties().is_empty());
assert_eq!(crate::css::ffi_stats::CPP_CALLBACK_COUNT.get(), 0);
})
.join()
.unwrap();
- assert!(!snapshot.properties[0].important);
- assert_eq!(snapshot.custom_properties.len(), 1);
+ assert!(!snapshot.properties().get(0).unwrap().important);
+ assert_eq!(snapshot.custom_properties().len(), 1);
}
#[test]
@@ -604,10 +1174,9 @@ mod tests {
let nested = rule.child_rules().unwrap().rule_at(1);
let block = unsafe { &*rust_rule_payload(&nested).declarations };
let snapshot = nested.cascade_declarations().unwrap();
- let old_data = Arc::downgrade(&snapshot);
let borrowed = block.data();
- assert_eq!(borrowed.properties.len(), 1);
- assert_eq!(borrowed.custom_properties.len(), 1);
+ assert_eq!(borrowed.properties().len(), 1);
+ assert_eq!(borrowed.custom_properties().len(), 1);
assert!(!rust_declaration_block_is_empty(block));
assert_eq!(rust_declaration_block_revision(block), 0);
assert!(rust_declaration_block_external_memory_size(block) > 0);
@@ -615,34 +1184,34 @@ mod tests {
assert!(!rust_declaration_block_remove(&mut fork, property_id::HEIGHT));
assert!(matches!(*block.state.borrow(), DeclarationBlockState::Immutable(_)));
assert!(matches!(*fork.state.borrow(), DeclarationBlockState::Immutable(_)));
- assert!(Arc::ptr_eq(&snapshot, &fork.data()));
+ assert!(SharedDeclarationBlock::ptr_eq(&snapshot, &fork.data()));
let mut retained = unsafe { Box::from_raw(rust_declaration_block_retain(block)) };
assert!(Rc::ptr_eq(&block.owner(), &retained.owner()));
assert!(rust_declaration_block_remove(&mut retained, property_id::WIDTH));
- assert!(block.data().properties.is_empty());
+ assert!(block.data().properties().is_empty());
assert_eq!(rust_declaration_block_revision(block), 1);
// A different handle's mutation cannot invalidate a pinned snapshot.
- assert_eq!(borrowed.properties[0].property_id, property_id::WIDTH);
+ assert_eq!(borrowed.properties().get(0).unwrap().property_id, property_id::WIDTH);
assert_eq!(
- borrowed.custom_properties[0].name.units(),
+ borrowed.custom_properties().get(0).unwrap().name.units(),
"--幅".encode_utf16().collect::<Vec<_>>()
);
- assert_eq!(fork.data().properties.len(), 1);
+ assert_eq!(fork.data().properties().len(), 1);
rust_declaration_block_replace(&mut retained, &fork);
- assert_eq!(block.data().properties.len(), 1);
+ assert_eq!(block.data().properties().len(), 1);
assert_eq!(rust_declaration_block_revision(block), 2);
assert!(matches!(*fork.state.borrow(), DeclarationBlockState::Immutable(_)));
drop((nested, rule, rules));
assert!(rust_declaration_block_remove(&mut fork, property_id::WIDTH));
assert!(matches!(*fork.state.borrow(), DeclarationBlockState::Mutable(_)));
- assert!(fork.data().properties.is_empty());
- assert_eq!(retained.data().properties.len(), 1);
- assert_eq!(snapshot.properties.len(), 1);
+ assert!(fork.data().properties().is_empty());
+ assert_eq!(retained.data().properties().len(), 1);
+ assert_eq!(snapshot.properties().len(), 1);
drop(retained);
drop(borrowed);
+ assert_eq!(snapshot.reference_count(), 1);
drop(snapshot);
- assert!(old_data.upgrade().is_none());
}
#[test]
fn font_synthesis_expands_existing_position_for_ordinary_values() {
@@ -651,7 +1220,7 @@ mod tests {
for source in ["none", "weight", "style", "small-caps", "weight style small-caps"] {
let data = parsed_declarations(&format!("font-synthesis-position: auto; font-synthesis: {source}"));
let position = data
- .properties
+ .properties()
.iter()
.find(|property| property.property_id == property_id::FONT_SYNTHESIS_POSITION)
.unwrap();
@@ -677,7 +1246,7 @@ mod tests {
use crate::css::css_enums::keyword;
let kept = parsed_declarations("font-synthesis-position: auto !important; font-synthesis: none");
let position = kept
- .properties
+ .properties()
.iter()
.find(|property| property.property_id == property_id::FONT_SYNTHESIS_POSITION)
.unwrap();
@@ -687,12 +1256,12 @@ mod tests {
);
let changed =
parsed_declarations("font-synthesis-position: auto !important; font-synthesis: weight !important");
- assert_eq!(changed.properties.len(), 4);
- for property in &changed.properties {
+ assert_eq!(changed.properties().len(), 4);
+ for property in changed.properties() {
assert!(property.important);
}
let position = changed
- .properties
+ .properties()
.iter()
.find(|property| property.property_id == property_id::FONT_SYNTHESIS_POSITION)
.unwrap();
@@ -712,28 +1281,35 @@ mod tests {
("revert-layer", keyword::REVERT_LAYER),
] {
let data = parsed_declarations(&format!("font-synthesis: {source} !important"));
- assert_eq!(data.properties.len(), 4, "{source}");
+ assert_eq!(data.properties().len(), 4, "{source}");
assert!(
- data.properties
+ data.properties()
.iter()
.any(|property| property.property_id == property_id::FONT_SYNTHESIS_POSITION)
);
- for property in &data.properties {
+ for property in data.properties() {
assert!(property.important);
assert!(matches!(property.value.as_ref(), StyleValueData::Keyword { keyword } if *keyword == expected));
}
}
let pending = parsed_declarations("font-synthesis: var(--s)");
- assert_eq!(pending.properties.len(), 5);
- assert_eq!(pending.properties[0].property_id, property_id::FONT_SYNTHESIS);
+ assert_eq!(pending.properties().len(), 5);
+ assert_eq!(
+ pending.properties().get(0).unwrap().property_id,
+ property_id::FONT_SYNTHESIS
+ );
assert!(
- pending.properties[1..]
+ pending
+ .properties()
.iter()
+ .skip(1)
.any(|property| property.property_id == property_id::FONT_SYNTHESIS_POSITION)
);
assert!(
- pending.properties[1..]
+ pending
+ .properties()
.iter()
+ .skip(1)
.all(|property| matches!(property.value.as_ref(), StyleValueData::PendingSubstitution { .. }))
);
}
diff --git a/Libraries/LibWeb/Rust/src/css/descriptor_block.rs b/Libraries/LibWeb/Rust/src/css/descriptor_block.rs
index 9c1635f3f35..8cb839d09b9 100644
--- a/Libraries/LibWeb/Rust/src/css/descriptor_block.rs
+++ b/Libraries/LibWeb/Rust/src/css/descriptor_block.rs
@@ -11,6 +11,7 @@ use crate::css::serialize::{
SerializationMode, StringUnits, TextSink, serialize_an_identifier, serialize_style_value, sink_into_raw,
};
use crate::css::style_value::StyleValueData;
+use crate::css::style_value_arc::StyleValueArc;
use std::cell::RefCell;
use std::ffi::c_void;
use std::rc::Rc;
@@ -20,12 +21,12 @@ use std::sync::Arc;
pub(crate) struct DescriptorData {
pub(crate) name: CssString,
pub(crate) id: u8,
- pub(crate) value: Arc<StyleValueData>,
+ pub(crate) value: StyleValueArc,
}
#[derive(Clone, Default)]
pub(crate) struct DescriptorBlockData {
- pub(crate) descriptors: Vec<DescriptorData>,
+ pub(crate) descriptors: crate::css::thin_slice::ThinSlice<DescriptorData>,
}
const _: () = {
@@ -64,7 +65,7 @@ impl DescriptorData {
FfiDescriptor {
name: FfiUtf16View::from_utf16(self.name.units()),
id: self.id,
- value: Arc::as_ptr(&self.value).cast(),
+ value: StyleValueArc::as_ptr(&self.value).cast(),
}
}
}
@@ -108,8 +109,8 @@ unsafe fn descriptor_from_view(view: &FfiDescriptor) -> DescriptorData {
assert!(!view.value.is_null());
let value = view.value.cast::<StyleValueData>();
let value = unsafe {
- Arc::increment_strong_count(value);
- Arc::from_raw(value)
+ StyleValueArc::increment_strong_count(value);
+ StyleValueArc::from_raw(value)
};
DescriptorData {
name,
@@ -184,7 +185,7 @@ pub extern "C" fn rust_descriptor_block_get(
.enumerate()
.all(|(index, unit)| *unit == name.code_unit_at(index))))
})
- .map_or(std::ptr::null(), |descriptor| Arc::as_ptr(&descriptor.value))
+ .map_or(std::ptr::null(), |descriptor| StyleValueArc::as_ptr(&descriptor.value))
}
#[unsafe(no_mangle)]
@@ -264,7 +265,7 @@ pub extern "C" fn rust_descriptor_block_external_memory_size(block: &FfiDescript
if matches!(*block.state.borrow(), DescriptorBlockState::Mutable(_)) {
size = size.saturating_add(size_of::<DescriptorBlockOwner>());
}
- size = size.saturating_add(data.descriptors.capacity().saturating_mul(size_of::<DescriptorData>()));
+ size = size.saturating_add(data.descriptors.heap_bytes());
for descriptor in &data.descriptors {
size = size.saturating_add(descriptor.name.units().len().saturating_mul(size_of::<u16>()));
}
@@ -283,21 +284,23 @@ mod tests {
let descriptor = |name: &str, value| DescriptorData {
name: CssString::from_utf16(&name.encode_utf16().collect::<Vec<_>>()),
id: CUSTOM_DESCRIPTOR_ID,
- value: Arc::new(StyleValueData::Number { value }),
+ value: StyleValueArc::new(StyleValueData::Number { value }),
};
let data = Arc::new(DescriptorBlockData {
- descriptors: vec![descriptor("--first", 13.0), descriptor("--色", 29.0)],
+ descriptors: [descriptor("--first", 13.0), descriptor("--色", 29.0)]
+ .into_iter()
+ .collect(),
});
let snapshot = data.clone();
std::thread::spawn(move || {
let mut block = FfiDescriptorBlock::new(data.clone());
let mut first = data.descriptors[0].view();
- first.value = Arc::as_ptr(&data.descriptors[1].value).cast();
+ first.value = StyleValueArc::as_ptr(&data.descriptors[1].value).cast();
assert!(unsafe { rust_descriptor_block_set(&mut block, &first) });
let second = data.descriptors[1].view();
assert!(rust_descriptor_block_remove(&mut block, second.id, second.name));
assert_eq!(block.data().descriptors.len(), 1);
- assert!(Arc::ptr_eq(
+ assert!(StyleValueArc::ptr_eq(
&block.data().descriptors[0].value,
&data.descriptors[1].value
));
diff --git a/Libraries/LibWeb/Rust/src/css/dom_selector_matching.rs b/Libraries/LibWeb/Rust/src/css/dom_selector_matching.rs
index f75e2ef532b..d45ae48429e 100644
--- a/Libraries/LibWeb/Rust/src/css/dom_selector_matching.rs
+++ b/Libraries/LibWeb/Rust/src/css/dom_selector_matching.rs
@@ -7,40 +7,30 @@
//! Selector matching for the DOM query APIs (`querySelector()`, `querySelectorAll()`, `matches()` and `closest()`),
//! against the DOM itself.
//!
-//! A query's selectors compile into a selector program whose atoms are the query's own names, and the one selector
-//! evaluator runs it with the live DOM as its subject. A query reads the DOM where it stands: nothing is mirrored for
+//! A query's selectors are matched by the one selector evaluator with the live DOM as its subject, and a query plan
+//! holds what its selectors tell it ahead of walking. A query reads the DOM where it stands: nothing is mirrored for
//! it and the style engine is not consulted. Every fact a selector tests is asked of the DOM through the callbacks the
//! host passes in.
use crate::css::ffi_support::OwnedBox;
use std::convert::Infallible;
use std::ffi::c_void;
-use std::mem::MaybeUninit;
use smallvec::SmallVec;
use super::css_tokenizer::TokenizerInput;
use super::ffi_support::FfiUtf16View;
use super::selector::RustSelector;
-use super::style::compiler::SelectorCompiler;
+use super::selector::SimpleSelector;
use super::style::fast_hash::FastMap as HashMap;
-use super::style::index::DispatchKey;
use super::style::index::StyleAtomID;
-use super::style::relative_selector::RelativeQueryID;
-use super::style::selector::FeatureTest;
+use super::style::input_types::StateFact;
use super::style::selector::NthPosition;
-use super::style::selector::QueryAtoms;
-use super::style::selector::SelectorNodeID;
-use super::style::selector::SelectorOp;
-use super::style::selector::SelectorProgram;
use super::style::selector_evaluation::ElementFeatures;
-use super::style::selector_evaluation::PrecedingSiblingPrefix;
-use super::style::selector_evaluation::RememberedPrefix;
use super::style::selector_evaluation::SelectorBindings;
use super::style::selector_evaluation::SelectorEvaluator;
use super::style::selector_evaluation::SelectorSubject;
use super::style::selector_evaluation::SelectorTree;
-use super::style::transaction::StateFact;
/// What a selector compares of one element: its names, as interned string identities, and how many of its attributes
/// have a local name the matcher asked for.
@@ -105,16 +95,19 @@ pub struct FfiDomSelectorCallbacks {
/// The element's 1-based index among its inclusive element siblings, as `which` counts them.
pub child_index: unsafe extern "C" fn(element: *const c_void, which: FfiChildIndex) -> u32,
/// The first element after `node` in tree order that is a descendant of `root` and, unless `local_name` is zero,
- /// has that local name, skipping the subtrees whose attribute name filter lacks one of the bits of
- /// `attribute_names`. `node` is `root` itself to start. Both may be any node.
+ /// has that local name, and unless `class_name` is zero, has that class, skipping the subtrees whose name filter
+ /// lacks one of the bits of `names`. `node` is `root` itself to start. Both may be any node.
pub next_element_in_subtree: unsafe extern "C" fn(
node: *const c_void,
root: *const c_void,
local_name: usize,
- attribute_names: u64,
+ class_name: usize,
+ names: u64,
) -> *const c_void,
- /// The bit of the DOM's attribute name filter for a local name.
- pub attribute_name_filter_bit: unsafe extern "C" fn(local_name: usize) -> u64,
+ /// The bit of the DOM's filter of the attribute names and classes in a subtree for a name.
+ pub name_filter_bit: unsafe extern "C" fn(local_name: usize) -> u64,
+ /// The name filter of the whole tree `node` is in, with every bit set where no one element holds that tree.
+ pub tree_name_filter: unsafe extern "C" fn(node: *const c_void) -> u64,
/// The shadow root the element hosts, or null.
pub shadow_root: unsafe extern "C" fn(element: *const c_void) -> *const c_void,
/// The host of a shadow root.
@@ -153,69 +146,340 @@ pub struct FfiDomSelectorQuery {
pub ids_and_classes_ignore_case: bool,
}
-type DomNode = *const c_void;
+/// Where the matches of a query lie relative to the element with the id it names.
+#[repr(u8)]
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub enum FfiDomIdLookupKind {
+ /// The query names no id its matches can be found by.
+ None,
+ /// Every match has the id.
+ Subject,
+ /// Every match is a descendant of the element with the id.
+ Ancestor,
+ /// Every match is a descendant of the parent of the element with the id, which is a sibling of an ancestor of
+ /// the match, or of the match itself.
+ AncestorsParent,
+}
-fn optional_node(node: *const c_void) -> Option<DomNode> {
- (!node.is_null()).then_some(node)
+/// An id a query's matches can be found by, which the host looks up in the id map of the tree it queries instead
+/// of walking the whole tree.
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct FfiDomIdLookup {
+ /// The raw identity of the id, or zero for `FfiDomIdLookupKind::None`.
+ pub id: usize,
+ pub kind: FfiDomIdLookupKind,
}
-/// The names a query's program holds as atoms, which are the raw identities of the interned strings its selectors
-/// hold. Atom `n` is entry `n - 1`, so no name is `StyleAtomID::NONE`.
-#[derive(Default)]
-struct QueryNames(Vec<(usize, Option<StyleAtomID>)>);
-
-impl QueryNames {
- fn intern(&mut self, raw: usize, namespace: Option<StyleAtomID>) -> StyleAtomID {
- let index = match self.0.iter().position(|&name| name == (raw, namespace)) {
- Some(index) => index,
- None => {
- self.0.push((raw, namespace));
- self.0.len() - 1
- }
+impl FfiDomIdLookup {
+ const NONE: Self = Self {
+ id: 0,
+ kind: FfiDomIdLookupKind::None,
+ };
+
+ /// The id the one selector of a query names nearest its subject, as long as only descendant, child and sibling
+ /// combinators lie between them. Only the combinator right of the compound with the id decides how its element
+ /// relates to the matches: past a descendant or child combinator the matches are its descendants, and past a
+ /// sibling combinator they are descendants of its parent.
+ fn of(selector: crate::css::selector::Selector<'_>, raw: impl Fn(StyleAtomID) -> usize) -> Self {
+ use crate::css::selector::Combinator;
+ let id_of = |compound: crate::css::selector::Selector<'_>| {
+ compound
+ .first_compound()
+ .simple_selectors
+ .iter()
+ .find_map(|simple| match simple {
+ SimpleSelector::Id(name) => Some(raw(name.name)),
+ _ => None,
+ })
+ .filter(|&id| id != 0)
};
- StyleAtomID(u32::try_from(index + 1).unwrap_or(u32::MAX))
+ if let Some(id) = id_of(selector) {
+ return Self {
+ id,
+ kind: FfiDomIdLookupKind::Subject,
+ };
+ }
+ let mut current = selector;
+ while let Some((combinator, left)) = current.left() {
+ let kind = match combinator {
+ Combinator::Descendant | Combinator::ImmediateChild => FfiDomIdLookupKind::Ancestor,
+ Combinator::NextSibling | Combinator::SubsequentSibling => FfiDomIdLookupKind::AncestorsParent,
+ _ => return Self::NONE,
+ };
+ if left.is_relative_anchor() {
+ return Self::NONE;
+ }
+ if let Some(id) = id_of(left) {
+ return Self { id, kind };
+ }
+ current = left;
+ }
+ Self::NONE
}
+}
- /// The raw identity of an atom's name, or zero for `NONE`.
- #[inline]
- fn raw(&self, atom: StyleAtomID) -> usize {
- atom.0
- .checked_sub(1)
- .and_then(|index| self.0.get(index as usize))
- .map_or(0, |&(raw, _)| raw)
- }
+type DomNode = *const c_void;
+
+/// The raw identities of the names the subject of a relative selector requires, each with whether it is an id or a
+/// class, which a quirks-mode document compares ignoring case.
+type SubjectNames = Box<[(bool, usize)]>;
+
+/// How many bits the filter of the names in an anchor's subtree has.
+const SUBTREE_NAME_FILTER_WORDS: usize = 64;
+
+/// The names of the elements in the subtree of a `:has()` anchor, as bits of a bloom filter.
+type SubtreeNameFilter = std::rc::Rc<[u64; SUBTREE_NAME_FILTER_WORDS]>;
+
+/// The two bits of a subtree name filter a name sets.
+fn subtree_name_filter_bits(raw: usize) -> [usize; 2] {
+ let hash = (raw as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
+ let bits = (SUBTREE_NAME_FILTER_WORDS * 64) as u64;
+ [((hash >> 32) % bits) as usize, ((hash >> 16) % bits) as usize]
+}
+
+fn optional_node(node: *const c_void) -> Option<DomNode> {
+ (!node.is_null()).then_some(node)
}
+/// A `:has()` argument list, with the names each of its selectors' subjects requires, if each requires any.
+type DescendantList = (
+ crate::css::style::selector_evaluation::SelectorListKey,
+ Option<Box<[SubjectNames]>>,
+);
+
/// A selector query compiled for one kind of document, as the host caches it with the query.
pub struct DomSelectorProgram {
- program: SelectorProgram<QueryAtoms>,
- names: QueryNames,
+ /// The raw identity of each name the selectors compare, by its atom, in an open-addressed table at most half full,
+ /// whose size is a power of two: a name lies in the slot its atom's low bits name, or in the first free one after.
+ raws: Box<[(StyleAtomID, usize)]>,
/// Every attribute name the program's selectors compare, in either case: an element's row is read with them.
attribute_names: Box<[usize]>,
/// The roots of the entries that can name an element. A query names elements, and a pseudo-element is not one.
- subjects: Box<[SelectorNodeID]>,
/// The local name every subject requires its element to have, or zero.
subject_local_name: usize,
+ /// Every class each subject requires its element to have, as written.
+ subject_classes: Box<[usize]>,
+ /// The classes and attribute names the compounds of each selector name directly, each with whether it is a class.
+ /// A selector matches only in a tree holding all of its names.
+ names_in_the_tree: Box<[SubjectNames]>,
/// The local names of the attributes every subject requires its element to carry.
required_attribute_names: Box<[usize]>,
/// Whether matching one element can ask the same question twice, which is only worth remembering answers for.
lone_match_repeats_questions: bool,
+ /// The `:has()` argument lists whose every selector starts with a descendant combinator, which match under no
+ /// descendant of an anchor they do not match under: the elements a match under the descendant would be are all
+ /// under the anchor too. Where every selector's subject requires a name, with those names by selector: such a list
+ /// matches under no anchor whose subtree lacks a name of every selector.
+ descendant_lists: Box<[DescendantList]>,
+ /// The id a query of one selector finds its matches by.
+ id_lookup: FfiDomIdLookup,
+ /// The selectors the query matches by, and the HTML namespace's atom.
+ sources: Box<[crate::css::selector::SelectorRef]>,
+ html_namespace: Option<crate::css::style::AtomLease>,
}
impl DomSelectorProgram {
- /// The attribute names every match carries, as bits of the DOM's attribute name filter.
- fn required_attribute_name_bits(&self, dom: &FfiDomSelectorCallbacks) -> u64 {
+ /// The attribute names and the classes every match carries, as bits of the DOM's filter of names in a subtree. A
+ /// class compared ignoring case can be written in another case than the element's.
+ fn required_name_bits(&self, dom: &FfiDomSelectorCallbacks, ignore_case: bool) -> u64 {
+ let classes: &[usize] = if ignore_case { &[] } else { &self.subject_classes };
self.required_attribute_names
.iter()
- .fold(0, |bits, &name| bits | unsafe { (dom.attribute_name_filter_bit)(name) })
+ .chain(classes)
+ .fold(0, |bits, &name| bits | unsafe { (dom.name_filter_bit)(name) })
}
}
+fn raw_of(atom: StyleAtomID) -> usize {
+ crate::css::style::process_atoms().local_raw_of(atom).unwrap_or(0)
+}
+
+/// What the selectors of a query name, anywhere in them.
+#[derive(Default)]
+struct QueryNames {
+ /// The raw identity of every name the query compares, which it looks up once here.
+ raws: Vec<(StyleAtomID, usize)>,
+ attribute_names: Vec<usize>,
+ /// A walk up or back tests each element it passes once, and so does a count of the siblings `of S` matches, unless
+ /// what it tests reaches beyond the element it tests.
+ lone_match_repeats_questions: bool,
+ descendant_lists: Vec<DescendantList>,
+}
+
+fn collect_query_names(selectors: &[crate::css::selector::SelectorRef]) -> QueryNames {
+ use crate::css::selector::PseudoClassType;
+ let mut found = QueryNames::default();
+ let QueryNames {
+ raws,
+ attribute_names,
+ lone_match_repeats_questions,
+ descendant_lists,
+ } = &mut found;
+ let atoms = crate::css::style::process_atoms();
+ for selector in selectors {
+ visit_query_selector(
+ selector.view(),
+ &mut |simple| {
+ let names = match simple {
+ SimpleSelector::TagName(name) => Some(name.name),
+ SimpleSelector::Id(name) | SimpleSelector::Class(name) => Some(name.name),
+ SimpleSelector::Attribute(attribute) => Some(attribute.qualified_name.name),
+ SimpleSelector::PseudoClass(pseudo_class)
+ if matches!(pseudo_class.pseudo_class, PseudoClassType::Dir | PseudoClassType::State)
+ && !pseudo_class.identifier_identity.is_none() =>
+ {
+ Some(pseudo_class.identifier_identity)
+ }
+ _ => None,
+ };
+ for name in names.into_iter().flat_map(|name| [name, atoms.ascii_lowercase(name)]) {
+ if !raws.iter().any(|&(known, _)| known == name) {
+ raws.push((name, raw_of(name)));
+ }
+ }
+ if let SimpleSelector::PseudoClass(pseudo_class) = simple
+ && pseudo_class.pseudo_class == PseudoClassType::Has
+ && let Some(list) = pseudo_class.argument_selector_list.identity()
+ && !descendant_lists.iter().any(|&(known, _)| known == list)
+ && pseudo_class.argument_selector_list.iter().all(|relative| {
+ matches!(
+ relative.leftmost_compound().combinator,
+ crate::css::selector::Combinator::Descendant
+ )
+ })
+ {
+ descendant_lists.push((list, names_required_under_anchor(pseudo_class.argument_selector_list)));
+ }
+ if let SimpleSelector::Attribute(attribute) = simple {
+ let name = attribute.qualified_name.name;
+ for name in [raw_of(name), raw_of(atoms.ascii_lowercase(name))] {
+ if !attribute_names.contains(&name) {
+ attribute_names.push(name);
+ }
+ }
+ }
+ },
+ lone_match_repeats_questions,
+ );
+ }
+ found
+}
+
+/// What the subject compound of every selector of a query tests directly, written as every element carrying it carries
+/// it, which is what each match has.
+#[derive(Default)]
+struct SubjectRequirements {
+ local_name: usize,
+ classes: Vec<usize>,
+ attribute_names: Vec<usize>,
+}
+
+/// Whether `attribute` names an attribute every element carrying it carries under that name, as the filter of names in
+/// a subtree holds it.
+fn names_a_filtered_attribute(attribute: &crate::css::selector::AttributeSelector<'_>) -> bool {
+ attribute.qualified_name.name_is_ascii_lowercase
+ && matches!(
+ attribute.qualified_name.namespace_type,
+ crate::css::selector::NamespaceType::Default | crate::css::selector::NamespaceType::None
+ )
+}
+
+fn subject_requirements(selectors: &[crate::css::selector::SelectorRef]) -> SubjectRequirements {
+ use crate::css::selector::PseudoClassType;
+ let mut local_name = None;
+ let mut classes: Option<Vec<usize>> = None;
+ let mut attribute_names: Option<Vec<usize>> = None;
+ for selector in selectors {
+ let selector = selector.view();
+ let mut required_local_name = None;
+ let mut required_by_entry = SmallVec::<[usize; 4]>::new();
+ let mut classes_of_entry = SmallVec::<[usize; 4]>::new();
+ // NB: An `:is()` or `:where()` of one compound requires what the compound does.
+ let mut subject_simples = SmallVec::<[SimpleSelector<'_>; 8]>::new();
+ for simple in selector.first_compound().simple_selectors.iter() {
+ if let SimpleSelector::PseudoClass(pseudo_class) = &simple
+ && matches!(pseudo_class.pseudo_class, PseudoClassType::Is | PseudoClassType::Where)
+ {
+ if let Some(argument) = pseudo_class.argument_selector_list.single()
+ && argument.left().is_none()
+ {
+ subject_simples.extend(argument.first_compound().simple_selectors.iter());
+ }
+ continue;
+ }
+ subject_simples.push(simple);
+ }
+ for simple in &subject_simples {
+ match simple {
+ SimpleSelector::TagName(name) if name.name_is_ascii_lowercase => {
+ required_local_name = Some(raw_of(name.name));
+ }
+ SimpleSelector::Attribute(attribute) if names_a_filtered_attribute(attribute) => {
+ required_by_entry.push(raw_of(attribute.qualified_name.name));
+ }
+ SimpleSelector::Class(name) => classes_of_entry.push(raw_of(name.name)),
+ _ => {}
+ }
+ }
+ local_name = match local_name {
+ None => Some(required_local_name),
+ Some(agreed) => Some(agreed.filter(|&agreed| Some(agreed) == required_local_name)),
+ };
+ match &mut attribute_names {
+ None => attribute_names = Some(required_by_entry.into_vec()),
+ Some(required) => required.retain(|name| required_by_entry.contains(name)),
+ }
+ match &mut classes {
+ None => classes = Some(classes_of_entry.into_vec()),
+ Some(classes) => classes.retain(|class| classes_of_entry.contains(class)),
+ }
+ }
+ let mut classes = classes.unwrap_or_default();
+ classes.retain(|&class| class != 0);
+ SubjectRequirements {
+ local_name: local_name.flatten().unwrap_or(0),
+ classes,
+ attribute_names: attribute_names.unwrap_or_default(),
+ }
+}
+
+/// The classes and attribute names the compounds of `selector` name directly.
+fn names_in_the_tree_of(selector: crate::css::selector::Selector<'_>) -> SubjectNames {
+ selector
+ .compounds()
+ .flat_map(|compound| compound.simple_selectors.iter())
+ .filter_map(|simple| match simple {
+ SimpleSelector::Class(name) => Some((true, raw_of(name.name))),
+ SimpleSelector::Attribute(attribute) if names_a_filtered_attribute(&attribute) => {
+ Some((false, raw_of(attribute.qualified_name.name)))
+ }
+ _ => None,
+ })
+ .filter(|&(_, raw)| raw != 0)
+ .collect()
+}
+
+/// The open-addressed table of `raws`, at most half full, whose size is a power of two.
+fn raw_table(raws: Vec<(StyleAtomID, usize)>) -> Box<[(StyleAtomID, usize)]> {
+ let mut table = vec![(StyleAtomID::NONE, 0); (raws.len() * 2).next_power_of_two().max(2)].into_boxed_slice();
+ let mask = table.len() - 1;
+ for (atom, raw) in raws {
+ let mut slot = atom.0 as usize & mask;
+ while !table[slot].0.is_none() {
+ slot = (slot + 1) & mask;
+ }
+ table[slot] = (atom, raw);
+ }
+ table
+}
+
/// Compile a selector list for the DOM query APIs, in a document whose HTML elements are in `html_namespace`, which
/// is zero for a document that is not an HTML document.
///
+///
/// # Safety
-/// `selectors` must point to `count` live selectors, which must outlive the program.
+/// `selectors` must point to `count` live selectors.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_dom_selector_program_create(
selectors: *const *const RustSelector,
@@ -226,97 +490,176 @@ pub unsafe extern "C" fn rust_dom_selector_program_create(
0 => &[][..],
_ => unsafe { ak::slice_from_raw_parts(selectors, count) },
};
- let mut names = QueryNames::default();
- let program = {
- let mut intern = |raw, namespace| names.intern(raw, namespace);
- let html_element_namespace = match html_namespace {
- 0 => StyleAtomID::NONE,
- namespace => intern(namespace, None),
- };
- let mut compiler = SelectorCompiler::for_query(&mut intern, html_element_namespace);
- for &selector in selectors {
- compiler.compile_for_query(unsafe { (*selector).compiled() });
- }
- compiler.finish()
+ // https://dom.spec.whatwg.org/#scope-match-a-selectors-string
+ // NB: A selector query matches elements, never pseudo-elements, `::slotted()` and `::part()` among them.
+ let selectors: Vec<crate::css::selector::SelectorRef> = selectors
+ .iter()
+ // SAFETY: The selectors are live.
+ .map(|&selector| unsafe { (*selector).selector.clone() })
+ .filter(|selector| {
+ let selector = selector.view();
+ !selector.compounds().any(|compound| {
+ compound
+ .simple_selectors
+ .iter()
+ .any(|simple| matches!(simple, SimpleSelector::PseudoElement(_)))
+ })
+ // NB: A selector with a compound no element satisfies matches nothing, and leaves the others free to share
+ // what they require.
+ && !selector
+ .compounds()
+ .any(|compound| crate::css::style::selector_analysis::never_matches(&compound))
+ })
+ .collect();
+ let QueryNames {
+ mut raws,
+ attribute_names,
+ lone_match_repeats_questions,
+ descendant_lists,
+ } = collect_query_names(&selectors);
+ let subject = subject_requirements(&selectors);
+ let names_in_the_tree = selectors
+ .iter()
+ .map(|selector| names_in_the_tree_of(selector.view()))
+ .collect();
+ // NB: Of several selectors, each could find its matches by another id, which the walk does better than lookups.
+ let id_lookup = match selectors.as_slice() {
+ [selector] => FfiDomIdLookup::of(selector.view(), raw_of),
+ _ => FfiDomIdLookup::NONE,
};
- let mut attribute_names = Vec::new();
- // A walk up or back tests each element it passes once, and so does a count of the siblings `of S` matches, unless
- // what it tests reaches beyond the element it tests.
- let mut lone_match_repeats_questions = false;
- // A name that folds is carried in one case or the other depending on the element, so the folded form it
- // dispatches on is not the name every match has.
- let mut folding_names = SmallVec::<[StyleAtomID; 4]>::new();
- for index in 0..program.node_count() {
- let Ok(index) = u32::try_from(index) else {
- break;
- };
- match program.node(SelectorNodeID(index)) {
- SelectorOp::Feature(FeatureTest::Attribute(test)) => {
- for name in [names.raw(test.name), names.raw(test.folded)] {
- if !attribute_names.contains(&name) {
- attribute_names.push(name);
+ // SAFETY: The namespace is a live interned string of the document.
+ let html_namespace = (html_namespace != 0).then(|| unsafe {
+ crate::css::style::AtomLease::acquire_raw(crate::css::style::process_atoms(), html_namespace)
+ });
+ // NB: A tag name written in another case than its own folds to compare with the names of the elements in the HTML
+ // namespace, which the subject asks the raw identity of then.
+ if let Some(namespace) = &html_namespace {
+ let atom = namespace.atom();
+ if !raws.iter().any(|&(known, _)| known == atom) {
+ raws.push((atom, raw_of(atom)));
+ }
+ }
+ Box::into_raw(Box::new(DomSelectorProgram {
+ attribute_names: attribute_names.into_boxed_slice(),
+ raws: raw_table(raws),
+ subject_local_name: subject.local_name,
+ subject_classes: subject.classes.into_boxed_slice(),
+ names_in_the_tree,
+ required_attribute_names: subject.attribute_names.into_boxed_slice(),
+ lone_match_repeats_questions,
+ descendant_lists: descendant_lists.into_boxed_slice(),
+ id_lookup,
+ sources: selectors.into_boxed_slice(),
+ html_namespace,
+ }))
+}
+
+/// The names the subject of each selector of a `:has()` argument list requires, whose walk over the anchor's subtree a
+/// filter of that subtree can spare, where each requires a name.
+fn names_required_under_anchor(list: crate::css::selector::SelectorListView<'_>) -> Option<Box<[SubjectNames]>> {
+ list.iter()
+ .map(|relative| {
+ let names: Box<[(bool, usize)]> = relative
+ .first_compound()
+ .simple_selectors
+ .iter()
+ .filter_map(|simple| match simple {
+ SimpleSelector::TagName(name) if name.name_is_ascii_lowercase => Some((false, raw_of(name.name))),
+ SimpleSelector::Id(name) | SimpleSelector::Class(name) => Some((true, raw_of(name.name))),
+ _ => None,
+ })
+ .filter(|&(_, raw)| raw != 0)
+ .collect();
+ (!names.is_empty()).then_some(names)
+ })
+ .collect()
+}
+
+/// Visit every simple selector of `selector` and of the selectors nested in it, noting in `repeats` whether a walk
+/// up or back, or a count of the siblings `of S` matches, tests what reaches beyond the elements it passes.
+fn visit_query_selector(
+ selector: crate::css::selector::Selector<'_>,
+ visit: &mut impl FnMut(&SimpleSelector<'_>),
+ repeats: &mut bool,
+) {
+ use crate::css::selector::{Combinator, PseudoClassType, PseudoElementSelector, PseudoElementValue};
+ let mut compound = Some(selector);
+ while let Some(current) = compound {
+ if current.is_relative_anchor() {
+ return;
+ }
+ let simple_selectors = current.first_compound().simple_selectors;
+ for simple in simple_selectors.iter() {
+ let simple = &simple;
+ visit(simple);
+ match simple {
+ SimpleSelector::PseudoClass(pseudo_class) => {
+ let of_counts = matches!(
+ pseudo_class.pseudo_class,
+ PseudoClassType::NthChild | PseudoClassType::NthLastChild
+ );
+ for nested in pseudo_class.argument_selector_list {
+ if of_counts && !reads_only_local_facts(nested) {
+ *repeats = true;
+ }
+ visit_query_selector(nested, visit, repeats);
}
}
- if test.name != test.folded {
- folding_names.push(test.folded);
- }
- }
- SelectorOp::Feature(FeatureTest::TagName(tag)) if tag.written != tag.folded => {
- folding_names.push(tag.folded);
- }
- SelectorOp::Ancestor(tested)
- | SelectorOp::PrecedingSibling(tested)
- | SelectorOp::NthPosition(NthPosition {
- of_selector: Some(tested),
- ..
- }) => lone_match_repeats_questions |= !program.selector_node_reads_only_local_facts(tested),
- _ => {}
- }
- }
- let mut subjects = Vec::new();
- let mut subject_local_name = None;
- let mut required_attribute_names: Option<Vec<usize>> = None;
- for (index, entry) in program.entries().iter().enumerate() {
- if entry.pseudo_element.is_some() || program.entry_never_matches(entry) {
- continue;
- }
- subjects.push(entry.root);
- // The keys an entry dispatches on are alternatives, so a lone one is required as well.
- let dispatch = program.subject_dispatch_keys(index);
- let mut required_local_name = None;
- let mut required_by_entry = SmallVec::<[usize; 4]>::new();
- for &key in program
- .subject_required_keys(index)
- .iter()
- .chain(dispatch.iter().filter(|_| dispatch.len() == 1))
- {
- match key {
- DispatchKey::TagName(name) if !folding_names.contains(&name) => required_local_name = Some(name),
- DispatchKey::AttributeName(name) if !folding_names.contains(&name) => {
- required_by_entry.push(names.raw(name));
- }
+ SimpleSelector::PseudoElement(PseudoElementSelector {
+ value: PseudoElementValue::CompoundSelector(argument),
+ ..
+ }) => visit_query_selector(*argument, visit, repeats),
_ => {}
}
}
- subject_local_name = match subject_local_name {
- None => Some(required_local_name),
- Some(agreed) => Some(agreed.filter(|&agreed| Some(agreed) == required_local_name)),
+ compound = match current.left() {
+ Some((combinator, left)) => {
+ if matches!(combinator, Combinator::Descendant | Combinator::SubsequentSibling)
+ && !reads_only_local_facts(left)
+ {
+ *repeats = true;
+ }
+ Some(left)
+ }
+ None => None,
};
- match &mut required_attribute_names {
- None => required_attribute_names = Some(required_by_entry.into_vec()),
- Some(required) => required.retain(|name| required_by_entry.contains(name)),
+ }
+}
+
+/// Whether the first compound of `selector` tests only facts of the element it is tested on.
+fn reads_only_local_facts(selector: crate::css::selector::Selector<'_>) -> bool {
+ use crate::css::selector::PseudoClassType;
+ fn simple_is_local(simple: &SimpleSelector<'_>) -> bool {
+ match simple {
+ SimpleSelector::Universal(_)
+ | SimpleSelector::TagName(_)
+ | SimpleSelector::Id(_)
+ | SimpleSelector::Class(_)
+ | SimpleSelector::Attribute(_) => true,
+ SimpleSelector::PseudoClass(pseudo_class) => match pseudo_class.pseudo_class {
+ PseudoClassType::Is | PseudoClassType::Where | PseudoClassType::Not => {
+ pseudo_class.argument_selector_list.iter().all(|nested| {
+ nested.left().is_none()
+ && nested
+ .first_compound()
+ .simple_selectors
+ .iter()
+ .all(|simple| simple_is_local(&simple))
+ })
+ }
+ PseudoClassType::Dir | PseudoClassType::Lang | PseudoClassType::Heading | PseudoClassType::State => {
+ true
+ }
+ kind => crate::css::style::component_matching::names_a_state(kind),
+ },
+ _ => false,
}
}
- let subject_local_name = subject_local_name.flatten().map_or(0, |name| names.raw(name));
- Box::into_raw(Box::new(DomSelectorProgram {
- program,
- names,
- attribute_names: attribute_names.into_boxed_slice(),
- subjects: subjects.into_boxed_slice(),
- subject_local_name,
- required_attribute_names: required_attribute_names.unwrap_or_default().into_boxed_slice(),
- lone_match_repeats_questions,
- }))
+ selector
+ .first_compound()
+ .simple_selectors
+ .iter()
+ .all(|simple| simple_is_local(&simple))
}
#[unsafe(no_mangle)]
@@ -324,6 +667,12 @@ pub extern "C" fn rust_dom_selector_program_destroy(program: OwnedBox<DomSelecto
drop(program);
}
+/// The id a query finds its matches by, if any.
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_dom_selector_program_id_lookup(program: &DomSelectorProgram) -> FfiDomIdLookup {
+ program.id_lookup
+}
+
/// The DOM, as the callbacks show it.
#[derive(Clone, Copy)]
struct DomTree<'q> {
@@ -353,11 +702,6 @@ impl SelectorTree for DomTree<'_> {
optional_node(unsafe { (self.dom.first_element_child)(parent) })
}
- #[inline]
- fn first_sibling(self, node: DomNode) -> DomNode {
- unsafe { (self.dom.first_element_sibling)(node) }
- }
-
#[inline]
fn shadow_root_of(self, host: DomNode) -> Option<DomNode> {
optional_node(unsafe { (self.dom.shadow_root)(host) })
@@ -370,7 +714,7 @@ impl SelectorTree for DomTree<'_> {
#[inline]
fn next_in_subtree(self, node: DomNode, root: DomNode) -> Option<DomNode> {
- optional_node(unsafe { (self.dom.next_element_in_subtree)(node, root, 0, 0) })
+ optional_node(unsafe { (self.dom.next_element_in_subtree)(node, root, 0, 0, 0) })
}
}
@@ -379,32 +723,40 @@ struct DomSubject<'q> {
dom: &'q FfiDomSelectorCallbacks,
query: &'q DomSelectorProgram,
ids_and_classes_ignore_case: bool,
- /// The element read last, whose facts are in `element` and whose attributes the program names are in
- /// `attributes`, or in `spilled_attributes` when there are more than fit. The host writes them in place, and they
- /// are read field by field where they lie. Nothing is written to the buffers until an element has such attributes.
+ /// The element read last, whose facts are in `element`. The attributes the program names of the element whose
+ /// attributes were asked for last, `attributes_of`, are in `attributes`: an element's attributes are read the first
+ /// time a test asks for them, as most elements fail a selector before it tests an attribute.
current: Option<DomNode>,
element: FfiDomElement,
- attributes: [MaybeUninit<FfiDomAttribute<'q>>; 4],
- spilled_attributes: Vec<FfiDomAttribute<'q>>,
+ attributes_of: Option<DomNode>,
+ attributes: SmallVec<[FfiDomAttribute<'q>; 4]>,
/// Whether the query remembers answers, which a query matching one element does only if it can ask a question
/// twice.
remembers_answers: bool,
/// The answers remembered, from the first one on.
answers: Option<RememberedAnswers>,
+ /// The raw identities of the process atoms outside the program asked about so far, which the query looks up once
+ /// each.
+ raws: std::cell::RefCell<SmallVec<[(StyleAtomID, usize); 8]>>,
+ /// The filter of the names in the subtree of each `:has()` anchor checked, made when the anchor is checked a second
+ /// time, with another list.
+ subtree_name_filters: HashMap<DomNode, Option<SubtreeNameFilter>>,
}
/// What a query has answered so far.
#[derive(Default)]
struct RememberedAnswers {
- relations: HashMap<(SelectorNodeID, DomNode), bool>,
- preceding_sibling_prefixes: HashMap<(SelectorNodeID, DomNode), PrecedingSiblingPrefix<DomNode>>,
- relative_queries: HashMap<(RelativeQueryID, DomNode), bool>,
- /// How many siblings an `of S` selector matches from the start (or the end) of an element's siblings through the
- /// element, by element, S and the end counted from.
- sibling_counts_of: HashMap<(DomNode, SelectorNodeID, bool), u32>,
+ /// The answers of `:has()` argument lists, by list and anchor, and the misses a miss of an ancestor answers.
+ relative_lists: HashMap<(crate::css::style::selector_evaluation::SelectorListKey, DomNode), bool>,
+ /// Whether an element or an ancestor of it matches a selector from one of its compounds leftwards, as a walk up
+ /// across a descendant combinator found, for every element it passed.
+ ancestors: HashMap<(crate::css::style::selector_evaluation::SelectorKey, DomNode), bool>,
+ /// The index of an element among its inclusive siblings an `of S` list matches, by list, by whether it counts
+ /// from the end, and by element.
+ of_indices: HashMap<(crate::css::style::selector_evaluation::SelectorListKey, bool, DomNode), i64>,
}
-impl<'q> DomSubject<'q> {
+impl DomSubject<'_> {
/// Where the query keeps answers, which it makes when it records its first.
#[inline]
fn remembered_answers(&mut self) -> Option<&mut RememberedAnswers> {
@@ -414,43 +766,97 @@ impl<'q> DomSubject<'q> {
}
}
+ /// The raw identity of the name the process atom `atom` names, or zero for `NONE`.
#[inline]
- fn names(&self) -> &'q QueryNames {
- &self.query.names
+ fn raw(&self, atom: StyleAtomID) -> usize {
+ if atom.is_none() {
+ return 0;
+ }
+ let table = &self.query.raws;
+ let mask = table.len() - 1;
+ let mut slot = atom.0 as usize & mask;
+ loop {
+ let (known, raw) = table[slot];
+ if known == atom {
+ return raw;
+ }
+ if known.is_none() {
+ break;
+ }
+ slot = (slot + 1) & mask;
+ }
+ if let Some(&(_, raw)) = self.raws.borrow().iter().find(|(known, _)| *known == atom) {
+ return raw;
+ }
+ // NB: A query names attributes in any namespace by their local names, qualified by no namespace.
+ let raw = crate::css::style::process_atoms().local_raw_of(atom).unwrap_or(0);
+ self.raws.borrow_mut().push((atom, raw));
+ raw
}
- /// Reads the element into `element`, and the attributes the program names into `attributes`.
+ /// The filter of the local names, ids and classes of the elements under `anchor`, read through a copy of `facts`.
#[inline(never)]
- fn read_element_with_attributes(&mut self, node: DomNode) {
- let dom = self.dom;
- let names = &self.query.attribute_names;
- let read = |attributes: *mut FfiDomAttribute, capacity: usize, element: &mut FfiDomElement| unsafe {
- (dom.element)(node, names.as_ptr(), names.len(), attributes, capacity, element);
+ fn subtree_name_filter(dom: &FfiDomSelectorCallbacks, facts: FfiDomElement, anchor: DomNode) -> SubtreeNameFilter {
+ let mut filter = [0u64; SUBTREE_NAME_FILTER_WORDS];
+ let mut add = |raw: usize| {
+ if raw != 0 {
+ for bit in subtree_name_filter_bits(raw) {
+ filter[bit / 64] |= 1 << (bit % 64);
+ }
+ }
};
- read(
- self.attributes.as_mut_ptr().cast(),
- self.attributes.len(),
- &mut self.element,
- );
- let count = self.element.attribute_count;
- if count > self.attributes.len() {
- self.spilled_attributes.clear();
- self.spilled_attributes.reserve_exact(count);
- read(self.spilled_attributes.as_mut_ptr(), count, &mut self.element);
- // SAFETY: The host wrote every attribute, as they fit.
- unsafe { self.spilled_attributes.set_len(count) };
+ let mut facts = facts;
+ let mut element = optional_node(unsafe { (dom.next_element_in_subtree)(anchor, anchor, 0, 0, 0) });
+ while let Some(current) = element {
+ // SAFETY: The host writes the element's facts, and no attribute where it is asked for none.
+ unsafe {
+ (dom.element)(current, std::ptr::null(), 0, std::ptr::null_mut(), 0, &mut facts);
+ }
+ add(facts.local_name);
+ add(facts.id);
+ // SAFETY: The classes stay as they are until the DOM next changes, which it does not during a query.
+ for &class in unsafe { ak::slice_from_raw_parts(facts.classes, facts.class_count) } {
+ add(class);
+ }
+ element = optional_node(unsafe { (dom.next_element_in_subtree)(current, anchor, 0, 0, 0) });
}
+ std::rc::Rc::new(filter)
}
- /// The attributes the program names of the element read last.
- #[inline]
- fn attributes(&self) -> &[FfiDomAttribute<'q>] {
- let count = self.element.attribute_count;
- match count <= self.attributes.len() {
- // SAFETY: The host wrote this many attributes to the buffer when it read the element.
- true => unsafe { ak::slice_from_raw_parts(self.attributes.as_ptr().cast(), count) },
- false => &self.spilled_attributes,
+ /// Reads the attributes the program names of `node` into `attributes`.
+ #[inline(never)]
+ fn fill_attributes(&mut self, node: DomNode) {
+ let dom = self.dom;
+ let names = &self.query.attribute_names;
+ let mut facts = self.element;
+ self.attributes.clear();
+ let capacity = self.attributes.capacity();
+ // SAFETY: The host writes at most the capacity it is told of, and says how many there are, all of which it
+ // wrote once they fit.
+ unsafe {
+ (dom.element)(
+ node,
+ names.as_ptr(),
+ names.len(),
+ self.attributes.as_mut_ptr(),
+ capacity,
+ &mut facts,
+ );
+ let count = facts.attribute_count;
+ if count > capacity {
+ self.attributes.reserve_exact(count);
+ (dom.element)(
+ node,
+ names.as_ptr(),
+ names.len(),
+ self.attributes.as_mut_ptr(),
+ count,
+ &mut facts,
+ );
+ }
+ self.attributes.set_len(count);
}
+ self.attributes_of = Some(node);
}
}
@@ -475,17 +881,17 @@ impl<'q> ElementFeatures for DomFeatures<'_, 'q> {
#[inline]
fn local_name_is(&self, name: StyleAtomID) -> bool {
- self.element().local_name == self.subject.names().raw(name)
+ self.element().local_name == self.subject.raw(name)
}
#[inline]
fn namespace_is(&self, namespace: StyleAtomID) -> bool {
- self.element().namespace_uri == self.subject.names().raw(namespace)
+ self.element().namespace_uri == self.subject.raw(namespace)
}
#[inline]
fn has_id(&self, id: StyleAtomID) -> bool {
- let id = self.subject.names().raw(id);
+ let id = self.subject.raw(id);
if self.element().id == 0 || id == 0 {
return false;
}
@@ -497,7 +903,7 @@ impl<'q> ElementFeatures for DomFeatures<'_, 'q> {
#[inline]
fn has_class(&self, class: StyleAtomID) -> bool {
- let class = self.subject.names().raw(class);
+ let class = self.subject.raw(class);
let element = self.element();
if element.class_count == 0 || class == 0 {
return false;
@@ -514,10 +920,11 @@ impl<'q> ElementFeatures for DomFeatures<'_, 'q> {
name: StyleAtomID,
any_namespace: bool,
) -> impl Iterator<Item = FfiDomAttribute<'q>> + '_ {
- let name = self.subject.names().raw(name);
+ let name = self.subject.raw(name);
debug_assert!(self.subject.current == Some(self.node));
+ debug_assert!(self.subject.query.attribute_names.is_empty() || self.subject.attributes_of == Some(self.node));
self.subject
- .attributes()
+ .attributes
.iter()
.copied()
.filter(move |attribute| attribute.local_name == name && (any_namespace || attribute.namespace_uri == 0))
@@ -525,7 +932,6 @@ impl<'q> ElementFeatures for DomFeatures<'_, 'q> {
}
impl<'q> SelectorSubject for DomSubject<'q> {
- type Atoms = QueryAtoms;
type Node = DomNode;
type Tree = DomTree<'q>;
/// An element's facts are read into the subject, where they stay until another element is read.
@@ -536,9 +942,6 @@ impl<'q> SelectorSubject for DomSubject<'q> {
where
Self: 's;
type Incomplete = Infallible;
- type Counters = ();
- type PrefixSlot = (SelectorNodeID, DomNode);
- const REMEMBERS_SIBLING_COUNTS_OF_SELECTORS: bool = true;
#[inline]
fn tree(&self) -> DomTree<'q> {
@@ -548,17 +951,22 @@ impl<'q> SelectorSubject for DomSubject<'q> {
#[inline]
fn row(&mut self, node: DomNode) -> Result<DomNode, Infallible> {
if self.current != Some(node) {
- match self.query.attribute_names.is_empty() {
- true => unsafe {
- (self.dom.element)(node, std::ptr::null(), 0, std::ptr::null_mut(), 0, &mut self.element);
- },
- false => self.read_element_with_attributes(node),
+ // SAFETY: The host writes the element's facts, and no attribute where it is asked for none.
+ unsafe {
+ (self.dom.element)(node, std::ptr::null(), 0, std::ptr::null_mut(), 0, &mut self.element);
}
self.current = Some(node);
}
Ok(node)
}
+ #[inline]
+ fn read_attributes(&mut self, node: DomNode) {
+ if self.attributes_of != Some(node) && !self.query.attribute_names.is_empty() {
+ self.fill_attributes(node);
+ }
+ }
+
#[inline]
fn features(&self, node: DomNode) -> DomFeatures<'_, 'q> {
DomFeatures { subject: self, node }
@@ -593,12 +1001,12 @@ impl<'q> SelectorSubject for DomSubject<'q> {
#[inline]
fn directionality_is(&self, node: DomNode, direction: StyleAtomID) -> bool {
let actual = unsafe { (self.dom.directionality)(node) };
- actual == self.names().raw(direction)
+ actual == self.raw(direction)
}
#[inline]
fn has_custom_state(&self, node: DomNode, state: StyleAtomID) -> bool {
- let state = self.names().raw(state);
+ let state = self.raw(state);
state != 0 && unsafe { (self.dom.has_custom_state)(node, state) }
}
@@ -617,69 +1025,6 @@ impl<'q> SelectorSubject for DomSubject<'q> {
unsafe { (self.dom.is_document_element)(node) }
}
- /// The scoping root and the shadow root stay bound for the whole query, so only a relative anchor or a `:host()`
- /// argument makes an answer local to one evaluation.
- #[inline]
- fn remembers_relations(&self, bindings: &SelectorBindings<DomNode>) -> bool {
- self.remembers_answers && bindings.relative_anchor.is_none() && !bindings.matching_host_argument
- }
-
- #[inline]
- fn relation_answer(
- &self,
- _program: &SelectorProgram<QueryAtoms>,
- relation: SelectorNodeID,
- node: DomNode,
- ) -> Option<bool> {
- self.answers.as_ref()?.relations.get(&(relation, node)).copied()
- }
-
- #[inline]
- fn record_relation_answer(
- &mut self,
- _program: &SelectorProgram<QueryAtoms>,
- relation: SelectorNodeID,
- node: DomNode,
- answer: bool,
- ) {
- if let Some(answers) = self.remembered_answers() {
- answers.relations.insert((relation, node), answer);
- }
- }
-
- #[inline]
- fn preceding_sibling_prefix(
- &mut self,
- _program: &SelectorProgram<QueryAtoms>,
- relation: SelectorNodeID,
- node: DomNode,
- ) -> Option<RememberedPrefix<(SelectorNodeID, DomNode), DomNode>> {
- // A sequence is keyed by its first sibling, which cannot change during a query. Children of
- // a document or fragment have one too, although the tree gives them no parent.
- let slot = (relation, self.tree().first_sibling(node));
- Some(RememberedPrefix {
- slot,
- // The tables are made with the first answer recorded, and until then every prefix is unknown.
- prefix: self
- .answers
- .as_ref()
- .and_then(|answers| answers.preceding_sibling_prefixes.get(&slot).copied()),
- })
- }
-
- #[inline]
- fn record_preceding_sibling_prefix(
- &mut self,
- _program: &SelectorProgram<QueryAtoms>,
- _relation: SelectorNodeID,
- slot: (SelectorNodeID, DomNode),
- prefix: PrecedingSiblingPrefix<DomNode>,
- ) {
- if let Some(answers) = self.remembered_answers() {
- answers.preceding_sibling_prefixes.insert(slot, prefix);
- }
- }
-
#[inline]
fn sibling_index(&mut self, position: NthPosition, node: DomNode) -> Result<Option<i64>, Infallible> {
// A fixed position near the end it counts from, such as `:last-child` or `:nth-child(3)`, is found by a scan of
@@ -699,43 +1044,157 @@ impl<'q> SelectorSubject for DomSubject<'q> {
Ok(Some(i64::from(unsafe { (self.dom.child_index)(node, which) })))
}
+ const REMEMBERS_ANCESTOR_ANSWERS: bool = true;
+
+ const REMEMBERS_SIBLING_ANSWERS: bool = true;
+
+ // NB: A query's walks share their bindings, and a compound left of `~` is behind no other
+ // combinator, so its answers share the ancestors' table.
+ type WalkAnswers = crate::css::style::selector_evaluation::SelectorKey;
+
#[inline]
- fn sibling_count_of(&self, selector: SelectorNodeID, from_end: bool, node: DomNode) -> Option<u32> {
- self.answers
- .as_ref()?
- .sibling_counts_of
- .get(&(node, selector, from_end))
- .copied()
+ fn walk_answers(
+ &mut self,
+ selector: crate::css::style::selector_evaluation::SelectorKey,
+ _bindings: &crate::css::style::selector_evaluation::SelectorBindings<DomNode>,
+ ) -> Option<Self::WalkAnswers> {
+ Some(selector)
}
#[inline]
- fn record_sibling_count_of(&mut self, selector: SelectorNodeID, from_end: bool, node: DomNode, count: u32) {
+ fn walk_answer(&self, selector: Self::WalkAnswers, node: DomNode) -> Option<bool> {
+ self.answers.as_ref()?.ancestors.get(&(selector, node)).copied()
+ }
+
+ #[inline]
+ fn record_walk_answers(&mut self, selector: Self::WalkAnswers, nodes: &[DomNode], answer: bool) {
if let Some(answers) = self.remembered_answers() {
- answers.sibling_counts_of.insert((node, selector, from_end), count);
+ // NB: A query that walks up once walks up for most of the elements it matches, across about as many
+ // ancestors each time, which the table makes room for at once.
+ if answers.ancestors.is_empty() {
+ answers.ancestors.reserve(256);
+ }
+ for &node in nodes {
+ answers.ancestors.insert((selector, node), answer);
+ }
}
}
#[inline]
- fn relative_answer(
+ fn remembers_of_indices(&self) -> bool {
+ self.remembers_answers
+ }
+
+ #[inline]
+ fn of_index_of(
&self,
- _program: &SelectorProgram<QueryAtoms>,
- query: RelativeQueryID,
+ list: crate::css::style::selector_evaluation::SelectorListKey,
+ from_end: bool,
+ node: DomNode,
+ ) -> Option<i64> {
+ self.answers.as_ref()?.of_indices.get(&(list, from_end, node)).copied()
+ }
+
+ #[inline]
+ fn record_of_index(
+ &mut self,
+ list: crate::css::style::selector_evaluation::SelectorListKey,
+ from_end: bool,
+ node: DomNode,
+ index: i64,
+ ) {
+ if let Some(answers) = self.remembered_answers() {
+ answers.of_indices.insert((list, from_end, node), index);
+ }
+ }
+
+ #[inline]
+ fn relative_answer_of(
+ &mut self,
+ list: crate::css::style::selector_evaluation::SelectorListKey,
anchor: DomNode,
+ bindings: &SelectorBindings<DomNode>,
) -> Option<bool> {
- self.answers.as_ref()?.relative_queries.get(&(query, anchor)).copied()
+ let tree = self.tree();
+ let query = self.query;
+ let answers = self.answers.as_mut()?;
+ if let Some(&answer) = answers.relative_lists.get(&(list, anchor)) {
+ return Some(answer);
+ }
+ // A list starting with a descendant combinator that misses under an ancestor of the anchor misses under the
+ // anchor too. An ancestor it matches under says nothing of the anchor, and the ones above that cannot be misses.
+ let descendant_list = query.descendant_lists.iter().find(|&&(known, _)| known == list);
+ if descendant_list.is_some() {
+ let mut passed = SmallVec::<[DomNode; 16]>::new();
+ passed.push(anchor);
+ let mut ancestor = tree.parent(anchor);
+ while let Some(current) = ancestor {
+ match answers.relative_lists.get(&(list, current)) {
+ Some(false) => {
+ // NB: Each element passed misses as well, which spares later walks up from passing it again.
+ for node in passed {
+ answers.relative_lists.insert((list, node), false);
+ }
+ return Some(false);
+ }
+ Some(true) => break,
+ None => passed.push(current),
+ }
+ ancestor = tree.parent(current);
+ }
+ }
+ // A list whose every selector requires a name under the anchor matches under no anchor whose subtree lacks
+ // one of each. The names are gathered once the anchor is checked again, as many anchors are checked once.
+ // NB: A `:host:has()` looks under the host's shadow root, not under the host.
+ if let Some((_, Some(required))) = descendant_list
+ && bindings.scope_shadow_root.and_then(|root| tree.host_of(root)) != Some(anchor)
+ {
+ let filters = &mut self.subtree_name_filters;
+ // NB: Many anchors are checked only once, and a miss of an ancestor answered those that a filter could.
+ let Some(own) = filters.get(&anchor).cloned() else {
+ filters.insert(anchor, None);
+ return None;
+ };
+ // NB: The filter of an ancestor holds every name under the anchor, so anchors nested in one share its filter
+ // and only the outermost walks its subtree.
+ let filter = own.unwrap_or_else(|| {
+ let mut ancestor = tree.parent(anchor);
+ while let Some(current) = ancestor {
+ if let Some(Some(filter)) = filters.get(&current) {
+ return filter.clone();
+ }
+ ancestor = tree.parent(current);
+ }
+ Self::subtree_name_filter(self.dom, self.element, anchor)
+ });
+ let lacks = |raw: usize| {
+ subtree_name_filter_bits(raw)
+ .iter()
+ .any(|&bit| filter[bit / 64] & (1 << (bit % 64)) == 0)
+ };
+ let ignore_case = self.ids_and_classes_ignore_case;
+ let rejected = required
+ .iter()
+ .all(|names| names.iter().any(|&(folds, raw)| !(folds && ignore_case) && lacks(raw)));
+ filters.insert(anchor, Some(filter));
+ if rejected {
+ answers.relative_lists.insert((list, anchor), false);
+ return Some(false);
+ }
+ }
+ None
}
#[inline]
- fn record_relative_answer(
+ fn record_relative_answer_of(
&mut self,
- _program: &SelectorProgram<QueryAtoms>,
- query: RelativeQueryID,
+ list: crate::css::style::selector_evaluation::SelectorListKey,
anchor: DomNode,
+ _bindings: &SelectorBindings<DomNode>,
answer: bool,
- _witness: Option<DomNode>,
) {
if let Some(answers) = self.remembered_answers() {
- answers.relative_queries.insert((query, anchor), answer);
+ answers.relative_lists.insert((list, anchor), answer);
}
}
}
@@ -744,6 +1203,8 @@ impl<'q> SelectorSubject for DomSubject<'q> {
struct DomQuery<'q> {
query: &'q DomSelectorProgram,
evaluator: SelectorEvaluator<DomSubject<'q>>,
+ /// What the query's selectors match in, the same for every element.
+ context: crate::css::style::component_matching::MatchContext<'q>,
}
impl<'q> DomQuery<'q> {
@@ -754,8 +1215,20 @@ impl<'q> DomQuery<'q> {
unsafe fn new(query: &'q FfiDomSelectorQuery, matches_one_element: bool) -> Self {
let program = unsafe { &*query.program };
let shadow_root = optional_node(query.shadow_root);
+ // NB: A query declares no namespaces.
+ let context = crate::css::style::component_matching::MatchContext {
+ html_namespace: program
+ .html_namespace
+ .as_ref()
+ .map_or(StyleAtomID::NONE, crate::css::style::AtomLease::atom),
+ fold_ids_and_classes: false,
+ namespaces: crate::css::selector_arena::SheetNamespaces::default(),
+ escapes_its_namespace: false,
+ logical_subject: false,
+ };
Self {
query: program,
+ context,
evaluator: SelectorEvaluator {
subject: DomSubject {
dom: unsafe { &*query.callbacks },
@@ -770,10 +1243,12 @@ impl<'q> DomQuery<'q> {
class_count: 0,
attribute_count: 0,
},
- attributes: [const { MaybeUninit::uninit() }; 4],
- spilled_attributes: Vec::new(),
+ attributes_of: None,
+ attributes: SmallVec::new(),
remembers_answers: !matches_one_element || program.lone_match_repeats_questions,
answers: None,
+ raws: Default::default(),
+ subtree_name_filters: Default::default(),
},
bindings: SelectorBindings {
scope_shadow_root: shadow_root,
@@ -785,9 +1260,10 @@ impl<'q> DomQuery<'q> {
}
fn matches(&mut self, element: DomNode) -> bool {
- let query = self.query;
- query.subjects.iter().any(|&subject| {
- let Ok(matches) = self.evaluator.matches_node(&query.program, subject, element, &());
+ let context = self.context;
+ // SAFETY: The selectors outlive the program.
+ self.query.sources.iter().any(|selector| {
+ let Ok(matches) = self.evaluator.matches_selector(selector.view(), element, context);
matches
})
}
@@ -841,15 +1317,32 @@ pub unsafe extern "C" fn rust_dom_selector_query_subtree(
) {
let mut query_run = unsafe { DomQuery::new(query, false) };
// A query whose every selector matches nothing needs no walk.
- if query_run.query.subjects.is_empty() {
+ if query_run.query.sources.is_empty() {
return;
}
let dom = query_run.evaluator.subject.dom;
- // Only an element with the local name every match has can match, and a subtree none of whose elements carries
- // every attribute name each match carries holds no match.
+ // A tree lacking a name of every selector holds no match. A class compared ignoring case can be written in another
+ // case than the element's.
+ let ignore_case = query_run.evaluator.subject.ids_and_classes_ignore_case;
+ let tree_names = unsafe { (dom.tree_name_filter)(root) };
+ if query_run.query.names_in_the_tree.iter().all(|names| {
+ names.iter().any(|&(is_class, name)| {
+ !(is_class && ignore_case) && tree_names & unsafe { (dom.name_filter_bit)(name) } == 0
+ })
+ }) {
+ return;
+ }
+ // Only an element with the local name and the class every match has can match, and a subtree whose name filter
+ // lacks an attribute name or a class each match carries holds no match.
let local_name = query_run.query.subject_local_name;
- let attribute_names = query_run.query.required_attribute_name_bits(dom);
- let next = |node| optional_node(unsafe { (dom.next_element_in_subtree)(node, root, local_name, attribute_names) });
+ // NB: A class compared ignoring case can be written in another case than the element's.
+ let class_name = match query_run.evaluator.subject.ids_and_classes_ignore_case {
+ true => 0,
+ false => query_run.query.subject_classes.first().copied().unwrap_or(0),
+ };
+ let names = query_run.query.required_name_bits(dom, ignore_case);
+ let next =
+ |node| optional_node(unsafe { (dom.next_element_in_subtree)(node, root, local_name, class_name, names) });
let mut candidate = next(root);
while let Some(element) = candidate {
if query_run.matches(element) && unsafe { found(context, element) } {
diff --git a/Libraries/LibWeb/Rust/src/css/ffi_stats.rs b/Libraries/LibWeb/Rust/src/css/ffi_stats.rs
index a360ad35c2b..461c6759b56 100644
--- a/Libraries/LibWeb/Rust/src/css/ffi_stats.rs
+++ b/Libraries/LibWeb/Rust/src/css/ffi_stats.rs
@@ -202,20 +202,6 @@ pub(crate) fn bump(op: FfiOp) {
}
}
-/// Counts a table ownership boundary only while diagnostics are enabled.
-#[inline]
-pub(crate) fn count_table_copy(values: impl FnOnce() -> (u64, u64)) {
- if !COUNTERS_ENABLED.load(Ordering::Relaxed) {
- return;
- }
- let (slots, retains) = values();
- let _ = COUNTER_CONTEXT.try_with(|context| {
- let context = context.get_or_init(|| BridgeCounterContext::new(counter_registry().clone()));
- context.counters.values[FfiOp::LonghandTableCopiedSlots as usize].fetch_add(slots, Ordering::Relaxed);
- context.counters.values[FfiOp::LonghandTableCopyRetains as usize].fetch_add(retains, Ordering::Relaxed);
- });
-}
-
#[inline]
pub(crate) fn bump_cpp_callback(op: FfiOp) {
#[cfg(test)]
diff --git a/Libraries/LibWeb/Rust/src/css/ffi_support.rs b/Libraries/LibWeb/Rust/src/css/ffi_support.rs
index ae02641bbe9..d7f8a31affa 100644
--- a/Libraries/LibWeb/Rust/src/css/ffi_support.rs
+++ b/Libraries/LibWeb/Rust/src/css/ffi_support.rs
@@ -126,11 +126,6 @@ impl<T> OwnedArc<T> {
pub(crate) fn into_arc(mut self) -> std::sync::Arc<T> {
self.take().expect("C++ hands over a live object")
}
-
- /// The reference, or none where C++ handed over null.
- pub(crate) fn into_option(mut self) -> Option<std::sync::Arc<T>> {
- self.take()
- }
}
impl<T> Drop for OwnedArc<T> {
diff --git a/Libraries/LibWeb/Rust/src/css/font_feature_values.rs b/Libraries/LibWeb/Rust/src/css/font_feature_values.rs
index acb453363bc..c5f02811d47 100644
--- a/Libraries/LibWeb/Rust/src/css/font_feature_values.rs
+++ b/Libraries/LibWeb/Rust/src/css/font_feature_values.rs
@@ -8,6 +8,7 @@ use crate::css::css_string::CssString;
use crate::css::ffi_support::{FfiUtf16View, OwnedArc};
use crate::css::parser::value_parser::equals_ascii_case_insensitive;
use crate::css::style_value::StyleValueData;
+use crate::css::style_value::{FunctionPayload, OpenTypeTaggedPayload};
use std::cell::RefCell;
use std::collections::HashMap;
use std::ffi::c_void;
@@ -407,12 +408,13 @@ pub unsafe extern "C" fn rust_font_shape_features(
_ => &[],
};
for alternate in alternates.iter().map(|alternate| alternate.data()) {
- let StyleValueData::Function { name, value } = alternate else {
+ let StyleValueData::Function(function_payload) = alternate else {
if keyword_of(Some(alternate)) == Some(HISTORICAL_FORMS) {
shape.set(b"hist", 1);
}
continue;
};
+ let FunctionPayload { name, value } = &**function_payload;
let Some(kind) = [
("stylistic", FontFeatureValuesRuleKind::Stylistic),
("styleset", FontFeatureValuesRuleKind::Styleset),
@@ -484,13 +486,10 @@ pub unsafe extern "C" fn rust_font_shape_features(
// 13. Font features implied by the value of font-feature-settings property are applied.
if let Some(StyleValueData::ValueList { values, .. }) = value(Input::FontFeatureSettings) {
for setting in values.as_slice() {
- if let StyleValueData::OpenTypeTagged {
- packed_tag,
- value: setting,
- ..
- } = setting.data()
- && let Some(setting) = integer_of(setting.data())
+ if let StyleValueData::OpenTypeTagged(open_type_tagged) = setting.data()
+ && let Some(setting) = integer_of(open_type_tagged.value.data())
{
+ let packed_tag = open_type_tagged.packed_tag;
// NB: A feature setting is kept as one byte.
shape.set(&packed_tag.to_be_bytes(), u32::from(setting as u8));
}
@@ -530,9 +529,10 @@ pub unsafe extern "C" fn rust_font_variation_axes(
return;
};
for setting in values.as_slice() {
- let StyleValueData::OpenTypeTagged { packed_tag, value, .. } = setting.data() else {
+ let StyleValueData::OpenTypeTagged(open_type_tagged_payload) = setting.data() else {
continue;
};
+ let OpenTypeTaggedPayload { packed_tag, value, .. } = &**open_type_tagged_payload;
let value = match value.data() {
StyleValueData::Number { value } => Some(*value),
calculated => crate::css::calc::resolve_calculated_number_without_context(calculated),
diff --git a/Libraries/LibWeb/Rust/src/css/function_signature.rs b/Libraries/LibWeb/Rust/src/css/function_signature.rs
index bdaf359c165..fe5cb2d2432 100644
--- a/Libraries/LibWeb/Rust/src/css/function_signature.rs
+++ b/Libraries/LibWeb/Rust/src/css/function_signature.rs
@@ -7,14 +7,14 @@
use crate::css::css_string::CssString;
use crate::css::ffi_support::FfiUtf16View;
use crate::css::parser::syntax::SyntaxNode;
-use crate::css::style_value::StyleValueData;
+use crate::css::style_value_arc::StyleValueArc;
use std::ffi::c_void;
use std::sync::Arc;
pub(crate) struct FunctionParameterData {
pub(crate) name: ak::Utf16FlyString,
pub(crate) syntax: Arc<SyntaxNode>,
- pub(crate) default_value: Option<Arc<StyleValueData>>,
+ pub(crate) default_value: Option<StyleValueArc>,
}
pub struct FunctionSignature {
@@ -65,6 +65,6 @@ pub extern "C" fn rust_function_signature_parameter(
default_value: parameter
.default_value
.as_ref()
- .map_or(std::ptr::null(), |value| Arc::as_ptr(value).cast()),
+ .map_or(std::ptr::null(), |value| StyleValueArc::as_ptr(value).cast()),
}
}
diff --git a/Libraries/LibWeb/Rust/src/css/host_shared.rs b/Libraries/LibWeb/Rust/src/css/host_shared.rs
index 1185f3db7bc..1d6e37c15d3 100644
--- a/Libraries/LibWeb/Rust/src/css/host_shared.rs
+++ b/Libraries/LibWeb/Rust/src/css/host_shared.rs
@@ -4,7 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! A pointer to a value the style transaction only borrows.
+//! A pointer to a value the style update only borrows.
//!
//! The evaluation step reads computed style values, style-group payloads, longhand tables and
//! animated overlays that somebody else owns: the retained catalog, an earlier pass, or the host.
@@ -12,10 +12,9 @@
//! side or scratch from being shareable, even though the step never writes through it and never
//! touches its reference count. [`HostShared`] is that pointer with the contract written down.
-use std::ffi::c_void;
use std::hash::{Hash, Hasher};
-/// A borrowed pointer to a value that is frozen for the length of a style transaction.
+/// A borrowed pointer to a value that is frozen for the length of a style update.
///
/// This is a plain `*const T` with one word of layout and no ownership: it retains nothing on
/// construction and releases nothing on drop. What it adds is the thread bound the raw pointer
@@ -26,7 +25,7 @@ pub(crate) struct HostShared<T: ?Sized>(*const T);
// SAFETY: The invariant, which every construction site upholds and the whole borrow-only
// computation contract rests on:
//
-// 1. The pointee is immutable for the length of a style transaction. A style value, a style-group
+// 1. The pointee is immutable for the length of a style update. A style value, a style-group
// payload, a frozen `ComputedLonghandTable` and an installed animated overlay are all written
// once, before the walk that reads them begins, and are replaced rather than mutated.
// 2. No reference count on the pointee is touched through this handle. `HostShared` owns nothing:
@@ -86,31 +85,14 @@ impl<T> HostShared<T> {
Self(pointer)
}
- /// The address of `value`, or null.
- pub(crate) fn from_option(value: Option<&T>) -> Self {
- Self(value.map_or(std::ptr::null(), std::ptr::from_ref))
- }
-
pub(crate) const fn as_ptr(self) -> *const T {
self.0
}
- pub(crate) fn cast_mut(self) -> *mut T {
- self.0.cast_mut()
- }
-
- pub(crate) fn is_null(self) -> bool {
- self.0.is_null()
- }
-
pub(crate) fn cast<U>(self) -> HostShared<U> {
HostShared(self.0.cast())
}
- pub(crate) fn addr(self) -> usize {
- self.0 as usize
- }
-
/// The pointee, for a caller that has already established it is live.
///
/// # Safety
@@ -127,32 +109,4 @@ impl<T> HostShared<T> {
pub(crate) unsafe fn as_ref<'a>(self) -> Option<&'a T> {
unsafe { self.0.as_ref() }
}
-
- /// The same addresses as a plain pointer slice, for a C++ consumer or an FFI signature.
- ///
- /// `HostShared<T>` is `repr(transparent)` over `*const T`, so the two slices have the same
- /// layout; this is a reinterpretation, not a copy.
- pub(crate) fn as_pointer_slice(handles: &[Self]) -> &[*const T] {
- // SAFETY: `repr(transparent)` makes the element types layout-identical.
- unsafe { ak::slice_from_raw_parts(handles.as_ptr().cast::<*const T>(), handles.len()) }
- }
-
- /// The inverse of [`Self::as_pointer_slice`].
- pub(crate) fn from_pointer_slice(pointers: &[*const T]) -> &[Self] {
- // SAFETY: `repr(transparent)` makes the element types layout-identical.
- unsafe { ak::slice_from_raw_parts(pointers.as_ptr().cast::<Self>(), pointers.len()) }
- }
}
-
-/// The style-group payload and style-value handles are untyped on the C++ side, so they travel as
-/// `c_void` exactly as the raw pointers they replace did.
-pub(crate) type SharedPayload = HostShared<c_void>;
-
-const _: () = {
- const fn assert_send<T: Send>() {}
- const fn assert_sync<T: Sync>() {}
- assert_send::<SharedPayload>();
- assert_sync::<SharedPayload>();
- assert!(size_of::<SharedPayload>() == size_of::<*const c_void>());
- assert!(align_of::<SharedPayload>() == align_of::<*const c_void>());
-};
diff --git a/Libraries/LibWeb/Rust/src/css/import_rule.rs b/Libraries/LibWeb/Rust/src/css/import_rule.rs
index 1f34a3b631e..5f25357aabd 100644
--- a/Libraries/LibWeb/Rust/src/css/import_rule.rs
+++ b/Libraries/LibWeb/Rust/src/css/import_rule.rs
@@ -8,12 +8,12 @@ use crate::css::css_string::CssString;
use crate::css::ffi_support::{FfiUtf16View, OwnedArc};
use crate::css::parser::query_parser::FfiQueryHandle;
use crate::css::scope_selectors::ScopeSelectors;
-use crate::css::style_value::StyleValueData;
+use crate::css::style_value_arc::StyleValueArc;
use std::ffi::c_void;
use std::sync::Arc;
pub struct ImportRuleData {
- pub(crate) url: Arc<StyleValueData>,
+ pub(crate) url: StyleValueArc,
pub(crate) layer: Option<CssString>,
pub(crate) supports: Option<Arc<FfiQueryHandle>>,
pub(crate) scope: Option<Arc<ScopeSelectors>>,
@@ -49,7 +49,7 @@ pub extern "C" fn rust_import_rule_release(rule: OwnedArc<ImportRuleData>) {
pub extern "C" fn rust_import_rule_view(rule: &ImportRuleData) -> FfiImportRuleView<'_> {
let layer = rule.layer.as_ref().map_or(&[][..], CssString::units);
FfiImportRuleView {
- url: Arc::as_ptr(&rule.url).cast(),
+ url: StyleValueArc::as_ptr(&rule.url).cast(),
has_layer: rule.layer.is_some(),
layer: FfiUtf16View::from_utf16(layer),
supports: rule.supports.as_ref().map_or(std::ptr::null(), Arc::as_ptr),
diff --git a/Libraries/LibWeb/Rust/src/css/inline_style_blocks.rs b/Libraries/LibWeb/Rust/src/css/inline_style_blocks.rs
new file mode 100644
index 00000000000..9c7ec118fa6
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/inline_style_blocks.rs
@@ -0,0 +1,277 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The declaration blocks of a document's style attributes, by their text, so that elements that
+//! write the same text hold one block.
+
+use crate::css::css_tokenizer::TokenizerInput;
+use crate::css::declaration_block::{DeclarationBlock, SharedDeclarationBlock};
+use crate::css::ffi_support::{FfiUtf16View, ascii_lowercase};
+use crate::css::style_value::RetainedString;
+use std::collections::HashMap;
+use std::hash::{BuildHasher, Hasher};
+
+struct InlineStyleEntry {
+ /// One byte per unit when the text is ASCII, as most style attributes are.
+ text: RetainedString,
+ quirks: bool,
+ block: SharedDeclarationBlock,
+}
+
+/// A document's style attribute blocks, by their text and the quirks mode they were parsed in.
+pub struct InlineStyleBlocks {
+ /// The entries by the hash of their text and quirks mode, one per hash.
+ blocks: HashMap<u64, InlineStyleEntry>,
+ /// The entries whose hash an entry of `blocks` already has, which a 64-bit hash makes rare.
+ collisions: Vec<InlineStyleEntry>,
+ /// How many entries the cache holds before it drops those only it still holds: twice as many
+ /// as the last drop kept, so dropping costs a constant per entry inserted.
+ sweep_threshold: usize,
+ /// Keyed at random, so that a page cannot make many texts fall into one bucket.
+ hasher: std::collections::hash_map::RandomState,
+}
+
+/// How many entries the cache holds before it first drops those only it still holds.
+const MINIMUM_SWEEP_THRESHOLD: usize = 256;
+
+fn units(text: TokenizerInput<'_>) -> impl Iterator<Item = u16> + '_ {
+ let (ascii, utf16): (&[u8], &[u16]) = match text {
+ TokenizerInput::Latin1(bytes) => (bytes, &[]),
+ TokenizerInput::Utf16(units) => (&[], units),
+ };
+ ascii.iter().map(|&byte| u16::from(byte)).chain(utf16.iter().copied())
+}
+
+/// Whether a block parsed from `text` may be shared by every element of the document that writes
+/// it. A value that resolves a URL, reads an attribute or is random per element is not, and an
+/// escape could spell the name of such a function.
+fn is_cacheable(text: TokenizerInput<'_>) -> bool {
+ const FUNCTIONS: [&[u8]; 5] = [b"url(", b"image-set(", b"src(", b"attr(", b"random("];
+ let lowered: Vec<u16> = units(text).map(ascii_lowercase).collect();
+ if lowered.contains(&u16::from(b'\\')) {
+ return false;
+ }
+ !FUNCTIONS.iter().any(|function| {
+ lowered.windows(function.len()).any(|window| {
+ window
+ .iter()
+ .zip(function.iter())
+ .all(|(&unit, &byte)| unit == u16::from(byte))
+ })
+ })
+}
+
+impl InlineStyleBlocks {
+ pub(crate) fn new() -> Self {
+ Self {
+ blocks: HashMap::new(),
+ collisions: Vec::new(),
+ sweep_threshold: MINIMUM_SWEEP_THRESHOLD,
+ hasher: std::collections::hash_map::RandomState::new(),
+ }
+ }
+
+ fn hash(&self, text: TokenizerInput<'_>, quirks: bool) -> u64 {
+ let mut hasher = self.hasher.build_hasher();
+ hasher.write_u8(u8::from(quirks));
+ for unit in units(text) {
+ hasher.write_u16(unit);
+ }
+ hasher.finish()
+ }
+
+ fn entry_count(&self) -> usize {
+ self.blocks.len() + self.collisions.len()
+ }
+
+ pub(crate) fn find(&self, text: TokenizerInput<'_>, quirks: bool) -> Option<SharedDeclarationBlock> {
+ let matches = |entry: &&InlineStyleEntry| entry.quirks == quirks && units(entry.text.units()).eq(units(text));
+ let entry = self.blocks.get(&self.hash(text, quirks))?;
+ if matches(&entry) {
+ return Some(entry.block.clone());
+ }
+ self.collisions.iter().find(matches).map(|entry| entry.block.clone())
+ }
+
+ pub(crate) fn insert(&mut self, text: TokenizerInput<'_>, quirks: bool, block: &SharedDeclarationBlock) {
+ if !is_cacheable(text) || self.find(text, quirks).is_some() {
+ return;
+ }
+ if self.entry_count() >= self.sweep_threshold {
+ self.sweep();
+ }
+ let entry = InlineStyleEntry {
+ text: RetainedString::from_text(text),
+ quirks,
+ block: block.clone(),
+ };
+ match self.blocks.entry(self.hash(text, quirks)) {
+ std::collections::hash_map::Entry::Vacant(slot) => {
+ slot.insert(entry);
+ }
+ std::collections::hash_map::Entry::Occupied(_) => self.collisions.push(entry),
+ }
+ }
+
+ /// Drops the entries whose block no element holds any more.
+ fn sweep(&mut self) {
+ self.blocks.retain(|_, entry| !entry.block.is_unique());
+ self.collisions.retain(|entry| !entry.block.is_unique());
+ self.sweep_threshold = (2 * self.entry_count()).max(MINIMUM_SWEEP_THRESHOLD);
+ }
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_inline_style_blocks_create() -> *mut InlineStyleBlocks {
+ Box::into_raw(Box::new(InlineStyleBlocks::new()))
+}
+
+/// # Safety
+/// `blocks` must come from `rust_inline_style_blocks_create` and not be used again.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_inline_style_blocks_destroy(blocks: *mut InlineStyleBlocks) {
+ assert!(!blocks.is_null());
+ drop(unsafe { Box::from_raw(blocks) });
+}
+
+/// A new declaration block holding the block of `text`, or null when no element wrote it.
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_inline_style_blocks_find(
+ blocks: &InlineStyleBlocks,
+ text: FfiUtf16View,
+ quirks: bool,
+) -> *mut DeclarationBlock {
+ let Some(text) = text.units() else {
+ return std::ptr::null_mut();
+ };
+ blocks.find(text, quirks).map_or(std::ptr::null_mut(), |block| {
+ Box::into_raw(Box::new(DeclarationBlock::new(block)))
+ })
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_inline_style_blocks_insert(
+ blocks: &mut InlineStyleBlocks,
+ text: FfiUtf16View,
+ quirks: bool,
+ block: &DeclarationBlock,
+) {
+ if let Some(text) = text.units() {
+ blocks.insert(text, quirks, &block.data());
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::css::parser::syntax_parser::parse_shared_block;
+ use crate::css::parser::value_parser::ParseContext;
+ use crate::css::style::pipeline::allocation_count::count_live_bytes;
+
+ fn parse(text: &str) -> SharedDeclarationBlock {
+ let units: Vec<u16> = text.encode_utf16().collect();
+ let context = ParseContext::default();
+ let parse = parse_shared_block(
+ TokenizerInput::Utf16(&units),
+ vec![crate::css::parser::syntax_parser::RuleContext::Style],
+ Some(&context),
+ false,
+ );
+ let block = unsafe {
+ Box::from_raw(crate::css::parser::syntax_parser::rust_css_syntax_parse_declaration_block(&parse))
+ };
+ block.data()
+ }
+
+ fn ascii(text: &str) -> TokenizerInput<'_> {
+ TokenizerInput::Latin1(text.as_bytes())
+ }
+
+ #[test]
+ fn equal_texts_share_one_block() {
+ let mut blocks = InlineStyleBlocks::new();
+ let text = "color: red; margin-left: 3.5px";
+ let block = parse(text);
+ blocks.insert(ascii(text), false, &block);
+ let utf16: Vec<u16> = text.encode_utf16().collect();
+ let hit = blocks.find(TokenizerInput::Utf16(&utf16), false).unwrap();
+ assert!(SharedDeclarationBlock::ptr_eq(&hit, &block));
+ assert!(blocks.find(ascii(text), true).is_none());
+ assert!(blocks.find(ascii("color: red"), false).is_none());
+ }
+
+ #[test]
+ fn texts_whose_values_differ_per_element_are_not_kept() {
+ let mut blocks = InlineStyleBlocks::new();
+ for text in [
+ "background: URL(a.png)",
+ "background-image: image-set(\"a.png\" 1x)",
+ "width: attr(data-w px)",
+ "width: random(1px, 2px)",
+ "c\\olor: red",
+ ] {
+ blocks.insert(ascii(text), false, &parse(text));
+ assert!(blocks.find(ascii(text), false).is_none(), "{text}");
+ }
+ }
+
+ #[test]
+ fn a_sweep_drops_the_blocks_only_the_cache_holds() {
+ let mut blocks = InlineStyleBlocks::new();
+ let held = parse("order: 0");
+ blocks.insert(ascii("order: 0"), false, &held);
+ for index in 1..=MINIMUM_SWEEP_THRESHOLD {
+ let text = format!("order: {index}");
+ blocks.insert(ascii(&text), false, &parse(&text));
+ }
+ assert_eq!(blocks.entry_count(), 2);
+ assert!(blocks.find(ascii("order: 0"), false).is_some());
+ assert_eq!(blocks.sweep_threshold, MINIMUM_SWEEP_THRESHOLD);
+ }
+
+ #[test]
+ fn a_hit_costs_the_element_its_declaration_block_handle() {
+ const COUNT: usize = 500;
+ let mut blocks = InlineStyleBlocks::new();
+ let text = "color: red; margin-left: 3.5px";
+ blocks.insert(ascii(text), false, &parse(text));
+ let mut handles = Vec::with_capacity(COUNT);
+ let ((), bytes) = count_live_bytes(|| {
+ for _ in 0..COUNT {
+ handles.push(Box::new(DeclarationBlock::new(
+ blocks.find(ascii(text), false).unwrap(),
+ )));
+ }
+ });
+ let per_element = bytes as f64 / COUNT as f64;
+ eprintln!("inline style, text another element repeats {per_element:.1} B (ceiling 24; 8 B, cached)");
+ assert!(per_element <= 24.0);
+ }
+
+ #[test]
+ fn own_text_costs_its_block_handle_and_entry() {
+ const COUNT: usize = 500;
+ // NB: Pooled values in pairs no other text repeats, so that each text parses a block of its own.
+ let texts: Vec<String> = (0..COUNT)
+ .map(|index| format!("z-index: {}; order: {}", index % 100, index / 100))
+ .collect();
+ let mut blocks = InlineStyleBlocks::new();
+ for text in &texts {
+ parse(text);
+ }
+ let mut handles = Vec::with_capacity(COUNT);
+ let ((), bytes) = count_live_bytes(|| {
+ for text in &texts {
+ let block = parse(text);
+ blocks.insert(ascii(text), false, &block);
+ handles.push(Box::new(DeclarationBlock::new(block)));
+ }
+ });
+ let per_element = bytes as f64 / COUNT as f64;
+ eprintln!("inline style, own text, 2 declarations {per_element:.1} B (ceiling 176; 16 + 16 B per declaration)");
+ assert!(per_element <= 176.0);
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/keyframes.rs b/Libraries/LibWeb/Rust/src/css/keyframes.rs
index aeb9420c4ac..67689063ddd 100644
--- a/Libraries/LibWeb/Rust/src/css/keyframes.rs
+++ b/Libraries/LibWeb/Rust/src/css/keyframes.rs
@@ -4,12 +4,12 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-use crate::css::declaration_block::{DeclarationBlock, DeclarationBlockData};
+use crate::css::declaration_block::{DeclarationBlock, SharedDeclarationBlock};
use std::sync::Arc;
pub struct KeyframeData {
pub(crate) keys: Box<[f64]>,
- pub(crate) declarations: Arc<DeclarationBlockData>,
+ pub(crate) declarations: SharedDeclarationBlock,
}
pub struct FfiKeyframe {
@@ -26,7 +26,7 @@ impl FfiKeyframe {
&self.data.keys
}
- pub(crate) fn declarations(&self) -> Arc<DeclarationBlockData> {
+ pub(crate) fn declarations(&self) -> SharedDeclarationBlock {
self.declarations.data()
}
diff --git a/Libraries/LibWeb/Rust/src/css/media_list.rs b/Libraries/LibWeb/Rust/src/css/media_list.rs
index 2620c11bcf6..05d279414ec 100644
--- a/Libraries/LibWeb/Rust/src/css/media_list.rs
+++ b/Libraries/LibWeb/Rust/src/css/media_list.rs
@@ -7,17 +7,19 @@
use crate::css::css_tokenizer::TokenizerInput;
use crate::css::ffi_support::{FfiUtf16View, OwnedBox};
use crate::css::parser::query_parser::{
- FfiMediaEnvironment, FfiQueryHandle, MediaEnvironment, VisitQuerySerialization, invalid_media_query,
+ FfiMediaEnvironment, FfiQueryHandle, MediaEnvironment, MediaQuery, VisitQuerySerialization, invalid_media_query,
media_query_handle, parse_media_query_list, resolve_query_feature,
};
+use crate::css::thin_slice::ThinSlice;
use std::cell::RefCell;
use std::ffi::c_void;
use std::rc::Rc;
use std::sync::Arc;
+/// A media list's queries, held by one pointer with their count before them.
#[derive(Clone, Default)]
pub struct MediaListData {
- pub(crate) queries: Vec<Arc<FfiQueryHandle>>,
+ pub(crate) queries: ThinSlice<Arc<FfiQueryHandle>>,
}
const _: () = {
@@ -25,6 +27,14 @@ const _: () = {
assert_send_sync::<MediaListData>();
};
+impl MediaListData {
+ pub(crate) fn from_queries(queries: Vec<MediaQuery>) -> Self {
+ Self {
+ queries: queries.into_iter().map(media_query_handle).collect(),
+ }
+ }
+}
+
struct MediaListState {
data: Arc<MediaListData>,
matches: Vec<bool>,
@@ -80,20 +90,16 @@ impl MediaList {
}
fn parse(source: TokenizerInput<'_>) -> MediaListData {
- MediaListData {
- queries: parse_media_query_list(source, &resolve_query_feature)
- .unwrap_or_else(|| vec![invalid_media_query()])
- .into_iter()
- .map(media_query_handle)
- .collect(),
- }
+ MediaListData::from_queries(
+ parse_media_query_list(source, &resolve_query_feature).unwrap_or_else(|| vec![invalid_media_query()]),
+ )
}
fn parse_medium(source: TokenizerInput<'_>) -> Option<Arc<FfiQueryHandle>> {
let mut data = parse(source);
match data.queries.len() {
0 => Some(media_query_handle(invalid_media_query())),
- 1 => data.queries.pop(),
+ 1 => Some(data.queries.remove(0)),
_ => None,
}
}
diff --git a/Libraries/LibWeb/Rust/src/css/mod.rs b/Libraries/LibWeb/Rust/src/css/mod.rs
index 2c2d4c85038..a9061aaa220 100644
--- a/Libraries/LibWeb/Rust/src/css/mod.rs
+++ b/Libraries/LibWeb/Rust/src/css/mod.rs
@@ -39,6 +39,7 @@ pub(crate) mod font_matching;
pub(crate) mod function_signature;
pub(crate) mod host_shared;
pub(crate) mod import_rule;
+pub mod inline_style_blocks;
pub(crate) mod keyframes;
pub(crate) mod layer_names;
pub(crate) mod math_functions;
@@ -52,16 +53,20 @@ pub(crate) mod retained_fly_string;
pub(crate) mod rule;
pub(crate) mod scope_selectors;
pub(crate) mod selector;
+mod selector_arena;
mod selector_operations;
pub(crate) mod selector_parser;
mod selector_serialization;
+pub(crate) mod selector_tree;
pub(crate) mod serialize;
pub mod style;
pub mod style_compute;
pub(crate) mod style_rule;
pub(crate) mod style_sheet;
pub(crate) mod style_value;
+pub(crate) mod style_value_arc;
pub mod table_group_builder;
+pub(crate) mod thin_slice;
pub mod transition;
pub(crate) mod value_codes;
diff --git a/Libraries/LibWeb/Rust/src/css/parser/arbitrary_substitution.rs b/Libraries/LibWeb/Rust/src/css/parser/arbitrary_substitution.rs
index fbfe9aa1d96..eefa8c9499b 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/arbitrary_substitution.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/arbitrary_substitution.rs
@@ -8,8 +8,6 @@ use crate::css::css_tokenizer::ParserTokenKind;
use crate::css::parser::component_value::{ComponentKind, ComponentValue};
use crate::css::parser::value_parser::equals_ascii_case_insensitive;
use std::collections::HashSet;
-use std::sync::RwLock;
-use std::sync::atomic::{AtomicU64, Ordering};
#[derive(Clone, Copy)]
pub(crate) enum ArbitrarySubstitutionFunction {
@@ -312,27 +310,47 @@ pub(crate) fn collect_arbitrary_substitution_function_presence(
Ok(())
}
-/// The attribute names an `attr()` anywhere in the process can read, ASCII-lowercased, or every
-/// name once one computes its name. A style engine copies an attribute's value text only for names
+/// The attribute names the `attr()`s a document holds can read, ASCII-lowercased, or every name
+/// once one computes its name. The document's host copies an attribute's value text only for names
/// a selector or this set can read, and backfills its elements when the set grows.
-struct AttrNamesRead {
+#[derive(Default)]
+pub(crate) struct AttrNamesRead {
any_name: bool,
names: HashSet<Box<[u16]>>,
+ generation: u64,
}
-static ATTR_NAMES_READ: RwLock<Option<AttrNamesRead>> = RwLock::new(None);
-static ATTR_NAMES_READ_GENERATION: AtomicU64 = AtomicU64::new(0);
+impl AttrNamesRead {
+ /// Grows with every name an `attr()` can newly read.
+ pub(crate) fn generation(&self) -> u64 {
+ self.generation
+ }
-/// Grows with every name an `attr()` can newly read.
-pub(crate) fn attr_names_read_generation() -> u64 {
- ATTR_NAMES_READ_GENERATION.load(Ordering::Acquire)
-}
+ /// Whether an `attr()` may read an attribute with this local name.
+ pub(crate) fn may_read(&self, local_name: &[u16]) -> bool {
+ self.any_name || self.names.contains(ascii_lowercase(local_name).as_slice())
+ }
+
+ /// Record what the `attr()` functions of a declared value can read.
+ pub(crate) fn note(&mut self, values: &[ComponentValue]) {
+ let mut names = Vec::new();
+ let mut any_name = false;
+ collect_attr_names_read(values, &mut names, &mut any_name);
+ let mut grew = any_name && !self.any_name;
+ self.any_name |= any_name;
+ for name in names {
+ grew |= self.names.insert(name.into_boxed_slice());
+ }
+ if grew {
+ self.generation += 1;
+ }
+ }
-/// Whether an `attr()` may read an attribute with this local name.
-pub(crate) fn attr_may_read_name(local_name: &[u16]) -> bool {
- let read = ATTR_NAMES_READ.read().expect("attr() name set poisoned");
- read.as_ref()
- .is_some_and(|read| read.any_name || read.names.contains(ascii_lowercase(local_name).as_slice()))
+ /// The bytes the names hold on the heap.
+ pub(crate) fn heap_size(&self) -> usize {
+ crate::heap_size::set_bytes(&self.names)
+ + self.names.iter().map(|name| size_of_val::<[u16]>(name)).sum::<usize>()
+ }
}
fn ascii_lowercase(text: &[u16]) -> Vec<u16> {
@@ -385,34 +403,6 @@ fn collect_attr_names_read(values: &[ComponentValue], names: &mut Vec<Vec<u16>>,
}
}
-/// Record what the `attr()` functions of a declared value can read, before any engine resolves it.
-pub(crate) fn note_attr_names_read_by(values: &[ComponentValue]) {
- let mut names = Vec::new();
- let mut any_name = false;
- collect_attr_names_read(values, &mut names, &mut any_name);
- {
- let read = ATTR_NAMES_READ.read().expect("attr() name set poisoned");
- if read.as_ref().is_some_and(|read| {
- read.any_name || (!any_name && names.iter().all(|name| read.names.contains(name.as_slice())))
- }) {
- return;
- }
- }
- let mut read = ATTR_NAMES_READ.write().expect("attr() name set poisoned");
- let read = read.get_or_insert_with(|| AttrNamesRead {
- any_name: false,
- names: HashSet::new(),
- });
- let mut grew = any_name && !read.any_name;
- read.any_name |= any_name;
- for name in names {
- grew |= read.names.insert(name.into_boxed_slice());
- }
- if grew {
- ATTR_NAMES_READ_GENERATION.fetch_add(1, Ordering::AcqRel);
- }
-}
-
pub(crate) fn declaration_value_is_valid(values: &[ComponentValue]) -> bool {
let mut position = 0;
consume_declaration_value_as_span(values, &mut position, None, false) && position == values.len()
diff --git a/Libraries/LibWeb/Rust/src/css/parser/calc_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/calc_parser.rs
index d4e85390593..f58e41cf723 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/calc_parser.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/calc_parser.rs
@@ -26,6 +26,8 @@ use crate::css::parser::component_value::{ComponentKind, ComponentValue};
use crate::css::parser::positions_shapes_parser::{parse_anchor_function, parse_anchor_size_function};
use crate::css::property_metadata::property_name;
use crate::css::style_compute::LENGTH_UNIT_NAMES;
+use crate::css::style_value::RandomValueSharingPayload;
+use crate::css::style_value::StyleValueBox;
use crate::css::style_value::{RetainedStyleValueData, StyleValueData};
use crate::css::value_codes::VALUE_TYPE_NUMBER;
use std::sync::Arc;
@@ -656,13 +658,15 @@ fn parse_random_value_sharing(
}
_ => return Err(CalcParseError::Invalid),
};
- return Ok(Some(StyleValueData::RandomValueSharing {
- fixed_value: RetainedStyleValueData::from_owned(fixed_value),
- is_auto: false,
- has_name: false,
- name: CssString::none(),
- element_shared: false,
- }));
+ return Ok(Some(StyleValueData::RandomValueSharing(StyleValueBox::new(
+ RandomValueSharingPayload {
+ fixed_value: RetainedStyleValueData::from_owned(fixed_value),
+ is_auto: false,
+ has_name: false,
+ name: CssString::none(),
+ element_shared: false,
+ },
+ ))));
}
let mut has_explicit_auto = false;
@@ -695,13 +699,15 @@ fn parse_random_value_sharing(
return Ok(None);
}
let (is_auto, name) = dashed_ident.map_or((true, auto_name), |name| (false, name));
- Ok(Some(StyleValueData::RandomValueSharing {
- fixed_value: RetainedStyleValueData::none(),
- is_auto,
- has_name: true,
- name,
- element_shared,
- }))
+ Ok(Some(StyleValueData::RandomValueSharing(StyleValueBox::new(
+ RandomValueSharingPayload {
+ fixed_value: RetainedStyleValueData::none(),
+ is_auto,
+ has_name: true,
+ name,
+ element_shared,
+ },
+ ))))
}
fn parse_random(arguments: &[&[ComponentValue]], context: CalcParserContext) -> Result<Arc<CalcNode>> {
@@ -736,13 +742,15 @@ fn parse_random(arguments: &[&[ComponentValue]], context: CalcParserContext) ->
return Err(CalcParseError::Invalid);
}
require_consistent(&types)?;
- let sharing = explicit_sharing.unwrap_or(StyleValueData::RandomValueSharing {
- fixed_value: RetainedStyleValueData::none(),
- is_auto: true,
- has_name: true,
- name: auto_name,
- element_shared: false,
- });
+ let sharing = explicit_sharing.unwrap_or(StyleValueData::RandomValueSharing(StyleValueBox::new(
+ RandomValueSharingPayload {
+ fixed_value: RetainedStyleValueData::none(),
+ is_auto: true,
+ has_name: true,
+ name: auto_name,
+ element_shared: false,
+ },
+ )));
Ok(Arc::new(CalcNode::Random {
min: nodes[0].clone(),
max: nodes[1].clone(),
diff --git a/Libraries/LibWeb/Rust/src/css/parser/color_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/color_parser.rs
index 742bb7f2c9f..0d745636845 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/color_parser.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/color_parser.rs
@@ -20,6 +20,9 @@ use crate::css::named_colors::named_color_from_name;
use crate::css::parser::calc_parser::{CalcParseError, CalcParserContext, parse_a_calc_function_node};
use crate::css::parser::component_value::{ComponentKind, ComponentValue};
use crate::css::parser::token_stream::TokenStream;
+use crate::css::style_value::{
+ CalculatedPayload, ColorFunctionPayload, ColorMixPayload, LightDarkPayload, StyleValueBox,
+};
use crate::css::style_value::{
ColorBase, RetainedNumericRangeList, RetainedStyleValueData, RetainedStyleValueDataList, StyleValueData,
};
@@ -65,7 +68,7 @@ fn make_color_function(
origin_color: Option<StyleValueData>,
) -> StyleValueData {
let [channel_0, channel_1, channel_2] = channels;
- StyleValueData::ColorFunction {
+ StyleValueData::ColorFunction(StyleValueBox::new(ColorFunctionPayload {
color_base: color_base(Some(color_type), syntax),
channel_0: retained(channel_0),
channel_1: retained(channel_1),
@@ -74,7 +77,7 @@ fn make_color_function(
has_name: name.is_some(),
name: name.unwrap_or_else(CssString::none),
origin_color: retained_optional(origin_color),
- }
+ }))
}
fn make_legacy_color(rgba: [u8; 4], name: Option<&[u16]>) -> StyleValueData {
@@ -397,7 +400,7 @@ fn parse_calculated_numeric(
NumericKind::Percentage => VALUE_TYPE_PERCENTAGE,
};
Some(ParsedNumeric {
- value: StyleValueData::Calculated {
+ value: StyleValueData::Calculated(StyleValueBox::new(CalculatedPayload {
rust_calculation: crate::css::calc::CalcNodeHandle::from_arc(root),
resolve_as_is_number: false,
resolve_as_base: 0,
@@ -410,7 +413,7 @@ fn parse_calculated_numeric(
accepted_range.0,
accepted_range.1,
),
- },
+ })),
kind,
})
}
@@ -902,7 +905,8 @@ fn parse_mix_percentage(context: &ParseContext, property: u16, stream: &mut Toke
stream.position = start;
return None;
}
- StyleValueData::Calculated { accepted_ranges, .. } => {
+ StyleValueData::Calculated(calculated_payload) => {
+ let CalculatedPayload { accepted_ranges, .. } = &mut **calculated_payload;
*accepted_ranges = RetainedNumericRangeList::from_single_numeric_range(VALUE_TYPE_PERCENTAGE, 0.0, 100.0);
}
_ => {}
@@ -952,12 +956,12 @@ fn parse_color_mix(context: &ParseContext, property: u16, values: &[ComponentVal
}
stream.discard_a_token();
}
- Some(StyleValueData::ColorMix {
+ Some(StyleValueData::ColorMix(StyleValueBox::new(ColorMixPayload {
color_base: color_base(None, COLOR_SYNTAX_MODERN),
color_interpolation_method: retained_optional(method),
colors: RetainedStyleValueDataList::from_retained_values(colors),
percentages: RetainedStyleValueDataList::from_retained_values(percentages),
- })
+ })))
}
fn parse_light_dark_or_contrast(
@@ -988,11 +992,11 @@ fn parse_light_dark_or_contrast(
if stream.has_next_token() {
return None;
}
- Some(StyleValueData::LightDark {
+ Some(StyleValueData::LightDark(StyleValueBox::new(LightDarkPayload {
color_base: color_base(None, COLOR_SYNTAX_MODERN),
light: retained(first),
dark: retained(second),
- })
+ })))
}
fn parse_color_function_component(
@@ -1105,13 +1109,9 @@ pub(crate) fn parse_color_value(
}
pub(crate) fn color_syntax(value: &StyleValueData) -> u8 {
- match value {
- StyleValueData::ContrastColor { color_base, .. }
- | StyleValueData::ColorFunction { color_base, .. }
- | StyleValueData::ColorMix { color_base, .. }
- | StyleValueData::LightDark { color_base, .. } => color_base.color_syntax,
- _ => COLOR_SYNTAX_LEGACY,
- }
+ value
+ .color_base()
+ .map_or(COLOR_SYNTAX_LEGACY, |color_base| color_base.color_syntax)
}
#[cfg(test)]
diff --git a/Libraries/LibWeb/Rust/src/css/parser/descriptor_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/descriptor_parser.rs
index feb859758fd..dd8dd7a3261 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/descriptor_parser.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/descriptor_parser.rs
@@ -4,8 +4,6 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#![allow(clippy::arc_with_non_send_sync)]
-
use crate::css::css_enums::{
keyword, keyword_from_ascii_case_insensitive, keyword_to_counter_style_name_keyword,
keyword_to_counter_style_system, keyword_to_page_size,
@@ -26,14 +24,16 @@ use crate::css::parser::value_parser::{
};
use crate::css::property_metadata::property_id;
use crate::css::style_compute::FfiLengthResolutionContext;
+use crate::css::style_value::CounterStyleSystemPayload;
+use crate::css::style_value::StyleValueBox;
use crate::css::style_value::{CssString, RetainedStyleValueData, StyleValueData};
+use crate::css::style_value_arc::StyleValueArc;
use std::ffi::c_void;
-use std::sync::Arc;
#[derive(Clone)]
pub(crate) struct ParsedDescriptor {
pub id: u8,
- pub value: Arc<StyleValueData>,
+ pub value: StyleValueArc,
}
fn non_whitespace(values: &[ComponentValue]) -> Vec<&ComponentValue> {
@@ -153,12 +153,16 @@ fn parse_counter_style_system(context: &ParseContext, values: &[ComponentValue])
let parsed_keyword = keyword_from_ascii_case_insensitive(identifier)?;
if let Some(system) = keyword_to_counter_style_system(parsed_keyword) {
stream.discard_whitespace();
- return stream.is_empty().then_some(StyleValueData::CounterStyleSystem {
- kind: 0,
- system,
- first_symbol: RetainedStyleValueData::none(),
- name: CssString::none(),
- });
+ return stream
+ .is_empty()
+ .then_some(StyleValueData::CounterStyleSystem(StyleValueBox::new(
+ CounterStyleSystemPayload {
+ kind: 0,
+ system,
+ first_symbol: RetainedStyleValueData::none(),
+ name: CssString::none(),
+ },
+ )));
}
if parsed_keyword == keyword::FIXED {
stream.discard_whitespace();
@@ -173,12 +177,16 @@ fn parse_counter_style_system(context: &ParseContext, values: &[ComponentValue])
)?)
};
stream.discard_whitespace();
- return stream.is_empty().then_some(StyleValueData::CounterStyleSystem {
- kind: 1,
- system: 0,
- first_symbol,
- name: CssString::none(),
- });
+ return stream
+ .is_empty()
+ .then_some(StyleValueData::CounterStyleSystem(StyleValueBox::new(
+ CounterStyleSystemPayload {
+ kind: 1,
+ system: 0,
+ first_symbol,
+ name: CssString::none(),
+ },
+ )));
}
if parsed_keyword == keyword::EXTENDS {
stream.discard_whitespace();
@@ -187,12 +195,16 @@ fn parse_counter_style_system(context: &ParseContext, values: &[ComponentValue])
unreachable!();
};
stream.discard_whitespace();
- return stream.is_empty().then_some(StyleValueData::CounterStyleSystem {
- kind: 2,
- system: 0,
- first_symbol: RetainedStyleValueData::none(),
- name: custom_ident,
- });
+ return stream
+ .is_empty()
+ .then_some(StyleValueData::CounterStyleSystem(StyleValueBox::new(
+ CounterStyleSystemPayload {
+ kind: 2,
+ system: 0,
+ first_symbol: RetainedStyleValueData::none(),
+ name: custom_ident,
+ },
+ )));
}
None
}
@@ -300,19 +312,19 @@ fn parse_value_type(
match value_type {
DescriptorValueType::FamilyName => {
match parse_font_descriptor(context, FontDescriptorKind::FamilyName, values) {
- ParseOutcome::Parsed(value) => Some(Arc::unwrap_or_clone(value)),
+ ParseOutcome::Parsed(value) => Some(StyleValueArc::unwrap_or_clone(value)),
_ => None,
}
}
DescriptorValueType::FontSrcList => {
match parse_font_descriptor(context, FontDescriptorKind::SourceList, values) {
- ParseOutcome::Parsed(value) => Some(Arc::unwrap_or_clone(value)),
+ ParseOutcome::Parsed(value) => Some(StyleValueArc::unwrap_or_clone(value)),
_ => None,
}
}
DescriptorValueType::UnicodeRangeTokens => {
match parse_font_descriptor(context, FontDescriptorKind::UnicodeRangeList, values) {
- ParseOutcome::Parsed(value) => Some(Arc::unwrap_or_clone(value)),
+ ParseOutcome::Parsed(value) => Some(StyleValueArc::unwrap_or_clone(value)),
_ => None,
}
}
@@ -418,7 +430,7 @@ fn parse_value_type(
}
) =>
{
- Some(Arc::unwrap_or_clone(value))
+ Some(StyleValueArc::unwrap_or_clone(value))
}
_ => None,
},
@@ -459,7 +471,7 @@ fn parse_with_metadata(
DescriptorSyntax::Keyword(keyword) => parse_keyword(values, keyword),
DescriptorSyntax::Property(property) => match parse_css_value(context, *property, values) {
ParseOutcome::Parsed(value) if metadata.allow_css_wide_keywords || !is_css_wide_keyword(&value) => {
- Some(Arc::unwrap_or_clone(value))
+ Some(StyleValueArc::unwrap_or_clone(value))
}
_ => None,
},
@@ -503,7 +515,7 @@ pub(crate) fn parse_descriptor(
};
Some(ParsedDescriptor {
id: metadata.id,
- value: Arc::new(value),
+ value: StyleValueArc::new(value),
})
}
@@ -532,7 +544,7 @@ pub extern "C" fn rust_parse_css_descriptor(
let mut source_units = Vec::with_capacity(source.len());
source.append_to(&mut source_units);
parse_descriptor(context, at_rule, &name_units, &values, &source_units)
- .map(|descriptor| Arc::into_raw(descriptor.value).cast::<c_void>())
+ .map(|descriptor| StyleValueArc::into_raw(descriptor.value).cast::<c_void>())
.unwrap_or(std::ptr::null())
}
@@ -541,7 +553,7 @@ mod tests {
use super::{consume_a_list_of_component_values, parse_descriptor, tokenize_for_parser};
use crate::css::parser::value_parser::ParseContext;
use crate::css::style_value::StyleValueData;
- use std::sync::Arc;
+ use crate::css::style_value_arc::StyleValueArc;
fn context() -> ParseContext<'static> {
ParseContext::default()
@@ -550,7 +562,7 @@ mod tests {
fn parse(at_rule: u8, name: &str, source: &str) -> Option<StyleValueData> {
let values = consume_a_list_of_component_values(tokenize_for_parser(source.as_bytes())).unwrap();
let source = source.encode_utf16().collect::<Vec<_>>();
- Arc::into_inner(
+ StyleValueArc::into_inner(
parse_descriptor(
&context(),
at_rule,
diff --git a/Libraries/LibWeb/Rust/src/css/parser/fonts_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/fonts_parser.rs
index c2d807d9f32..30216089018 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/fonts_parser.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/fonts_parser.rs
@@ -4,8 +4,6 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#![allow(clippy::arc_with_non_send_sync)]
-
use super::arbitrary_substitution::contains_arbitrary_substitution_function;
use super::component_value::ComponentValue;
use super::token_stream::TokenStream;
@@ -22,14 +20,14 @@ use crate::css::css_enums::{
};
use crate::css::css_string::CssString;
use crate::css::property_metadata::property_id;
+use crate::css::style_value::{FontSourcePayload, FunctionPayload, OpenTypeTaggedPayload, StyleValueBox, UrlPayload};
use crate::css::style_value::{
RetainedByteList, RetainedRequestUrlModifierList, RetainedString, RetainedStyleValueData,
RetainedStyleValueDataList, StyleValueData,
};
-use std::sync::Arc;
+use crate::css::style_value_arc::StyleValueArc;
-// NB: Mirrors Libraries/LibGfx/Font/FontSupport.cpp and the format-name mapping that this series
-// removed from Libraries/LibWeb/CSS/FontFace.cpp.
+// NB: Mirrors Libraries/LibGfx/Font/FontSupport.cpp.
const FONT_FORMAT_SUPPORT: &[(&str, bool)] = &[
("embedded-opentype", false),
("opentype", true),
@@ -374,10 +372,10 @@ fn parse_font_variant_alternates(context: &ParseContext, values: &[ComponentValu
return None;
}
let function_name = canonical_name.encode_utf16().collect::<Vec<_>>();
- parsed[slot] = Some(StyleValueData::Function {
+ parsed[slot] = Some(StyleValueData::Function(StyleValueBox::new(FunctionPayload {
name: CssString::from_utf16(&function_name),
value: retained(value_list(names, 1, true)),
- });
+ })));
}
let parsed = parsed.into_iter().flatten().collect::<Vec<_>>();
(!parsed.is_empty()).then(|| value_list(parsed, 0, true))
@@ -395,12 +393,12 @@ fn parse_opentype_tag(_context: &ParseContext, tokens: &mut TokenStream<'_>) ->
fn open_type_tagged(mode: u8, tag: [u16; 4], value: StyleValueData) -> StyleValueData {
let packed_tag = u32::from(tag[0]) << 24 | u32::from(tag[1]) << 16 | u32::from(tag[2]) << 8 | u32::from(tag[3]);
- StyleValueData::OpenTypeTagged {
+ StyleValueData::OpenTypeTagged(StyleValueBox::new(OpenTypeTaggedPayload {
mode,
tag_name: CssString::from_utf16(&tag),
packed_tag,
value: retained(value),
- }
+ }))
}
fn parse_font_feature_settings(context: &ParseContext, values: &[ComponentValue]) -> Option<StyleValueData> {
@@ -552,7 +550,7 @@ fn parse_font_source(context: &ParseContext, values: &[ComponentValue]) -> Optio
if tokens.has_next_token() {
return None;
}
- return Some(StyleValueData::FontSource {
+ return Some(StyleValueData::FontSource(StyleValueBox::new(FontSourcePayload {
is_local: true,
local_name: retained(local_name),
url: RetainedString::from_ascii(String::new()),
@@ -561,18 +559,18 @@ fn parse_font_source(context: &ParseContext, values: &[ComponentValue]) -> Optio
has_format: false,
format: crate::css::css_string::CssString::none(),
tech: RetainedByteList::from_bytes(Vec::new()),
- });
+ })));
}
let url = super::value_parser::parse_url_value(context, tokens.consume_a_token())?;
- let StyleValueData::Url {
+ let StyleValueData::Url(url_payload) = url else {
+ unreachable!()
+ };
+ let UrlPayload {
url,
url_type,
modifiers: url_modifiers,
- } = url
- else {
- unreachable!()
- };
+ } = url_payload.into_inner();
tokens.discard_whitespace();
let mut tech = Vec::new();
let mut format = None;
@@ -593,7 +591,7 @@ fn parse_font_source(context: &ParseContext, values: &[ComponentValue]) -> Optio
if tokens.has_next_token() {
return None;
}
- Some(StyleValueData::FontSource {
+ Some(StyleValueData::FontSource(StyleValueBox::new(FontSourcePayload {
is_local: false,
local_name: RetainedStyleValueData::none(),
url,
@@ -605,7 +603,7 @@ fn parse_font_source(context: &ParseContext, values: &[ComponentValue]) -> Optio
None => crate::css::css_string::CssString::none(),
},
tech: RetainedByteList::from_bytes(tech),
- })
+ })))
}
fn parse_unicode_range_text(text: &[u16]) -> Option<StyleValueData> {
@@ -698,7 +696,9 @@ pub(crate) fn parse_font_descriptor(
}
FontDescriptorKind::UnicodeRangeList => parse_unicode_ranges(values),
};
- parsed.map_or(ParseOutcome::Invalid, |parsed| ParseOutcome::Parsed(Arc::new(parsed)))
+ parsed.map_or(ParseOutcome::Invalid, |parsed| {
+ ParseOutcome::Parsed(StyleValueArc::new(parsed))
+ })
}
pub(crate) fn parse_font_property(context: &ParseContext, property: u16, values: &[ComponentValue]) -> ParseOutcome {
@@ -734,7 +734,7 @@ pub(crate) fn parse_font_property(context: &ParseContext, property: u16, values:
))
|| (keyword == keyword::NONE && property == property_id::FONT_VARIANT_LIGATURES))
{
- return ParseOutcome::Parsed(Arc::new(StyleValueData::Keyword { keyword }));
+ return ParseOutcome::Parsed(StyleValueArc::new(StyleValueData::Keyword { keyword }));
}
let parsed = match property {
property_id::FONT_FAMILY => parse_font_family(context, values),
@@ -748,7 +748,9 @@ pub(crate) fn parse_font_property(context: &ParseContext, property: u16, values:
property_id::FONT_VARIANT_NUMERIC => parse_font_variant_numeric(values),
_ => unreachable!(),
};
- parsed.map_or(ParseOutcome::Invalid, |parsed| ParseOutcome::Parsed(Arc::new(parsed)))
+ parsed.map_or(ParseOutcome::Invalid, |parsed| {
+ ParseOutcome::Parsed(StyleValueArc::new(parsed))
+ })
}
#[cfg(test)]
diff --git a/Libraries/LibWeb/Rust/src/css/parser/grid_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/grid_parser.rs
index 7ec119b5181..46fd85e3524 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/grid_parser.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/grid_parser.rs
@@ -5,10 +5,13 @@
*/
// Parsed values use the thread-confined shared graph owned by the C++ style objects.
-#![allow(clippy::arc_with_non_send_sync)]
+use crate::css::style_value::{
+ FunctionPayload, GridTemplateAreaPayload, GridTrackPlacementPayload, GridTrackSizeListPayload, ShorthandPayload,
+ StyleValueBox,
+};
+use crate::css::style_value_arc::StyleValueArc;
use std::collections::HashMap;
-use std::sync::Arc;
use super::value_parser::{
NumericRange, ParseContext, ParseOutcome, equals_ascii_case_insensitive, is_arbitrary_substitution_function,
@@ -36,11 +39,11 @@ fn grid_track_list(
preserve_line_name_sets: bool,
entries: Vec<RetainedGridTrackEntry>,
) -> StyleValueData {
- StyleValueData::GridTrackSizeList {
+ StyleValueData::GridTrackSizeList(StyleValueBox::new(GridTrackSizeListPayload {
is_subgrid,
preserve_line_name_sets,
entries: RetainedGridTrackEntryList::from_retained_entries(entries),
- }
+ }))
}
fn parse_keyword(value: &ComponentValue, expected: u16) -> Option<StyleValueData> {
@@ -221,10 +224,10 @@ fn parse_grid_track_size(
tokens.position = start;
return None;
}
- let function = StyleValueData::Function {
+ let function = StyleValueData::Function(StyleValueBox::new(FunctionPayload {
name: CssString::from_utf16(name),
value: RetainedStyleValueData::from_owned(value),
- };
+ }));
tokens.discard_a_token();
return Some(RetainedGridTrackEntry::size(function));
}
@@ -321,10 +324,10 @@ fn parse_grid_intrinsic_or_fixed_size(
tokens.position = start;
return None;
}
- let function = StyleValueData::Function {
+ let function = StyleValueData::Function(StyleValueBox::new(FunctionPayload {
name: CssString::from_utf16(name),
value: RetainedStyleValueData::from_owned(value),
- };
+ }));
tokens.discard_a_token();
return Some(RetainedGridTrackEntry::size(function));
}
@@ -703,14 +706,16 @@ fn parse_grid_track_placement(
tokens.discard_a_token();
tokens.discard_whitespace();
if tokens.is_empty() {
- return Some(StyleValueData::GridTrackPlacement {
- kind: 0,
- value: RetainedStyleValueData::none(),
- has_name: false,
- name: crate::css::css_string::CssString::none(),
- implicit_start_name: crate::css::css_string::CssString::none(),
- implicit_end_name: crate::css::css_string::CssString::none(),
- });
+ return Some(StyleValueData::GridTrackPlacement(StyleValueBox::new(
+ GridTrackPlacementPayload {
+ kind: 0,
+ value: RetainedStyleValueData::none(),
+ has_name: false,
+ name: crate::css::css_string::CssString::none(),
+ implicit_start_name: crate::css::css_string::CssString::none(),
+ implicit_end_name: crate::css::css_string::CssString::none(),
+ },
+ )));
}
return None;
}
@@ -786,62 +791,66 @@ fn parse_grid_track_placement(
&& (parsed_integer.is_some() || has_name)
&& !matches!(parsed_integer, Some(StyleValueData::Integer { value: 0 }))
{
- return Some(StyleValueData::GridTrackPlacement {
- kind: 2,
- value: parsed_integer.map_or_else(RetainedStyleValueData::none, RetainedStyleValueData::from_owned),
- has_name,
- name: name.unwrap_or_else(crate::css::css_string::CssString::none),
- implicit_start_name: implicit_start_name.unwrap_or_else(crate::css::css_string::CssString::none),
- implicit_end_name: implicit_end_name.unwrap_or_else(crate::css::css_string::CssString::none),
- });
+ return Some(StyleValueData::GridTrackPlacement(StyleValueBox::new(
+ GridTrackPlacementPayload {
+ kind: 2,
+ value: parsed_integer.map_or_else(RetainedStyleValueData::none, RetainedStyleValueData::from_owned),
+ has_name,
+ name: name.unwrap_or_else(crate::css::css_string::CssString::none),
+ implicit_start_name: implicit_start_name.unwrap_or_else(crate::css::css_string::CssString::none),
+ implicit_end_name: implicit_end_name.unwrap_or_else(crate::css::css_string::CssString::none),
+ },
+ )));
}
if is_span
&& (parsed_integer.is_some() || has_name)
&& !matches!(parsed_integer, Some(StyleValueData::Integer { value }) if value <= 0)
{
- return Some(StyleValueData::GridTrackPlacement {
- kind: 1,
- value: RetainedStyleValueData::from_owned(parsed_integer.unwrap_or(StyleValueData::Integer { value: 1 })),
- has_name,
- name: name.unwrap_or_else(crate::css::css_string::CssString::none),
- implicit_start_name: crate::css::css_string::CssString::none(),
- implicit_end_name: crate::css::css_string::CssString::none(),
- });
+ return Some(StyleValueData::GridTrackPlacement(StyleValueBox::new(
+ GridTrackPlacementPayload {
+ kind: 1,
+ value: RetainedStyleValueData::from_owned(
+ parsed_integer.unwrap_or(StyleValueData::Integer { value: 1 }),
+ ),
+ has_name,
+ name: name.unwrap_or_else(crate::css::css_string::CssString::none),
+ implicit_start_name: crate::css::css_string::CssString::none(),
+ implicit_end_name: crate::css::css_string::CssString::none(),
+ },
+ )));
}
None
}
fn auto_grid_track_placement() -> StyleValueData {
- StyleValueData::GridTrackPlacement {
+ StyleValueData::GridTrackPlacement(StyleValueBox::new(GridTrackPlacementPayload {
kind: 0,
value: RetainedStyleValueData::none(),
has_name: false,
name: crate::css::css_string::CssString::none(),
implicit_start_name: crate::css::css_string::CssString::none(),
implicit_end_name: crate::css::css_string::CssString::none(),
- }
+ }))
}
pub(crate) fn is_custom_ident_placement(value: &StyleValueData) -> bool {
matches!(
value,
- StyleValueData::GridTrackPlacement {
- kind: 2,
- value,
- has_name: true,
- ..
- } if value.optional_data().is_none()
+ StyleValueData::GridTrackPlacement(placement)
+ if placement.kind == 2 && placement.has_name && placement.value.optional_data().is_none()
)
}
fn grid_shorthand(property: u16, sub_properties: Vec<u16>, values: Vec<StyleValueData>) -> ParseOutcome {
- ParseOutcome::Parsed(Arc::new(StyleValueData::Shorthand {
- shorthand_property: property,
- sub_properties: RetainedPropertyIdList::from_property_ids(sub_properties),
- values: RetainedStyleValueDataList::from_retained_values(
- values.into_iter().map(RetainedStyleValueData::from_owned).collect(),
- ),
- }))
+ ParseOutcome::Parsed(StyleValueArc::new(StyleValueData::Shorthand(StyleValueBox::new(
+ ShorthandPayload {
+ shorthand_property: property,
+ sub_properties: RetainedPropertyIdList::from_property_ids(sub_properties),
+ values: RetainedStyleValueDataList::from_retained_values(
+ values.into_iter().map(RetainedStyleValueData::from_owned).collect(),
+ ),
+ },
+ ))))
}
fn slash_separated_components(values: &[ComponentValue]) -> Option<Vec<&[ComponentValue]>> {
@@ -955,11 +964,11 @@ fn initial_grid_values() -> [StyleValueData; 6] {
keyword: keyword::AUTO,
})],
),
- StyleValueData::GridTemplateArea {
+ StyleValueData::GridTemplateArea(StyleValueBox::new(GridTemplateAreaPayload {
grid_areas: RetainedGridAreaList::from_retained_elements(Vec::new()),
row_count: 0,
column_count: 0,
- },
+ })),
grid_track_list(false, false, Vec::new()),
grid_track_list(false, false, Vec::new()),
]
@@ -1301,10 +1310,12 @@ fn parse_grid_template_areas(_context: &ParseContext, values: &[ComponentValue])
if parse_keyword(tokens.next_token(), keyword::NONE).is_some() {
tokens.discard_a_token();
tokens.discard_whitespace();
- return tokens.is_empty().then(|| StyleValueData::GridTemplateArea {
- grid_areas: RetainedGridAreaList::from_retained_elements(Vec::new()),
- row_count: 0,
- column_count: 0,
+ return tokens.is_empty().then(|| {
+ StyleValueData::GridTemplateArea(StyleValueBox::new(GridTemplateAreaPayload {
+ grid_areas: RetainedGridAreaList::from_retained_elements(Vec::new()),
+ row_count: 0,
+ column_count: 0,
+ }))
});
}
let mut rows = Vec::new();
@@ -1365,11 +1376,13 @@ fn parse_grid_template_areas(_context: &ParseContext, values: &[ComponentValue])
));
}
}
- Some(StyleValueData::GridTemplateArea {
- grid_areas: RetainedGridAreaList::from_retained_elements(areas),
- row_count: rows.len(),
- column_count: column_count.unwrap_or(0),
- })
+ Some(StyleValueData::GridTemplateArea(StyleValueBox::new(
+ GridTemplateAreaPayload {
+ grid_areas: RetainedGridAreaList::from_retained_elements(areas),
+ row_count: rows.len(),
+ column_count: column_count.unwrap_or(0),
+ },
+ )))
}
fn contains_math_function(values: &[ComponentValue]) -> bool {
@@ -1428,7 +1441,7 @@ pub(crate) fn parse_grid_property(context: &ParseContext, property: u16, values:
_ => return ParseOutcome::NotHandled,
};
if let Some(parsed) = parsed {
- ParseOutcome::Parsed(Arc::new(parsed))
+ ParseOutcome::Parsed(StyleValueArc::new(parsed))
} else if contains_deferred_function(values) || contains_math_function(values) {
ParseOutcome::NotHandled
} else {
@@ -1539,9 +1552,10 @@ mod tests {
let ParseOutcome::Parsed(value) = parse(property, source) else {
panic!("shorthand should parse: {source}");
};
- let StyleValueData::Shorthand { values, .. } = &*value else {
+ let StyleValueData::Shorthand(shorthand_payload) = &*value else {
panic!("value should be a shorthand: {source}");
};
+ let ShorthandPayload { values, .. } = &**shorthand_payload;
assert_eq!(values.as_slice().len(), expected_values);
}
for (property, source) in [
@@ -1571,9 +1585,10 @@ mod tests {
let ParseOutcome::Parsed(value) = parse(property, source) else {
panic!("shorthand should parse: {source}");
};
- let StyleValueData::Shorthand { values, .. } = &*value else {
+ let StyleValueData::Shorthand(shorthand_payload) = &*value else {
panic!("value should be a shorthand: {source}");
};
+ let ShorthandPayload { values, .. } = &**shorthand_payload;
assert_eq!(values.as_slice().len(), expected_values);
}
for (property, source) in [
diff --git a/Libraries/LibWeb/Rust/src/css/parser/images_gradients_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/images_gradients_parser.rs
index 8166303e68b..09885df6b70 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/images_gradients_parser.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/images_gradients_parser.rs
@@ -6,9 +6,11 @@
//! CSS image and gradient parsing, mirroring ValueParsing.cpp and GradientParsing.cpp.
-#![allow(clippy::arc_with_non_send_sync)]
-
-use std::sync::Arc;
+use crate::css::style_value::{
+ ConicGradientPayload, ImagePayload, ImageSetPayload, LightDarkPayload, LinearGradientPayload,
+ RadialGradientPayload, RadialSizePayload, StyleValueBox, UrlPayload,
+};
+use crate::css::style_value_arc::StyleValueArc;
use crate::css::css_string::CssString;
use crate::css::css_tokenizer::ParserTokenKind;
@@ -53,29 +55,29 @@ fn image_resource_context() -> ImageResourceContext {
}
fn image_from_url(url: StyleValueData) -> Option<StyleValueData> {
- let StyleValueData::Url {
+ let StyleValueData::Url(url_payload) = url else {
+ return None;
+ };
+ let UrlPayload {
url,
url_type,
modifiers,
- } = url
- else {
- return None;
- };
- Some(StyleValueData::Image {
+ } = url_payload.into_inner();
+ Some(StyleValueData::Image(StyleValueBox::new(ImagePayload {
url,
url_type,
url_modifiers: modifiers,
resource_context: image_resource_context(),
- })
+ })))
}
fn image_from_string(string: &[u16]) -> Option<StyleValueData> {
- Some(StyleValueData::Image {
+ Some(StyleValueData::Image(StyleValueBox::new(ImagePayload {
url: RetainedString::from_utf16(string)?,
url_type: 0,
url_modifiers: RetainedRequestUrlModifierList::from_retained_modifiers(Vec::new()),
resource_context: image_resource_context(),
- })
+ })))
}
fn parse_type(_context: &ParseContext, value: &ComponentValue) -> Option<CssString> {
@@ -138,8 +140,10 @@ fn parse_image_set(context: &ParseContext, property: u16, arguments: &[Component
type_string,
));
}
- (!options.is_empty()).then(|| StyleValueData::ImageSet {
- options: RetainedImageSetOptionList::from_retained_elements(options),
+ (!options.is_empty()).then(|| {
+ StyleValueData::ImageSet(StyleValueBox::new(ImageSetPayload {
+ options: RetainedImageSetOptionList::from_retained_elements(options),
+ }))
})
}
@@ -396,16 +400,18 @@ fn parse_linear_gradient(
tokens.discard_a_token();
}
let (color_stop_list, color_syntax) = parse_color_stop_list(context, property, &mut tokens, false)?;
- Some(StyleValueData::LinearGradient {
- has_direction_value: direction_value.is_some(),
- direction_value: optional_retained(direction_value),
- side_or_corner,
- color_stop_list,
- gradient_type: u8::from(webkit.is_some()),
- repeating: repeating.is_some(),
- color_interpolation_method: optional_retained(interpolation_method),
- color_syntax,
- })
+ Some(StyleValueData::LinearGradient(StyleValueBox::new(
+ LinearGradientPayload {
+ has_direction_value: direction_value.is_some(),
+ direction_value: optional_retained(direction_value),
+ side_or_corner,
+ color_stop_list,
+ gradient_type: u8::from(webkit.is_some()),
+ repeating: repeating.is_some(),
+ color_interpolation_method: optional_retained(interpolation_method),
+ color_syntax,
+ },
+ )))
}
// https://drafts.csswg.org/css-images-4/#conic-gradients
@@ -472,18 +478,20 @@ fn parse_conic_gradient(
tokens.discard_a_token();
}
let (color_stop_list, color_syntax) = parse_color_stop_list(context, property, &mut tokens, true)?;
- Some(StyleValueData::ConicGradient {
- from_angle: optional_retained(from_angle),
- position: retained(position.unwrap_or_else(center_position)),
- color_stop_list,
- repeating,
- color_interpolation_method: optional_retained(interpolation_method),
- color_syntax,
- })
+ Some(StyleValueData::ConicGradient(StyleValueBox::new(
+ ConicGradientPayload {
+ from_angle: optional_retained(from_angle),
+ position: retained(position.unwrap_or_else(center_position)),
+ color_stop_list,
+ repeating,
+ color_interpolation_method: optional_retained(interpolation_method),
+ color_syntax,
+ },
+ )))
}
fn default_radial_size() -> StyleValueData {
- StyleValueData::RadialSize {
+ StyleValueData::RadialSize(StyleValueBox::new(RadialSizePayload {
component_count: 1,
is_extent_0: true,
extent_0: 2,
@@ -491,7 +499,7 @@ fn default_radial_size() -> StyleValueData {
is_extent_1: false,
extent_1: 0,
value_1: RetainedStyleValueData::none(),
- }
+ }))
}
fn parse_ending_shape(tokens: &mut TokenStream<'_>) -> Option<u8> {
@@ -514,14 +522,14 @@ fn parse_ending_shape(tokens: &mut TokenStream<'_>) -> Option<u8> {
}
fn radial_size_shape(size: &StyleValueData) -> Option<(u8, bool)> {
- let StyleValueData::RadialSize {
+ let StyleValueData::RadialSize(radial_size_payload) = size else {
+ return None;
+ };
+ let RadialSizePayload {
component_count,
is_extent_0,
..
- } = size
- else {
- return None;
- };
+ } = &**radial_size_payload;
Some((*component_count, *is_extent_0))
}
@@ -596,15 +604,17 @@ fn parse_radial_gradient(
tokens.discard_a_token();
}
let (color_stop_list, color_syntax) = parse_color_stop_list(context, property, &mut tokens, false)?;
- Some(StyleValueData::RadialGradient {
- ending_shape,
- size: retained(size),
- position: retained(position.unwrap_or_else(center_position)),
- color_stop_list,
- repeating,
- color_interpolation_method: optional_retained(interpolation_method),
- color_syntax,
- })
+ Some(StyleValueData::RadialGradient(StyleValueBox::new(
+ RadialGradientPayload {
+ ending_shape,
+ size: retained(size),
+ position: retained(position.unwrap_or_else(center_position)),
+ color_stop_list,
+ repeating,
+ color_interpolation_method: optional_retained(interpolation_method),
+ color_syntax,
+ },
+ )))
}
fn parse_gradient(
@@ -675,7 +685,7 @@ fn parse_light_dark_image(
if tokens.has_next_token() {
return None;
}
- Some(StyleValueData::LightDark {
+ Some(StyleValueData::LightDark(StyleValueBox::new(LightDarkPayload {
color_base: crate::css::style_value::ColorBase {
has_color_type: false,
color_type: 0,
@@ -683,7 +693,7 @@ fn parse_light_dark_image(
},
light: retained(light),
dark: retained(dark),
- })
+ })))
}
pub(crate) fn is_image_function_name(name: &[u16]) -> bool {
@@ -719,7 +729,7 @@ fn parse_image_or_none(context: &ParseContext, property: u16, values: &[Componen
&& let Some(url) = parse_url_value(context, tokens.next_token())
{
tokens.discard_a_token();
- if matches!(&url, StyleValueData::Url { url, .. } if url.is_fragment()) {
+ if matches!(&url, StyleValueData::Url(url) if url.url.is_fragment()) {
// NB: Preserve the SVG resource path for local mask references.
url
} else {
@@ -752,7 +762,7 @@ pub(crate) fn parse_image_property(context: &ParseContext, property: u16, values
parse_image_or_none(context, property, values)
};
parsed.map_or(ParseOutcome::NotHandled, |parsed| {
- ParseOutcome::Parsed(Arc::new(parsed))
+ ParseOutcome::Parsed(StyleValueArc::new(parsed))
})
}
diff --git a/Libraries/LibWeb/Rust/src/css/parser/memory_tests.rs b/Libraries/LibWeb/Rust/src/css/parser/memory_tests.rs
new file mode 100644
index 00000000000..b343d057a12
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/parser/memory_tests.rs
@@ -0,0 +1,342 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The heap a parsed style sheet holds, per unit of CSS: per rule, selector, declaration by kind,
+//! at-rule, keyframe and sheet. Each figure is the slope between two sheets that differ only in how
+//! many of the unit they hold, so the fixed costs cancel; the bytes are what the allocator was
+//! asked for and still holds once the parse returns, counted exactly by the test allocator.
+//!
+//! Each ceiling is what the unit may hold, which a change growing it has to raise, beside the
+//! typical figure the unit is measured against.
+
+use crate::css::css_tokenizer::TokenizerInput;
+use crate::css::parser::syntax_parser::parse_stylesheet_uncached;
+use crate::css::parser::value_parser::ParseContext;
+use crate::css::rule::NativeRuleList;
+use crate::css::style::pipeline::allocation_count::count_live_bytes;
+use std::sync::Arc;
+
+/// The bytes a parse of `text` leaves allocated, but for the text it keeps, and those the rules the
+/// CSSOM materializes from it add. What the process interns or pools for every sheet, as names and common values, is the
+/// process's: a parse of the same text before the one counted has it in place, so that what this
+/// thread happens to grow or clear of those tables, beside the other test threads, is not counted.
+fn parsed_bytes(text: &str) -> (i64, i64) {
+ let units: Vec<u16> = text.encode_utf16().collect();
+ let context = ParseContext::default();
+ let parse = || Arc::new(parse_stylesheet_uncached(TokenizerInput::Utf16(&units), Some(&context)));
+ let interned = parse();
+ let (parsed, parse_bytes) = count_live_bytes(parse);
+ let (list, native_bytes) = count_live_bytes(|| {
+ let list = NativeRuleList::from_parsed(parsed.clone());
+ for index in 0..list.len() {
+ list.rule_at(index);
+ }
+ list
+ });
+ drop((list, parsed, interned));
+ // NB: The sheet keeps its text, one byte per ASCII character, for DevTools, in place of the copy
+ // each document kept. The text is left out of every unit but the sheet's.
+ assert!(text.is_ascii());
+ (parse_bytes - text.len() as i64, native_bytes)
+}
+
+fn sheet(count: usize, unit: &dyn Fn(usize) -> String) -> String {
+ (0..count).map(|index| unit(index) + "\n").collect()
+}
+
+/// The bytes each of the units `unit` makes adds to a parse, and to the rules the CSSOM materializes
+/// from it.
+fn slope(unit: &dyn Fn(usize) -> String) -> (f64, f64) {
+ const COUNT: usize = 500;
+ let small = parsed_bytes(&sheet(COUNT, unit));
+ let large = parsed_bytes(&sheet(2 * COUNT, unit));
+ (
+ (large.0 - small.0) as f64 / COUNT as f64,
+ (large.1 - small.1) as f64 / COUNT as f64,
+ )
+}
+
+/// The bytes each declaration `declaration(rule, k)` adds to a rule, of `per_rule` and twice as
+/// many in each of the rules.
+fn declaration_slope(per_rule: usize, declaration: &dyn Fn(usize, usize) -> String) -> f64 {
+ const COUNT: usize = 500;
+ let rules = |declarations: usize| {
+ sheet(COUNT, &|index| {
+ // NB: A declaration of the rule's own keeps sheets from sharing one block between rules. Each
+ // declaration's value is its own as well, which the parse would otherwise share.
+ let mut rule = format!(".c{index} {{ order: {index} ");
+ for k in 0..declarations {
+ rule += &format!("; {}", declaration(index, k));
+ }
+ rule + " }"
+ })
+ };
+ let small = parsed_bytes(&rules(per_rule)).0;
+ let large = parsed_bytes(&rules(2 * per_rule)).0;
+ (large - small) as f64 / (COUNT * per_rule) as f64
+}
+
+struct Unit {
+ name: &'static str,
+ bytes: f64,
+ ceiling: f64,
+ typical: &'static str,
+}
+
+fn check(units: &[Unit]) {
+ let mut over = Vec::new();
+ for unit in units {
+ eprintln!(
+ "{:<44} {:>8.1} B (ceiling {:>6}; {})",
+ unit.name, unit.bytes, unit.ceiling, unit.typical
+ );
+ if unit.bytes > unit.ceiling {
+ over.push(unit.name);
+ }
+ }
+ assert!(over.is_empty(), "over their ceilings: {over:?}");
+}
+
+const KEYWORDS: [&str; 8] = [
+ "display: block",
+ "position: relative",
+ "float: left",
+ "clear: both",
+ "visibility: hidden",
+ "text-align: center",
+ "box-sizing: border-box",
+ "text-transform: uppercase",
+];
+
+const LENGTH_PROPERTIES: [&str; 8] = [
+ "margin-left",
+ "margin-right",
+ "margin-top",
+ "margin-bottom",
+ "padding-left",
+ "padding-right",
+ "padding-top",
+ "padding-bottom",
+];
+
+const COLOR_PROPERTIES: [&str; 8] = [
+ "color",
+ "background-color",
+ "border-left-color",
+ "border-right-color",
+ "border-top-color",
+ "border-bottom-color",
+ "outline-color",
+ "caret-color",
+];
+
+const URL_PROPERTIES: [&str; 4] = [
+ "background-image",
+ "list-style-image",
+ "border-image-source",
+ "mask-image",
+];
+
+const SHORTHANDS: [&str; 4] = ["margin", "padding", "inset", "scroll-margin"];
+
+#[test]
+fn parsed_sheet_bytes_per_unit() {
+ let rule = slope(&|index| format!(".c{index} {{ color: red }}"));
+ // NB: Pooled values in pairs no other rule repeats, so that each rule parses a block of its own.
+ let own_block = slope(&|index| format!(".c{index} {{ z-index: {}; order: {} }}", index % 100, index / 100));
+ let style_rule =
+ |selector: &dyn Fn(usize) -> String| slope(&|index| format!("{} {{ color: red }}", selector(index)));
+ let compound = style_rule(&|index| format!("div.c{index}.d{index}[x]"));
+ let complex = style_rule(&|index| format!(".a{index} .b{index} > .c{index}"));
+ let list = style_rule(&|index| format!(".a{index}, .b{index}"));
+ let argument_list = style_rule(&|index| format!(":is(.x{index}, .y{index}) .z{index}"));
+ let wrapped = |wrap: &dyn Fn(usize) -> String| {
+ slope(&|index| format!("{} {{ .c{index} {{ color: red }} }}", wrap(index))).0 - rule.0
+ };
+ let keyframes = |count: usize| {
+ slope(&|index| {
+ let mut rule = format!("@keyframes k{index} {{");
+ for k in 0..count {
+ rule += &format!(" {}% {{ opacity: 0.{index} }}", k * 100 / count);
+ }
+ rule + " }"
+ })
+ .0
+ };
+ let (two_keyframes, four_keyframes) = (keyframes(2), keyframes(4));
+ let sheets = {
+ const COUNT: usize = 200;
+ let bytes: i64 = (0..COUNT)
+ .map(|index| parsed_bytes(&format!(".s{index} {{ color: red }}")).0)
+ .sum();
+ bytes as f64 / COUNT as f64 - rule.0
+ };
+
+ check(&[
+ Unit {
+ name: "sheet, fixed",
+ bytes: sheets,
+ // NB: The arena holds the sheet's `@namespace` declarations and the rank of its compounds.
+ ceiling: 920.0,
+ typical: "about 600-1000 B",
+ },
+ Unit {
+ name: "style rule `.c` with a shared block",
+ bytes: rule.0,
+ ceiling: 144.0,
+ typical: "24 B + 16 B selector + 16 B facts of its compound",
+ },
+ Unit {
+ name: "declaration block of a rule's own, fixed",
+ bytes: own_block.0 - rule.0 - 2.0 * 10.0,
+ ceiling: 24.0,
+ typical: "8 B + 16 B per declaration",
+ },
+ Unit {
+ name: "style rule, materialized for the CSSOM",
+ bytes: rule.1,
+ ceiling: 160.0,
+ typical: "the CSSOM wrapper only",
+ },
+ Unit {
+ name: "simple selector, in a compound",
+ bytes: (compound.0 - rule.0) / 3.0,
+ ceiling: 24.0,
+ typical: "16 B",
+ },
+ Unit {
+ name: "compound selector, after a combinator",
+ bytes: (complex.0 - rule.0) / 2.0,
+ ceiling: 32.0,
+ typical: "16 B + 16 B compound facts",
+ },
+ Unit {
+ name: "complex selector, in a list",
+ bytes: list.0 - rule.0,
+ ceiling: 32.0,
+ typical: "16 B + 16 B compound facts",
+ },
+ Unit {
+ name: ":is() of two classes, left of a class",
+ bytes: argument_list.0 - rule.0,
+ ceiling: 88.0,
+ typical: "an argument list of two complex selectors and the compound it is in, with their compound facts",
+ },
+ Unit {
+ name: "declaration, keyword",
+ bytes: declaration_slope(4, &|_, k| KEYWORDS[k].to_owned()),
+ ceiling: 10.0,
+ typical: "10 B",
+ },
+ Unit {
+ name: "declaration, length",
+ bytes: declaration_slope(4, &|index, k| format!("{}: {index}.{k}75px", LENGTH_PROPERTIES[k])),
+ ceiling: 34.0,
+ typical: "26 B",
+ },
+ Unit {
+ name: "declaration, rgb() color",
+ bytes: declaration_slope(4, &|index, k| {
+ format!(
+ "{}: rgb({}, {}, {k})",
+ COLOR_PROPERTIES[k],
+ index % 256,
+ index / 256 % 256
+ )
+ }),
+ ceiling: 98.0,
+ typical: "10 B, cached",
+ },
+ Unit {
+ name: "declaration, rgb() color another property repeats",
+ bytes: declaration_slope(4, &|index, k| {
+ format!(
+ "{}: rgb({}, {}, 0)",
+ COLOR_PROPERTIES[k],
+ index % 256,
+ index / 256 % 256
+ )
+ }),
+ ceiling: 10.0,
+ typical: "10 B, cached",
+ },
+ Unit {
+ name: "declaration, url()",
+ bytes: declaration_slope(2, &|index, k| format!("{}: url(a{index}-{k}.png)", URL_PROPERTIES[k])),
+ ceiling: 128.0,
+ typical: "16 + 40 B + text",
+ },
+ Unit {
+ name: "declaration, var()",
+ bytes: declaration_slope(4, &|index, k| format!("{}: var(--v{index}-{k})", LENGTH_PROPERTIES[k])),
+ ceiling: 98.0,
+ typical: "about 30 B + text",
+ },
+ Unit {
+ name: "declaration, shorthand of 4 longhands",
+ bytes: declaration_slope(2, &|index, k| format!("{}: {index}.5px {k}px", SHORTHANDS[k])),
+ ceiling: 88.0,
+ typical: "40 B",
+ },
+ Unit {
+ name: "declaration, custom property",
+ bytes: declaration_slope(4, &|index, k| format!("--p{k}: {index}.{k}px solid")),
+ ceiling: 80.0,
+ typical: "about 36 B + text",
+ },
+ Unit {
+ name: "@media around a rule",
+ bytes: wrapped(&|index| format!("@media (min-width: {index}px)")),
+ ceiling: 274.0,
+ typical: "about 112 B + expressions",
+ },
+ Unit {
+ name: "@supports around a rule",
+ bytes: wrapped(&|index| format!("@supports (z-index: {index})")),
+ ceiling: 300.0,
+ typical: "about 40 B + condition",
+ },
+ Unit {
+ name: "@container around a rule",
+ bytes: wrapped(&|index| format!("@container (min-width: {index}px)")),
+ ceiling: 286.0,
+ typical: "about 120 B",
+ },
+ Unit {
+ name: "@layer block around a rule",
+ bytes: wrapped(&|index| format!("@layer l{index}")),
+ ceiling: 172.0,
+ typical: "about 40 B",
+ },
+ Unit {
+ name: "@keyframes with 2 keyframes",
+ bytes: two_keyframes,
+ ceiling: 500.0,
+ typical: "about 40 + 2 x (32 + block) B",
+ },
+ Unit {
+ name: "keyframe",
+ bytes: (four_keyframes - two_keyframes) / 2.0,
+ ceiling: 168.0,
+ typical: "about 32 B + block",
+ },
+ Unit {
+ name: "@font-face",
+ bytes: slope(&|index| format!("@font-face {{ font-family: f{index}; src: url(f{index}.woff) }}")).0,
+ ceiling: 505.0,
+ typical: "about 16 B + block",
+ },
+ Unit {
+ name: "@property",
+ bytes: slope(&|index| {
+ format!("@property --p{index} {{ syntax: \"<length>\"; inherits: false; initial-value: {index}px }}")
+ })
+ .0,
+ ceiling: 659.0,
+ typical: "about 24 B + block",
+ },
+ ]);
+}
diff --git a/Libraries/LibWeb/Rust/src/css/parser/mod.rs b/Libraries/LibWeb/Rust/src/css/parser/mod.rs
index 40c2ad52897..938a2290f4e 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/mod.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/mod.rs
@@ -12,6 +12,8 @@ pub(crate) mod descriptor_parser;
pub(crate) mod fonts_parser;
pub(crate) mod grid_parser;
pub(crate) mod images_gradients_parser;
+#[cfg(test)]
+mod memory_tests;
pub(crate) mod positions_shapes_parser;
pub(crate) mod query_parser;
mod stylesheet_cache;
diff --git a/Libraries/LibWeb/Rust/src/css/parser/positions_shapes_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/positions_shapes_parser.rs
index 7f5e32824b1..2296bb9e903 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/positions_shapes_parser.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/positions_shapes_parser.rs
@@ -5,7 +5,6 @@
*/
// Parsed values use the thread-confined shared graph owned by the C++ style objects.
-#![allow(clippy::arc_with_non_send_sync)]
use super::component_value::{ComponentKind, ComponentValue, trim_whitespace};
use super::token_stream::TokenStream;
@@ -20,12 +19,16 @@ use crate::css::property_metadata::{
longhands_for_shorthand, property_accepted_value_types, property_has_coordinating_list_multiplicity, property_id,
};
use crate::css::style_compute::px_length_unit;
+use crate::css::style_value::{
+ AnchorPayload, AnchorSizePayload, BorderRadiusPayload, BorderRadiusRectPayload, FunctionPayload, PositionPayload,
+ RadialSizePayload, RayPayload, RectPayload, ShorthandPayload, StyleValueBox,
+};
use crate::css::style_value::{
BasicShapeData, CssString, OwnedBasicShapeData, RetainedPropertyIdList, RetainedShapePoint, RetainedShapePointList,
RetainedStyleValueData, RetainedStyleValueDataList, StyleValueData,
};
+use crate::css::style_value_arc::StyleValueArc;
use crate::css::value_codes::*;
-use std::sync::Arc;
// NB: These are the generated C++ PositionEdge enum values.
const EDGE_CENTER: u8 = 0;
@@ -47,10 +50,10 @@ fn edge(edge: Option<u8>, offset: Option<StyleValueData>) -> StyleValueData {
}
fn position(edge_x: StyleValueData, edge_y: StyleValueData) -> StyleValueData {
- StyleValueData::Position {
+ StyleValueData::Position(StyleValueBox::new(PositionPayload {
edge_x: retained(edge_x),
edge_y: retained(edge_y),
- }
+ }))
}
pub(crate) fn center_position() -> StyleValueData {
@@ -290,13 +293,14 @@ fn parse_background_position(
let mut x_values = Vec::with_capacity(positions.len());
let mut y_values = Vec::with_capacity(positions.len());
for position in positions {
- let StyleValueData::Position { edge_x, edge_y } = position else {
+ let StyleValueData::Position(position_payload) = position else {
unreachable!();
};
+ let PositionPayload { edge_x, edge_y } = &*position_payload;
x_values.push(edge_x.data().clone());
y_values.push(edge_y.data().clone());
}
- Some(StyleValueData::Shorthand {
+ Some(StyleValueData::Shorthand(StyleValueBox::new(ShorthandPayload {
shorthand_property: property_id::BACKGROUND_POSITION,
sub_properties: RetainedPropertyIdList::from_property_ids(vec![
property_id::BACKGROUND_POSITION_X,
@@ -306,7 +310,7 @@ fn parse_background_position(
retained(value_list(x_values)),
retained(value_list(y_values)),
]),
- })
+ })))
}
fn parse_background_position_axis(
@@ -377,11 +381,11 @@ fn keyword_value(value: &ComponentValue, accepted: &[u16]) -> Option<StyleValueD
fn border_radius(horizontal: StyleValueData, vertical: StyleValueData) -> StyleValueData {
let is_elliptical = horizontal != vertical;
- StyleValueData::BorderRadius {
+ StyleValueData::BorderRadius(StyleValueBox::new(BorderRadiusPayload {
is_elliptical,
horizontal_radius: retained(horizontal),
vertical_radius: retained(vertical),
- }
+ }))
}
fn expanded_four(values: &[StyleValueData]) -> Option<[StyleValueData; 4]> {
@@ -439,12 +443,14 @@ fn parse_border_radius_rect(
};
let corners: [StyleValueData; 4] =
std::array::from_fn(|index| border_radius(horizontal[index].clone(), vertical[index].clone()));
- Some(StyleValueData::BorderRadiusRect {
- top_left: retained(corners[0].clone()),
- top_right: retained(corners[1].clone()),
- bottom_right: retained(corners[2].clone()),
- bottom_left: retained(corners[3].clone()),
- })
+ Some(StyleValueData::BorderRadiusRect(StyleValueBox::new(
+ BorderRadiusRectPayload {
+ top_left: retained(corners[0].clone()),
+ top_right: retained(corners[1].clone()),
+ bottom_right: retained(corners[2].clone()),
+ bottom_left: retained(corners[3].clone()),
+ },
+ )))
}
fn zero_border_radius_rect() -> StyleValueData {
@@ -453,12 +459,12 @@ fn zero_border_radius_rect() -> StyleValueData {
unit: px_length_unit(),
};
let corner = border_radius(zero.clone(), zero);
- StyleValueData::BorderRadiusRect {
+ StyleValueData::BorderRadiusRect(StyleValueBox::new(BorderRadiusRectPayload {
top_left: retained(corner.clone()),
top_right: retained(corner.clone()),
bottom_right: retained(corner.clone()),
bottom_left: retained(corner),
- }
+ }))
}
fn parse_single_border_radius(
@@ -497,16 +503,16 @@ fn parse_border_radius_shorthand(
) -> Option<StyleValueData> {
let mut tokens = TokenStream::new(values);
let rect = parse_border_radius_rect(context, property, &mut tokens)?;
- let StyleValueData::BorderRadiusRect {
+ let StyleValueData::BorderRadiusRect(border_radius_rect_payload) = rect else {
+ unreachable!();
+ };
+ let BorderRadiusRectPayload {
top_left,
top_right,
bottom_right,
bottom_left,
- } = rect
- else {
- unreachable!();
- };
- Some(StyleValueData::Shorthand {
+ } = border_radius_rect_payload.into_inner();
+ Some(StyleValueData::Shorthand(StyleValueBox::new(ShorthandPayload {
shorthand_property: property_id::BORDER_RADIUS,
sub_properties: RetainedPropertyIdList::from_property_ids(vec![
property_id::BORDER_TOP_LEFT_RADIUS,
@@ -515,7 +521,7 @@ fn parse_border_radius_shorthand(
property_id::BORDER_BOTTOM_LEFT_RADIUS,
]),
values: RetainedStyleValueDataList::from_retained_values(vec![top_left, top_right, bottom_right, bottom_left]),
- })
+ })))
}
fn parse_legacy_rect(context: &ParseContext, property: u16, values: &[ComponentValue]) -> Option<StyleValueData> {
@@ -554,12 +560,12 @@ fn parse_legacy_rect(context: &ParseContext, property: u16, values: &[ComponentV
if tokens.has_next_token() {
return None;
}
- Some(StyleValueData::Rect {
+ Some(StyleValueData::Rect(StyleValueBox::new(RectPayload {
top: retained(sides[0].clone()),
right: retained(sides[1].clone()),
bottom: retained(sides[2].clone()),
left: retained(sides[3].clone()),
- })
+ })))
}
fn parse_corner_shape(context: &ParseContext, property: u16, value: &ComponentValue) -> Option<StyleValueData> {
@@ -618,11 +624,11 @@ fn positional_shorthand(property: u16, values: Vec<StyleValueData>) -> Option<St
4 => expanded_four(&values)?.into_iter().collect(),
_ => return None,
};
- Some(StyleValueData::Shorthand {
+ Some(StyleValueData::Shorthand(StyleValueBox::new(ShorthandPayload {
shorthand_property: property,
sub_properties: RetainedPropertyIdList::from_property_ids(longhands.to_vec()),
values: RetainedStyleValueDataList::from_retained_values(expanded.into_iter().map(retained).collect()),
- })
+ })))
}
fn parse_corner_shape_property(
@@ -685,7 +691,7 @@ fn radial_size(components: Vec<RadialComponent>) -> Option<StyleValueData> {
RadialComponent::Value(parsed) => value[index] = retained(parsed),
}
}
- Some(StyleValueData::RadialSize {
+ Some(StyleValueData::RadialSize(StyleValueBox::new(RadialSizePayload {
component_count: u8::from(is_extent[1] || value[1].optional_data().is_some()) + 1,
is_extent_0: is_extent[0],
extent_0: extent[0],
@@ -693,7 +699,7 @@ fn radial_size(components: Vec<RadialComponent>) -> Option<StyleValueData> {
is_extent_1: is_extent[1],
extent_1: extent[1],
value_1: std::mem::replace(&mut value[1], RetainedStyleValueData::none()),
- })
+ })))
}
pub(crate) fn parse_radial_size(
@@ -896,7 +902,7 @@ fn parse_circle_or_ellipse(
let mut tokens = TokenStream::new(arguments);
let mut radius = parse_radial_size(context, property, &mut tokens);
if radius.as_ref().is_some_and(|radius| {
- matches!(radius, StyleValueData::RadialSize { component_count, .. } if *component_count != if ellipse { 2 } else { 1 })
+ matches!(radius, StyleValueData::RadialSize(radial_size) if radial_size.component_count != if ellipse { 2 } else { 1 })
}) {
return None;
}
@@ -1072,9 +1078,10 @@ fn parse_shape_position(
property: u16,
values: &[ComponentValue],
) -> Option<RetainedShapePoint> {
- let StyleValueData::Position { edge_x, edge_y } = parse_position_value(context, property, values, false)? else {
+ let StyleValueData::Position(position_payload) = parse_position_value(context, property, values, false)? else {
return None;
};
+ let PositionPayload { edge_x, edge_y } = position_payload.into_inner();
Some(RetainedShapePoint::from_retained_values(edge_x, edge_y))
}
@@ -1557,12 +1564,12 @@ fn parse_ray(context: &ParseContext, property: u16, arguments: &[ComponentValue]
NumericRange::INFINITE,
)?);
}
- Some(StyleValueData::Ray {
+ Some(StyleValueData::Ray(StyleValueBox::new(RayPayload {
size: size.unwrap_or(keyword::CLOSEST_SIDE),
contain,
angle: retained(angle?),
position: position.map_or_else(RetainedStyleValueData::none, retained),
- })
+ })))
}
/// Whether this component value starts an <'offset-path'> value.
@@ -1953,12 +1960,12 @@ pub(crate) fn parse_anchor_function(
} else {
None
};
- Some(StyleValueData::Anchor {
+ Some(StyleValueData::Anchor(StyleValueBox::new(AnchorPayload {
has_anchor_name: anchor_name.is_some(),
anchor_name: anchor_name.unwrap_or_else(CssString::none),
anchor_side: retained(side?),
fallback_value: fallback.map_or_else(RetainedStyleValueData::none, retained),
- })
+ })))
}
fn anchor_size_keyword(value: &ComponentValue) -> Option<u8> {
@@ -2081,13 +2088,13 @@ pub(crate) fn parse_anchor_size_function(
if fallback.is_some() && !comma_present && has_name_or_size {
return None;
}
- Some(StyleValueData::AnchorSize {
+ Some(StyleValueData::AnchorSize(StyleValueBox::new(AnchorSizePayload {
has_anchor_name: anchor_name.is_some(),
anchor_name: anchor_name.unwrap_or_else(CssString::none),
has_anchor_size: anchor_size.is_some(),
anchor_size: anchor_size.unwrap_or(0),
fallback_value: fallback.map_or_else(RetainedStyleValueData::none, retained),
- })
+ })))
}
fn contains_anchor_in_math_function(values: &[ComponentValue], inside_math_function: bool) -> bool {
@@ -2133,10 +2140,10 @@ fn parse_fit_content(context: &ParseContext, property: u16, values: &[ComponentV
if tokens.has_next_token() {
return None;
}
- Some(StyleValueData::Function {
+ Some(StyleValueData::Function(StyleValueBox::new(FunctionPayload {
name: CssString::from_utf16(&"fit-content".encode_utf16().collect::<Vec<_>>()),
value: retained(argument),
- })
+ })))
}
fn parse_inset_leaf(context: &ParseContext, property: u16, tokens: &mut TokenStream<'_>) -> Option<StyleValueData> {
@@ -2256,7 +2263,9 @@ pub(crate) fn parse_anchor_fit_property(
} else {
return ParseOutcome::NotHandled;
};
- parsed.map_or(ParseOutcome::Invalid, |parsed| ParseOutcome::Parsed(Arc::new(parsed)))
+ parsed.map_or(ParseOutcome::Invalid, |parsed| {
+ ParseOutcome::Parsed(StyleValueArc::new(parsed))
+ })
}
pub(crate) fn parse_geometry_property(
@@ -2349,7 +2358,9 @@ pub(crate) fn parse_geometry_property(
} else {
return ParseOutcome::NotHandled;
};
- parsed.map_or(ParseOutcome::Invalid, |parsed| ParseOutcome::Parsed(Arc::new(parsed)))
+ parsed.map_or(ParseOutcome::Invalid, |parsed| {
+ ParseOutcome::Parsed(StyleValueArc::new(parsed))
+ })
}
pub(crate) fn parse_position_property(
@@ -2380,7 +2391,9 @@ pub(crate) fn parse_position_property(
}
})
};
- parsed.map_or(ParseOutcome::Invalid, |parsed| ParseOutcome::Parsed(Arc::new(parsed)))
+ parsed.map_or(ParseOutcome::Invalid, |parsed| {
+ ParseOutcome::Parsed(StyleValueArc::new(parsed))
+ })
}
#[cfg(test)]
@@ -2434,12 +2447,12 @@ mod tests {
else {
panic!("background-position should parse");
};
- let StyleValueData::Shorthand {
- sub_properties, values, ..
- } = &*value
- else {
+ let StyleValueData::Shorthand(shorthand_payload) = &*value else {
panic!("background-position should expand to its axes");
};
+ let ShorthandPayload {
+ sub_properties, values, ..
+ } = &**shorthand_payload;
assert_eq!(
sub_properties.as_slice(),
[property_id::BACKGROUND_POSITION_X, property_id::BACKGROUND_POSITION_Y]
@@ -2480,7 +2493,7 @@ mod tests {
let ParseOutcome::Parsed(value) = parse_geometry(property_id::BORDER_RADIUS, "1px 2px 3px / 4px 5px") else {
panic!("border-radius should parse");
};
- assert!(matches!(&*value, StyleValueData::Shorthand { values, .. } if values.as_slice().len() == 4));
+ assert!(matches!(&*value, StyleValueData::Shorthand(shorthand) if shorthand.values.as_slice().len() == 4));
assert!(matches!(
parse_geometry(property_id::BORDER_RADIUS, "-1px"),
ParseOutcome::Invalid
diff --git a/Libraries/LibWeb/Rust/src/css/parser/query_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/query_parser.rs
index 2538630b01f..98ce2f3b8f5 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/query_parser.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/query_parser.rs
@@ -6,6 +6,7 @@
use crate::css::css_enums::keyword_from_ascii_case_insensitive;
use crate::css::css_pixels::CssPixels;
+use crate::css::css_string::CssString;
use crate::css::css_tokenizer::{ParserString, ParserTokenKind, TextDetacher, TokenizerInput, tokenize_for_parser};
use crate::css::custom_properties::environment_variable_is_known;
use crate::css::ffi_support::{FfiUtf16View, OwnedArc};
@@ -25,6 +26,7 @@ use crate::css::selector_operations::contains_unsupported_selector;
use crate::css::selector_parser::{SelectorParsingMode, SelectorType, parse_selector_list};
use crate::css::serialize::{StringUnits, TextSink, serialize_an_identifier, serialize_component_values_to_utf16};
use crate::css::style_compute::{FfiLengthResolutionContext, LENGTH_UNIT_NAMES, px_length_unit};
+use crate::css::style_value::RatioPayload;
use crate::css::style_value::StyleValueData;
use std::ffi::c_void;
use std::marker::PhantomData;
@@ -38,8 +40,6 @@ struct QueryFeatureMetadata {
allows_range: bool,
}
-// NB: Mirrors the SizeFeatureID order and range support that Libraries/LibWeb/CSS/ContainerQuery.h
-// and .cpp carried before this series removed them.
const SIZE_FEATURES: &[QueryFeatureMetadata] = &[
QueryFeatureMetadata {
name: "aspect-ratio",
@@ -92,8 +92,7 @@ const SCROLL_STATE_FEATURE_SCROLLED: u8 = 1;
const SCROLL_STATE_FEATURE_SNAPPED: u8 = 2;
const SCROLL_STATE_FEATURE_STUCK: u8 = 3;
-// NB: Media feature IDs follow MediaFeatures.json iteration order, as did the C++ resolver that
-// this series removed from Libraries/LibWeb/CSS/Parser/RustQueryParsing.cpp.
+// NB: Media feature IDs follow MediaFeatures.json iteration order.
/// Looks up a query feature by name over a table of `(name, allows_range)` entries. The media and
/// size tables come from different generators, so they are matched through this shared accessor.
fn feature_from_name<'a>(table: impl IntoIterator<Item = (&'a str, bool)>, name: &[u16]) -> Option<(u8, bool)> {
@@ -241,8 +240,7 @@ impl<'a> FfiMediaEnvironment<'a> {
}
#[derive(Clone, Copy)]
-#[repr(C)]
-pub struct FfiContainerFacts {
+pub struct ContainerFacts {
pub container_available: bool,
pub size_available: bool,
pub width: f64,
@@ -291,31 +289,48 @@ pub(crate) enum FeatureNameType {
Max,
}
+/// A query feature's value, kept as its source text rather than the tokens it was parsed from,
+/// which hold several times as much. The components the text holds are tokenized again
+/// whenever they are read, which only parsing it into a value the first time a query evaluates it
+/// and serializing it do.
#[derive(Clone, Debug)]
pub(crate) struct QueryFeatureValue {
- pub components: Vec<ComponentValue>,
+ text: CssString,
+ /// The keyword a value that is a lone identifier names, which evaluation reads as it is.
+ keyword: Option<u16>,
/// What the value parses to, made the first time a query evaluates the value.
parsed: std::sync::OnceLock<Box<ParsedFeatureValues>>,
}
impl PartialEq for QueryFeatureValue {
fn eq(&self, other: &Self) -> bool {
- self.components == other.components
+ self.text == other.text
}
}
impl QueryFeatureValue {
pub(crate) fn new(components: Vec<ComponentValue>) -> Self {
+ let components = trim_whitespace(&components);
+ let keyword = match components {
+ [component] => component.ident().and_then(keyword_from_ascii_case_insensitive),
+ _ => None,
+ };
Self {
- components,
+ text: source_text(components),
+ keyword,
parsed: std::sync::OnceLock::new(),
}
}
+ /// The components of the value, without the whitespace around them.
+ pub(crate) fn components(&self) -> Vec<ComponentValue> {
+ components_from_source(TokenizerInput::Utf16(self.text.units())).unwrap_or_default()
+ }
+
/// What the value parses to as `kind`, which it is parsed to the first time it is asked for.
fn parsed_as(&self, kind: FeatureValueParse) -> Option<&StyleValueData> {
self.parsed.get_or_init(Box::default).0[kind as usize]
- .get_or_init(|| parse_feature_value_as(&self.components, kind))
+ .get_or_init(|| parse_feature_value_as(&self.components(), kind))
.as_ref()
}
}
@@ -354,21 +369,24 @@ pub(crate) enum QueryFeature {
name_type: FeatureNameType,
value: QueryFeatureValue,
},
+ /// Each side boxed, so that every other feature, and every expression, stays small.
Range {
id: u8,
- left: Option<(QueryFeatureValue, FeatureComparison)>,
- right: Option<(FeatureComparison, QueryFeatureValue)>,
+ left: Option<Box<(QueryFeatureValue, FeatureComparison)>>,
+ right: Option<Box<(FeatureComparison, QueryFeatureValue)>>,
},
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum SupportsFeature {
+ /// A declaration or selector is evaluated as it is parsed and kept as its source text, which
+ /// serializing the condition reads.
Declaration {
- components: Vec<ComponentValue>,
+ text: CssString,
matches: bool,
},
Selector {
- components: Vec<ComponentValue>,
+ text: CssString,
matches: bool,
},
FontTech {
@@ -418,25 +436,27 @@ pub(crate) enum Expression {
And(Vec<Expression>),
Or(Vec<Expression>),
InParens(Box<Expression>),
+ /// A `<general-enclosed>`, kept as its source text: it only serializes.
GeneralEnclosed {
- component: ComponentValue,
+ text: CssString,
result: MatchResult,
},
GeneralEnclosedValues {
- components: Vec<ComponentValue>,
+ text: CssString,
result: MatchResult,
},
QueryFeature(QueryFeature),
SupportsFeature(SupportsFeature),
StyleFunction(Box<Expression>),
- StyleFeature(StyleFeature),
+ /// Boxed, as the largest feature, so that the expressions of other features stay small.
+ StyleFeature(Box<StyleFeature>),
ScrollStateFunction(Box<Expression>),
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct MediaQuery {
pub negated: bool,
- pub media_type: Option<ParserString>,
+ pub media_type: Option<CssString>,
pub condition: Option<Expression>,
pub valid: bool,
}
@@ -467,6 +487,15 @@ fn original_source(values: &[ComponentValue]) -> ParserString {
)
}
+/// The source text `values` were tokenized from.
+fn source_text(values: &[ComponentValue]) -> CssString {
+ let text: Vec<u16> = values
+ .iter()
+ .flat_map(|component| component.original_source_text.iter())
+ .collect();
+ CssString::from_utf16(&text)
+}
+
fn components_from_source<'a>(source: impl Into<TokenizerInput<'a>>) -> Option<Vec<ComponentValue>> {
consume_a_list_of_component_values(tokenize_for_parser(source)).ok()
}
@@ -537,9 +566,9 @@ fn parse_general_enclosed(stream: &mut TokenStream<'_>, result: MatchResult) ->
if !contains_only_any_value(values) {
return None;
}
- let component = component.clone();
+ let text = source_text(std::slice::from_ref(component));
transaction.commit();
- Some(Expression::GeneralEnclosed { component, result })
+ Some(Expression::GeneralEnclosed { text, result })
}
fn parse_boolean_expression_group<F>(
@@ -560,8 +589,8 @@ where
parse_boolean_expression(&mut child_stream, result_for_general_enclosed, parse_test)
&& child_stream.is_empty()
{
- if let Expression::GeneralEnclosedValues { components, .. } = &mut expression {
- *components = values.to_vec();
+ if let Expression::GeneralEnclosedValues { text, .. } = &mut expression {
+ *text = source_text(values);
}
transaction.commit();
return Some(Expression::InParens(Box::new(expression)));
@@ -800,7 +829,7 @@ where
return Some(QueryFeature::Range {
id,
left: None,
- right: Some((comparison, value)),
+ right: Some(Box::new((comparison, value))),
});
}
}
@@ -831,7 +860,7 @@ where
transaction.commit();
return Some(QueryFeature::Range {
id,
- left: Some((left, left_comparison)),
+ left: Some(Box::new((left, left_comparison))),
right: None,
});
}
@@ -847,8 +876,8 @@ where
transaction.commit();
Some(QueryFeature::Range {
id,
- left: Some((left, left_comparison)),
- right: Some((right_comparison, right)),
+ left: Some(Box::new((left, left_comparison))),
+ right: Some(Box::new((right_comparison, right))),
})
}
@@ -900,15 +929,13 @@ where
pub(crate) fn invalid_media_query() -> MediaQuery {
MediaQuery {
negated: true,
- media_type: Some(ParserString::from(
- "all".encode_utf16().collect::<Vec<_>>().into_boxed_slice(),
- )),
+ media_type: Some(CssString::from_utf16(&"all".encode_utf16().collect::<Vec<_>>())),
condition: None,
valid: false,
}
}
-fn parse_media_type(stream: &mut TokenStream<'_>) -> Option<ParserString> {
+fn parse_media_type(stream: &mut TokenStream<'_>) -> Option<CssString> {
let mut transaction = stream.begin_transaction();
transaction.discard_whitespace();
let name = transaction.consume_a_token().ident()?;
@@ -918,7 +945,7 @@ fn parse_media_type(stream: &mut TokenStream<'_>) -> Option<ParserString> {
{
return None;
}
- let name = ParserString::from(name.to_vec().into_boxed_slice());
+ let name = CssString::from_utf16(name);
transaction.commit();
Some(name)
}
@@ -1069,7 +1096,7 @@ pub(crate) fn supports_feature_matches(
) else {
return false;
};
- selectors.len() == 1 && !contains_unsupported_selector(&selectors[0])
+ selectors.selectors.len() == 1 && !contains_unsupported_selector(&selectors.selectors[0])
}
SupportsFeatureKind::FontTech => font_tech_name_is_supported(value),
SupportsFeatureKind::FontFormat => font_format_is_supported(value),
@@ -1092,7 +1119,7 @@ where
transaction.commit();
return Some(Expression::InParens(Box::new(Expression::SupportsFeature(
SupportsFeature::Declaration {
- components: values.to_vec(),
+ text: source_text(values),
matches,
},
))));
@@ -1123,7 +1150,7 @@ where
let matches = evaluate_feature(kind, &name_or_source);
let feature = match kind {
SupportsFeatureKind::Selector => SupportsFeature::Selector {
- components: values.to_vec(),
+ text: source_text(values),
matches,
},
SupportsFeatureKind::FontTech => SupportsFeature::FontTech {
@@ -1187,7 +1214,7 @@ where
}
let matches = evaluate_feature(SupportsFeatureKind::Declaration, &supports_components_source(values));
Some(Expression::SupportsFeature(SupportsFeature::Declaration {
- components: values.to_vec(),
+ text: source_text(values),
matches,
}))
}
@@ -1251,21 +1278,21 @@ where
let middle = parse_style_range_value(&values[middle_start..second_index])?;
let right = parse_style_range_value(&values[second_index + second_consumed..])?;
stream.position = stream.values.len();
- return Some(Expression::StyleFeature(StyleFeature::Range {
+ return Some(Expression::StyleFeature(Box::new(StyleFeature::Range {
left,
left_comparison,
middle,
right: Some((right_comparison, right)),
- }));
+ })));
}
let middle = parse_style_range_value(&values[middle_start..])?;
stream.position = stream.values.len();
- return Some(Expression::StyleFeature(StyleFeature::Range {
+ return Some(Expression::StyleFeature(Box::new(StyleFeature::Range {
left,
left_comparison,
middle,
right: None,
- }));
+ })));
}
if let Some(colon) = values.iter().position(ComponentValue::is_colon) {
@@ -1273,7 +1300,7 @@ where
if resolve_feature(QueryKind::Style, name.as_ref()).is_none() {
stream.position = stream.values.len();
return Some(Expression::GeneralEnclosedValues {
- components: original_values.to_vec(),
+ text: source_text(original_values),
result: MatchResult::Unknown,
});
}
@@ -1286,31 +1313,31 @@ where
return None;
}
stream.position = stream.values.len();
- return Some(Expression::StyleFeature(StyleFeature::Plain {
+ return Some(Expression::StyleFeature(Box::new(StyleFeature::Plain {
name,
value: value.to_vec(),
original_source: original_source(original_values),
original_value_source: original_source(value),
- }));
+ })));
}
let name = single_ident(values)?;
if resolve_feature(QueryKind::Style, name.as_ref()).is_none() {
stream.position = stream.values.len();
return Some(Expression::GeneralEnclosedValues {
- components: original_values.to_vec(),
+ text: source_text(original_values),
result: MatchResult::Unknown,
});
}
stream.position = stream.values.len();
- Some(Expression::StyleFeature(StyleFeature::Boolean(name)))
+ Some(Expression::StyleFeature(Box::new(StyleFeature::Boolean(name))))
}
/// A `<style-range>` as `style()` parses it, or `None` where the values are not one.
pub(crate) fn parse_style_range(values: &[ComponentValue]) -> Option<StyleFeature> {
let mut stream = TokenStream::new(values);
match parse_style_feature(&mut stream, &resolve_query_feature)? {
- Expression::StyleFeature(range @ StyleFeature::Range { .. }) => Some(range),
+ Expression::StyleFeature(feature) if matches!(*feature, StyleFeature::Range { .. }) => Some(*feature),
_ => None,
}
}
@@ -1345,7 +1372,7 @@ where
let expression = parsed_expression.filter(|_| !inner.has_next_token()).or_else(|| {
(!trim_whitespace(values).is_empty() && contains_only_any_value(values)).then_some(
Expression::GeneralEnclosedValues {
- components: values.to_vec(),
+ text: source_text(values),
result: MatchResult::Unknown,
},
)
@@ -1398,10 +1425,7 @@ fn scroll_state_feature_accepts_keyword(id: u8, keyword: u16) -> bool {
}
fn scroll_state_feature_value_keyword(id: u8, value: &QueryFeatureValue) -> Option<u16> {
- let [component] = trim_whitespace(&value.components) else {
- return None;
- };
- let keyword = keyword_from_ascii_case_insensitive(component.ident()?)?;
+ let keyword = value.keyword?;
scroll_state_feature_accepts_keyword(id, keyword).then_some(keyword)
}
@@ -1547,9 +1571,6 @@ impl FfiQueryHandle {
impl MediaQuery {
fn detach(&mut self, detacher: &mut TextDetacher) {
- if let Some(media_type) = &mut self.media_type {
- media_type.detach(detacher);
- }
if let Some(condition) = &mut self.condition {
condition.detach(detacher);
}
@@ -1567,40 +1588,19 @@ impl Expression {
Self::And(expressions) | Self::Or(expressions) => expressions
.iter_mut()
.for_each(|expression| expression.detach(detacher)),
- Self::GeneralEnclosed { component, .. } => component.detach(detacher),
- Self::GeneralEnclosedValues { components, .. } => {
- components.iter_mut().for_each(|value| value.detach(detacher));
- }
- Self::QueryFeature(feature) => feature.detach(detacher),
+ Self::GeneralEnclosed { .. } | Self::GeneralEnclosedValues { .. } => {}
+ // NB: A query feature's value holds its own text.
+ Self::QueryFeature(_) => {}
Self::SupportsFeature(feature) => feature.detach(detacher),
Self::StyleFeature(feature) => feature.detach(detacher),
}
}
}
-impl QueryFeature {
- fn detach(&mut self, detacher: &mut TextDetacher) {
- match self {
- Self::Boolean { .. } => {}
- Self::Plain { value, .. } => value.components.iter_mut().for_each(|value| value.detach(detacher)),
- Self::Range { left, right, .. } => {
- if let Some((value, _)) = left {
- value.components.iter_mut().for_each(|value| value.detach(detacher));
- }
- if let Some((_, value)) = right {
- value.components.iter_mut().for_each(|value| value.detach(detacher));
- }
- }
- }
- }
-}
-
impl SupportsFeature {
fn detach(&mut self, detacher: &mut TextDetacher) {
match self {
- Self::Declaration { components, .. } | Self::Selector { components, .. } => {
- components.iter_mut().for_each(|value| value.detach(detacher));
- }
+ Self::Declaration { .. } | Self::Selector { .. } => {}
Self::FontTech { name, .. }
| Self::FontFormat { name, .. }
| Self::AtRule { name, .. }
@@ -1668,7 +1668,8 @@ fn push_utf16(sink: &mut TextSink, value: &[u16]) {
}
fn serialize_query_feature_value(sink: &mut TextSink, value: &QueryFeatureValue, id: u8, kind: QueryKind) {
- let components = trim_whitespace(&value.components);
+ let value_components = value.components();
+ let components = trim_whitespace(&value_components);
let media_feature_value_types = if kind == QueryKind::Media {
MEDIA_FEATURES
.get(usize::from(id))
@@ -1713,7 +1714,7 @@ fn serialize_query_feature_value(sink: &mut TextSink, value: &QueryFeatureValue,
return;
}
let serialized = serialize_component_values_to_utf16(
- &value.components,
+ &value_components,
crate::css::parser::component_value::ComponentSerializationMode::Normalized,
);
push_utf16(sink, &serialized);
@@ -1745,7 +1746,7 @@ fn serialize_query_feature(sink: &mut TextSink, feature: &QueryFeature, kind: Qu
if kind == QueryKind::ScrollState {
sink.push_ascii(name);
if let QueryFeature::Plain { value, .. } = feature
- && let [component] = trim_whitespace(&value.components)
+ && let [component] = value.components().as_slice()
&& let Some(ident) = component.ident()
{
// The value is a keyword, which serializes in lowercase.
@@ -1775,14 +1776,14 @@ fn serialize_query_feature(sink: &mut TextSink, feature: &QueryFeature, kind: Qu
serialize_query_feature_value(sink, value, id, kind);
}
QueryFeature::Range { left, right, .. } => {
- if let Some((value, comparison)) = left {
+ if let Some((value, comparison)) = left.as_deref() {
serialize_query_feature_value(sink, value, id, kind);
sink.push_ascii(" ");
sink.push_ascii(feature_comparison_text(*comparison));
sink.push_ascii(" ");
}
sink.push_ascii(name);
- if let Some((comparison, value)) = right {
+ if let Some((comparison, value)) = right.as_deref() {
sink.push_ascii(" ");
sink.push_ascii(feature_comparison_text(*comparison));
sink.push_ascii(" ");
@@ -1848,24 +1849,15 @@ fn serialize_expression(sink: &mut TextSink, expression: &Expression, kind: Quer
serialize_expression(sink, child, kind);
sink.push_ascii(")");
}
- Expression::GeneralEnclosed { component, .. } => push_utf16(sink, &component.original_source_text.to_vec()),
- Expression::GeneralEnclosedValues { components, .. } => {
- for component in components {
- push_utf16(sink, &component.original_source_text.to_vec());
- }
+ Expression::GeneralEnclosed { text, .. } | Expression::GeneralEnclosedValues { text, .. } => {
+ push_utf16(sink, text.units());
}
Expression::QueryFeature(feature) => serialize_query_feature(sink, feature, kind),
Expression::SupportsFeature(feature) => match feature {
- SupportsFeature::Declaration { components, .. } => {
- for component in components {
- push_utf16(sink, &component.original_source_text.to_vec());
- }
- }
- SupportsFeature::Selector { components, .. } => {
+ SupportsFeature::Declaration { text, .. } => push_utf16(sink, text.units()),
+ SupportsFeature::Selector { text, .. } => {
sink.push_ascii("selector(");
- for component in components {
- push_utf16(sink, &component.original_source_text.to_vec());
- }
+ push_utf16(sink, text.units());
sink.push_ascii(")");
}
SupportsFeature::FontTech { name, .. } => {
@@ -1899,7 +1891,7 @@ fn serialize_expression(sink: &mut TextSink, expression: &Expression, kind: Quer
serialize_expression(sink, child, QueryKind::ScrollState);
sink.push_ascii(")");
}
- Expression::StyleFeature(feature) => match feature {
+ Expression::StyleFeature(feature) => match &**feature {
StyleFeature::Boolean(name) => serialize_style_property_name(sink, name),
StyleFeature::Plain {
name,
@@ -1941,9 +1933,9 @@ fn serialize_media_query(query: &MediaQuery) -> Vec<u16> {
let media_type_is_all = query
.media_type
.as_ref()
- .is_none_or(|media_type| equals_ascii_case_insensitive(media_type, b"all"));
+ .is_none_or(|media_type| equals_ascii_case_insensitive(media_type.units(), b"all"));
if query.negated || !media_type_is_all || query.condition.is_none() {
- let media_type = query.media_type.as_deref().unwrap_or(&[]);
+ let media_type = query.media_type.as_ref().map(CssString::units).unwrap_or(&[]);
if equals_ascii_case_insensitive(media_type, b"all") {
sink.push_ascii("all");
} else if equals_ascii_case_insensitive(media_type, b"print") {
@@ -2037,10 +2029,13 @@ fn resolve_parsed_media_feature_value(
CssPixels::nearest_value_for(pixels).to_double(),
))
}
- StyleValueData::Ratio { numerator, denominator } => Some(ResolvedFeatureValue::Ratio {
- numerator: resolve_number(numerator.data(), length_context)?,
- denominator: resolve_number(denominator.data(), length_context)?,
- }),
+ StyleValueData::Ratio(ratio_payload) => {
+ let RatioPayload { numerator, denominator } = &**ratio_payload;
+ Some(ResolvedFeatureValue::Ratio {
+ numerator: resolve_number(numerator.data(), length_context)?,
+ denominator: resolve_number(denominator.data(), length_context)?,
+ })
+ }
StyleValueData::Resolution { value, unit } => {
let value = crate::css::calc::CalcNumericValue::Resolution {
value: *value,
@@ -2133,10 +2128,7 @@ fn parse_media_feature_value(
let Some(metadata) = MEDIA_FEATURES.get(usize::from(id)) else {
return ResolvedFeatureValue::Unknown;
};
- let components = trim_whitespace(&value.components);
- if let [component] = components
- && let Some(name) = component.ident()
- && let Some(keyword) = keyword_from_ascii_case_insensitive(name)
+ if let Some(keyword) = value.keyword
&& metadata.accepted_keywords.contains(&keyword)
{
return ResolvedFeatureValue::Ident(keyword);
@@ -2181,11 +2173,8 @@ fn parse_size_feature_value(
value: &QueryFeatureValue,
length_context: Option<&FfiLengthResolutionContext>,
) -> ResolvedFeatureValue {
- let components = trim_whitespace(&value.components);
if id == 4
- && let [component] = components
- && let Some(name) = component.ident()
- && let Some(keyword) = keyword_from_ascii_case_insensitive(name)
+ && let Some(keyword) = value.keyword
&& matches!(
keyword,
crate::css::css_enums::keyword::LANDSCAPE | crate::css::css_enums::keyword::PORTRAIT
@@ -2327,14 +2316,14 @@ fn evaluate_query_feature(
}
}
QueryFeature::Range { left, right, .. } => {
- if let Some((value, comparison)) = left {
+ if let Some((value, comparison)) = left.as_deref() {
let value = parse_media_feature_value(id, value, length_context);
let result = compare_feature_values(&value, *comparison, &queried_value);
if result != MatchResult::True {
return result;
}
}
- if let Some((comparison, value)) = right {
+ if let Some((comparison, value)) = right.as_deref() {
let value = parse_media_feature_value(id, value, length_context);
let result = compare_feature_values(&queried_value, *comparison, &value);
if result != MatchResult::True {
@@ -2436,9 +2425,7 @@ pub(crate) fn parse_and_evaluate_media_if_condition(
source: &[u16],
environment: &FfiMediaEnvironment<'_>,
) -> Option<MatchResult> {
- // NB: Mirrors the media arm of evaluate_condition_for_substitution, which this series removed
- // from Libraries/LibWeb/CSS/StyleComputer.cpp. Try a standalone media feature first, then
- // fall back to a full media condition.
+ // NB: Try a standalone media feature first, then fall back to a full media condition.
let expression = parse_media_feature_from_source(source, &resolve_query_feature).or_else(|| {
let values = components_from_source(source)?;
parse_media_condition(&values, &resolve_query_feature)
@@ -2454,9 +2441,7 @@ pub(crate) fn parse_and_evaluate_supports_if_condition(
let declared_namespaces = declared_namespaces_from_context(context);
let evaluate_feature =
|kind: SupportsFeatureKind, value: &[u16]| supports_feature_matches(context, &declared_namespaces, kind, value);
- // NB: Mirrors the supports arm of evaluate_condition_for_substitution, which this series
- // removed from Libraries/LibWeb/CSS/StyleComputer.cpp. Try a supports declaration first,
- // then fall back to a full supports condition.
+ // NB: Try a supports declaration first, then fall back to a full supports condition.
let expression = parse_supports_declaration_from_source(source, &evaluate_feature)
.or_else(|| parse_supports_condition(source, &evaluate_feature))?;
Some(evaluate_supports_expression(&expression))
@@ -2506,7 +2491,7 @@ fn container_requirements_in(expression: &Expression, kind: QueryKind) -> u8 {
}
}
-fn container_size_value(id: u8, facts: &FfiContainerFacts) -> Option<ResolvedFeatureValue> {
+fn container_size_value(id: u8, facts: &ContainerFacts) -> Option<ResolvedFeatureValue> {
if !facts.size_available {
return None;
}
@@ -2538,7 +2523,7 @@ fn container_size_value(id: u8, facts: &FfiContainerFacts) -> Option<ResolvedFea
fn evaluate_container_size_feature(
feature: &QueryFeature,
- facts: &FfiContainerFacts,
+ facts: &ContainerFacts,
length_context: Option<&FfiLengthResolutionContext>,
) -> MatchResult {
let id = match feature {
@@ -2579,14 +2564,14 @@ fn evaluate_container_size_feature(
}
}
QueryFeature::Range { left, right, .. } => {
- if let Some((value, comparison)) = left {
+ if let Some((value, comparison)) = left.as_deref() {
let value = parse_size_feature_value(id, value, length_context);
let result = compare_feature_values(&value, *comparison, &queried_value);
if result != MatchResult::True {
return result;
}
}
- if let Some((comparison, value)) = right {
+ if let Some((comparison, value)) = right.as_deref() {
let value = parse_size_feature_value(id, value, length_context);
let result = compare_feature_values(&queried_value, *comparison, &value);
if result != MatchResult::True {
@@ -2607,7 +2592,7 @@ fn scroll_state_axis_edges(side: u8) -> u8 {
}
// https://drafts.csswg.org/css-conditional-5/#scroll-state-container
-fn evaluate_container_scroll_state_feature(feature: &QueryFeature, facts: &FfiContainerFacts) -> MatchResult {
+fn evaluate_container_scroll_state_feature(feature: &QueryFeature, facts: &ContainerFacts) -> MatchResult {
use crate::css::css_enums::keyword;
if !facts.scroll_state_available {
return MatchResult::Unknown;
@@ -2688,7 +2673,7 @@ pub(crate) type EvaluateStyleFeature<'a> = dyn FnMut(&StyleFeature) -> MatchResu
fn evaluate_container_expression(
expression: &Expression,
- facts: &FfiContainerFacts,
+ facts: &ContainerFacts,
length_context: Option<&FfiLengthResolutionContext>,
style: &mut EvaluateStyleFeature<'_>,
) -> MatchResult {
@@ -2698,7 +2683,7 @@ fn evaluate_container_expression(
fn evaluate_container_expression_in(
expression: &Expression,
kind: QueryKind,
- facts: &FfiContainerFacts,
+ facts: &ContainerFacts,
length_context: Option<&FfiLengthResolutionContext>,
style: &mut EvaluateStyleFeature<'_>,
) -> MatchResult {
@@ -2751,7 +2736,7 @@ fn evaluate_media_query(
environment: &[FfiMediaFeatureValue],
length_context: Option<&FfiLengthResolutionContext>,
) -> MatchResult {
- let mut result = match query.media_type.as_deref() {
+ let mut result = match query.media_type.as_ref().map(CssString::units) {
None => MatchResult::True,
Some(media_type) if equals_ascii_case_insensitive(media_type, b"all") => MatchResult::True,
Some(media_type) if equals_ascii_case_insensitive(media_type, b"screen") => MatchResult::True,
@@ -2821,8 +2806,6 @@ fn default_source_size() -> StyleValueData {
}
// https://html.spec.whatwg.org/multipage/images.html#parsing-a-sizes-attribute
-// NB: Mirrors the C++ implementation of this algorithm that this series replaced in
-// Libraries/LibWeb/CSS/Parser/Parser.cpp.
fn parse_sizes_attribute(
context: &ParseContext,
source: TokenizerInput<'_>,
@@ -2922,12 +2905,9 @@ pub unsafe extern "C" fn rust_parse_sizes_attribute(
};
let media_environment = media_environment.and_then(FfiMediaEnvironment::parts);
let img_auto_width = img_auto_width.copied();
- Arc::into_raw(Arc::new(parse_sizes_attribute(
- context,
- source,
- media_environment,
- img_auto_width,
- )))
+ crate::css::style_value_arc::StyleValueArc::into_raw(crate::css::style_value_arc::StyleValueArc::new(
+ parse_sizes_attribute(context, source, media_environment, img_auto_width),
+ ))
.cast()
}
@@ -3002,7 +2982,7 @@ pub extern "C" fn css_query_evaluate_supports(handle: Option<&FfiQueryHandle>) -
/// The length resolution context in `facts`, if any, must be readable for the call.
pub(crate) unsafe fn evaluate_container_query(
handle: &FfiQueryHandle,
- facts: &FfiContainerFacts,
+ facts: &ContainerFacts,
style: &mut EvaluateStyleFeature<'_>,
) -> MatchResult {
let QueryTree::Expression { expression, kind } = &handle.tree else {
diff --git a/Libraries/LibWeb/Rust/src/css/parser/stylesheet_cache.rs b/Libraries/LibWeb/Rust/src/css/parser/stylesheet_cache.rs
index 1e81dc8a847..6a6859ab739 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/stylesheet_cache.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/stylesheet_cache.rs
@@ -12,6 +12,7 @@ use crate::css::style_compute::{FfiFontMetrics, FfiLengthResolutionContext};
use std::cell::Cell;
use std::collections::{HashMap, HashSet, hash_map::RandomState};
use std::hash::{BuildHasher, Hash, Hasher};
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, Weak};
#[derive(PartialEq, Eq, Hash)]
@@ -318,10 +319,35 @@ impl StyleSheetKey {
}
}
+/// The scheme and host of a document's URL, keyed for each process, which a parse only the process still keeps is
+/// handed out to alone: a hit is about 20 ms faster than a parse, so a page must not be able to tell what the pages
+/// of another site parsed.
+#[derive(Clone, Copy, PartialEq, Eq)]
+struct SitePartition(u64);
+
+impl SitePartition {
+ fn of_document(context: Option<&ParseContext>) -> Self {
+ let url = context.map_or(&[][..], |context| context.document_url.as_slice());
+ let end_of_host = match url.windows(3).position(|bytes| bytes == b"://") {
+ Some(separator) => url[separator + 3..]
+ .iter()
+ .position(|&byte| matches!(byte, b'/' | b'?' | b'#'))
+ .map_or(url.len(), |end| separator + 3 + end),
+ None => url.iter().position(|&byte| byte == b':').unwrap_or(url.len()),
+ };
+ static HASHER: OnceLock<RandomState> = OnceLock::new();
+ Self(HASHER.get_or_init(RandomState::new).hash_one(&url[..end_of_host]))
+ }
+}
+
pub(super) struct CachedParseMetadata {
key: StyleSheetKey,
dependencies: ParseDependencies,
final_random_function_index: Option<usize>,
+ /// The partition of the document that last asked for the parse.
+ partition: AtomicU64,
+ /// Whether the process keeps the parse past its last document.
+ kept: AtomicBool,
}
type Entries = HashMap<u64, Vec<Weak<ParsedStyleSheet>>>;
@@ -368,15 +394,27 @@ impl Drop for InFlightParse {
}
}
-fn find(entries: &Entries, hash: u64, key: &StyleSheetKey) -> Option<Arc<ParsedStyleSheet>> {
+fn find(entries: &Entries, hash: u64, key: &StyleSheetKey, partition: SitePartition) -> Option<Arc<ParsedStyleSheet>> {
entries.get(&hash)?.iter().filter_map(Weak::upgrade).find(|sheet| {
- sheet
- .cache_metadata
- .as_ref()
- .is_some_and(|metadata| metadata.key.matches(key, metadata.dependencies))
+ sheet.cache_metadata.as_ref().is_some_and(|metadata| {
+ // NB: Only the upgrade and what the process keeps hold a parse no document holds.
+ let only_kept = metadata.kept.load(Ordering::Relaxed) && Arc::strong_count(sheet) == 2;
+ metadata.key.matches(key, metadata.dependencies)
+ && (!only_kept || metadata.partition.load(Ordering::Relaxed) == partition.0)
+ })
})
}
+/// Have the process keep `sheet`, a parse just published, which holds about `bytes`.
+fn keep_past_release(sheet: &Arc<ParsedStyleSheet>, bytes: usize) {
+ let metadata = sheet
+ .cache_metadata
+ .as_ref()
+ .expect("a published parse has its metadata");
+ metadata.kept.store(true, Ordering::Relaxed);
+ crate::render_state::process_style().keep_parsed_sheet(sheet, bytes);
+}
+
pub(super) fn parse_with_cache(
source: TokenizerInput<'_>,
context: Option<&ParseContext>,
@@ -389,6 +427,7 @@ pub(super) fn parse_with_cache(
},
None => None,
};
+ let partition = SitePartition::of_document(context);
let key = StyleSheetKey {
text: TextDigest::new(source),
context: context_key,
@@ -410,7 +449,10 @@ pub(super) fn parse_with_cache(
let cached = {
let mut cache = shared.lock();
loop {
- if let Some(sheet) = hashes.iter().find_map(|&hash| find(&cache.entries, hash, &key)) {
+ if let Some(sheet) = hashes
+ .iter()
+ .find_map(|&hash| find(&cache.entries, hash, &key, partition))
+ {
break Some(sheet);
}
// The parse in flight may publish under a context-dependent hash that this key doesn't match; the
@@ -422,7 +464,10 @@ pub(super) fn parse_with_cache(
}
};
if let Some(sheet) = cached {
- sheet.cache_metadata.as_ref().unwrap().dependencies.record();
+ let metadata = sheet.cache_metadata.as_ref().unwrap();
+ metadata.partition.store(partition.0, Ordering::Relaxed);
+ crate::render_state::process_style().note_parsed_sheet_use(&sheet);
+ metadata.dependencies.record();
if let Some(counter) = context.and_then(|context| context.random_function_index) {
counter.set(
sheet
@@ -446,7 +491,7 @@ pub(super) fn parse_with_cache(
let mut cache = shared.lock();
let entries = &mut cache.entries;
// A worker whose context matched this key under another dependency may have published while this one parsed.
- if let Some(sheet) = find(entries, hash, &key) {
+ if let Some(sheet) = find(entries, hash, &key, partition) {
drop(cache);
drop(in_flight);
return sheet;
@@ -461,11 +506,19 @@ pub(super) fn parse_with_cache(
final_random_function_index: context
.and_then(|context| context.random_function_index)
.map(RandomFunctionIndex::get),
+ partition: AtomicU64::new(partition.0),
+ kept: AtomicBool::new(false),
});
+ let bytes = source.len() + sheet.bytes_kept_past_release();
let sheet = Arc::new(sheet);
entries.entry(hash).or_default().push(Arc::downgrade(&sheet));
drop(cache);
drop(in_flight);
+ // NB: Unit tests of parsing count what a parse holds, and that it goes with its last holder.
+ #[cfg(not(test))]
+ keep_past_release(&sheet, bytes);
+ #[cfg(test)]
+ let _ = bytes;
sheet
}
@@ -473,6 +526,33 @@ pub(super) fn parse_with_cache(
mod tests {
use super::*;
+ fn parsed_for_document(source: &str, document_url: &'static str) -> Arc<ParsedStyleSheet> {
+ let units: Vec<u16> = source.encode_utf16().collect();
+ let context = ParseContext {
+ document_url: ak::Span::new(document_url.as_bytes()),
+ ..Default::default()
+ };
+ crate::css::parser::syntax_parser::parse_shared_stylesheet(TokenizerInput::Utf16(&units), Some(&context))
+ }
+
+ #[test]
+ fn a_page_of_the_same_site_finds_a_parse_no_document_holds_and_another_sites_does_not() {
+ let source = ".kept-past-release { width: 11.75px }";
+ let first = parsed_for_document(source, "https://one.example/a");
+ keep_past_release(&first, 0);
+ let pointer = Arc::as_ptr(&first);
+ drop(first);
+ let second = parsed_for_document(source, "https://one.example/b");
+ assert_eq!(Arc::as_ptr(&second), pointer);
+ drop(second);
+ let other_site = parsed_for_document(source, "https://other.example/a");
+ assert_ne!(Arc::as_ptr(&other_site), pointer);
+
+ // While a document holds a parse, any document finds it, as a frame of another site does.
+ let frame = parsed_for_document(source, "https://third.example/a");
+ assert!(Arc::ptr_eq(&frame, &other_site));
+ }
+
#[test]
fn text_digests_agree_for_ascii_and_utf16_forms_of_one_text() {
let utf16 = |text: &str| text.encode_utf16().collect::<Vec<_>>();
diff --git a/Libraries/LibWeb/Rust/src/css/parser/syntax.rs b/Libraries/LibWeb/Rust/src/css/parser/syntax.rs
index c35c51b75ed..781e78cf6e9 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/syntax.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/syntax.rs
@@ -451,12 +451,6 @@ pub extern "C" fn rust_syntax_release(syntax: OwnedArc<SyntaxNode>) {
drop(syntax);
}
-/// # Safety
-/// `syntax` must be null or a live parsed-syntax handle.
-pub(crate) unsafe fn clone_syntax_handle(syntax: *const c_void) -> Option<SyntaxNode> {
- unsafe { syntax.cast::<SyntaxNode>().as_ref() }.cloned()
-}
-
#[unsafe(no_mangle)]
pub extern "C" fn rust_syntax_is_universal(syntax: &SyntaxNode) -> bool {
matches!(syntax, SyntaxNode::Universal)
@@ -521,13 +515,14 @@ pub unsafe extern "C" fn rust_parse_with_syntax(
return std::ptr::null();
};
*out_status = FfiParseStatus::Parsed;
- Arc::into_raw(Arc::new(parsed)).cast()
+ crate::css::style_value_arc::StyleValueArc::into_raw(crate::css::style_value_arc::StyleValueArc::new(parsed)).cast()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::css::parser::value_parser::RandomFunctionIndex;
+ use crate::css::style_value::UnresolvedPayload;
fn context(random_function_index: &RandomFunctionIndex) -> ParseContext<'_> {
ParseContext {
@@ -626,12 +621,21 @@ mod tests {
crate::css::css_tokenizer::tokenize_for_parser_without_source(b"1.00px").into_vec(),
)
.unwrap();
- let Some(StyleValueData::Unresolved { source_text, .. }) =
+ let Some(StyleValueData::Unresolved(unresolved_payload)) =
parse_with_syntax_component_values(&context, &values, &SyntaxNode::Universal, Some(&source))
else {
panic!("expected an unresolved value");
};
- assert_eq!(source_text.units(), source);
+ let unresolved_payload: &UnresolvedPayload = &unresolved_payload;
+ let source_text = unresolved_payload.source_text();
+ assert_eq!(
+ {
+ let mut units = Vec::new();
+ source_text.append_to(&mut units);
+ units
+ },
+ source
+ );
}
#[test]
@@ -640,16 +644,24 @@ mod tests {
let context = context(&random_function_index);
let mut values = consume_a_list_of_component_values(tokenize_for_parser(b"a b".as_slice())).unwrap();
values.remove(1);
- let Some(StyleValueData::Unresolved {
- source_text,
- components,
- ..
- }) = parse_with_syntax_component_values(&context, &values, &SyntaxNode::Universal, None)
+ let Some(StyleValueData::Unresolved(unresolved_payload)) =
+ parse_with_syntax_component_values(&context, &values, &SyntaxNode::Universal, None)
else {
panic!("expected an unresolved value");
};
- assert_eq!(source_text.units(), utf16("a/**/b"));
- assert_eq!(components.as_slice(), values.as_slice());
+ let source_text = unresolved_payload.source_text();
+ assert_eq!(
+ {
+ let mut units = Vec::new();
+ source_text.append_to(&mut units);
+ units
+ },
+ utf16("a/**/b")
+ );
+ assert!(crate::css::style_value::components_equal(
+ &unresolved_payload.components(),
+ &values
+ ));
}
#[test]
diff --git a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs
index 3568ed697e4..53bd77adaad 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs
@@ -12,7 +12,9 @@ use crate::css::css_tokenizer::{
CssNumberType, ParserString, ParserToken, ParserTokenFeed, ParserTokenKind, SourcePosition, TokenizerInput,
tokenize_for_parser,
};
-use crate::css::declaration_block::{DeclarationBlock, DeclarationBlockData, DeclaredProperty};
+use crate::css::declaration_block::{
+ DeclarationBlock, DeclarationBlockBuilder, DeclaredProperty, SharedDeclarationBlock,
+};
use crate::css::descriptor_block::{DescriptorBlockData, DescriptorData, FfiDescriptorBlock};
use crate::css::descriptor_metadata::{CUSTOM_DESCRIPTOR_ID, descriptor_longhands};
use crate::css::ffi_support::{ArcRef, FfiUtf16View, OwnedArc};
@@ -34,7 +36,7 @@ use crate::css::parser::component_value::{
use crate::css::parser::descriptor_parser::parse_descriptor;
use crate::css::parser::query_parser::{
ContainerCondition, Expression, FfiQueryHandle, MediaQuery, QueryKind, declared_namespaces_from_context,
- expression_query_handle, media_query_handle, parse_container_condition_list_from_component_values,
+ expression_query_handle, parse_container_condition_list_from_component_values,
parse_media_query_list_from_component_values, parse_supports_condition_from_component_values,
parse_supports_declaration_from_component_values, resolve_query_feature, supports_feature_matches,
};
@@ -48,15 +50,18 @@ use crate::css::property_metadata::{property_id, property_id_from_name};
use crate::css::property_rule::PropertyRuleData;
use crate::css::rule::{NativeRule, NativeRuleList, NativeRuleType, RulePayload};
use crate::css::scope_selectors::ScopeSelectors;
+use crate::css::selector_arena::{NestingTarget, RuleOrdinal};
use crate::css::selector_parser::{
RustParsedSelectorList, SelectorType, StyleNestingParent, parse_selector_list_from_component_values,
};
use crate::css::serialize::serialize_component_values_to_utf16;
use crate::css::style_compute::value_is_computationally_independent;
use crate::css::style_rule::StyleRule;
-use crate::css::style_value::{RetainedRequestUrlModifierList, RetainedString, StyleValueData};
+use crate::css::style_value::{RetainedRequestUrlModifierList, RetainedString, StyleValueBox, StyleValueData};
+use crate::css::style_value::{ShorthandPayload, UrlPayload};
+use crate::css::style_value_arc::StyleValueArc;
use std::borrow::Cow;
-use std::cell::RefCell;
+use std::cell::{Cell, RefCell};
use std::ffi::c_void;
use std::fmt;
use std::rc::Rc;
@@ -248,7 +253,7 @@ struct ParsedImportPrelude {
}
#[derive(Clone, PartialEq)]
-struct ParsedStyleValue(Arc<StyleValueData>);
+struct ParsedStyleValue(StyleValueArc);
impl fmt::Debug for ParsedStyleValue {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
@@ -559,7 +564,7 @@ fn parse_scope_prelude(
let Some(start) = parse_selector(start, selector_type) else {
return ParsedRulePrelude::Invalid;
};
- Some(start.adapt_for_nesting(nesting_parent))
+ Some(start.adapt_for_nesting(nesting_parent).into_list(nesting_parent))
}
None => None,
};
@@ -568,7 +573,7 @@ fn parse_scope_prelude(
let Some(end) = parse_selector(end, SelectorType::Relative) else {
return ParsedRulePrelude::Invalid;
};
- Some(end)
+ Some(end.into_list(StyleNestingParent::None))
}
None => None,
};
@@ -642,23 +647,23 @@ fn parse_import_selector(
if selectors.is_empty() || selectors.contains_pseudo_element() {
return None;
}
- Some(selectors)
+ Some(selectors.into_list(StyleNestingParent::None))
}
fn parse_import_url(context: &ParseContext, value: &ComponentValue) -> Option<ParsedStyleValue> {
let url = match &value.kind {
- ComponentKind::Token(ParserTokenKind::String(url)) => StyleValueData::Url {
+ ComponentKind::Token(ParserTokenKind::String(url)) => StyleValueData::Url(StyleValueBox::new(UrlPayload {
url: RetainedString::from_utf16(url)?,
url_type: 0,
modifiers: RetainedRequestUrlModifierList::from_retained_modifiers(Vec::new()),
- },
+ })),
ComponentKind::Token(ParserTokenKind::Url(_)) => parse_url_value(context, value)?,
ComponentKind::Function { name, .. } if equals_ascii_case_insensitive(name, b"url") => {
parse_url_value(context, value)?
}
_ => return None,
};
- Some(ParsedStyleValue(Arc::new(url)))
+ Some(ParsedStyleValue(StyleValueArc::new(url)))
}
fn parse_import_prelude<R>(
@@ -789,19 +794,13 @@ fn parse_css_type(values: &[ComponentValue], position: &mut usize) -> Option<Par
fn unresolved_contains_arbitrary_substitution_function(value: &StyleValueData) -> bool {
matches!(
value,
- StyleValueData::Unresolved {
- presence_attr: true,
- ..
- } | StyleValueData::Unresolved {
- presence_dashed_function: true,
- ..
- } | StyleValueData::Unresolved { presence_env: true, .. }
- | StyleValueData::Unresolved { presence_if: true, .. }
- | StyleValueData::Unresolved {
- presence_inherit: true,
- ..
- }
- | StyleValueData::Unresolved { presence_var: true, .. }
+ StyleValueData::Unresolved(unresolved)
+ if unresolved.presence().attr
+ || unresolved.presence().dashed_function
+ || unresolved.presence().env
+ || unresolved.presence().if_
+ || unresolved.presence().inherit
+ || unresolved.presence().var
)
}
@@ -822,7 +821,7 @@ fn parse_function_default(
return Some(ParsedStyleValue(unparsed));
}
let source = serialize_component_values_to_utf16(values, ComponentSerializationMode::Retokenize);
- parse_with_syntax(context, &source, syntax).map(|value| ParsedStyleValue(Arc::new(value)))
+ parse_with_syntax(context, &source, syntax).map(|value| ParsedStyleValue(StyleValueArc::new(value)))
}
fn parse_function_prelude(rule: &AtRule, context: &ParseContext) -> ParsedRulePrelude {
@@ -1034,7 +1033,7 @@ fn parse_property_prelude(rule: &AtRule, context: &ParseContext) -> ParsedRulePr
return ParsedRulePrelude::Invalid;
}
let initial_value = initial_value_source.map(|source| {
- ParsedStyleValue(Arc::new(
+ ParsedStyleValue(StyleValueArc::new(
parse_with_syntax(context, &source, &syntax).unwrap_or(StyleValueData::GuaranteedInvalid),
))
});
@@ -1359,6 +1358,14 @@ fn has_ignored_vendor_prefix(name: TokenizerInput<'_>) -> bool {
> 1
}
+/// What the rule is nested in, as `&` sees it.
+fn rule_nesting_parent(rule: &Rule) -> StyleNestingParent {
+ match rule {
+ Rule::At(rule) => rule.nesting_parent,
+ Rule::Qualified(rule) => rule.nesting_parent,
+ }
+}
+
fn rule_kind(rule: &Rule) -> ParsedRuleKind {
let Rule::At(rule) = rule else {
return ParsedRuleKind::Qualified;
@@ -1408,8 +1415,6 @@ fn at_rule_kind(name: &[u16]) -> ParsedRuleKind {
}
}
-// NB: Mirrors the at-rule support list that this series removed from
-// Libraries/LibWeb/CSS/Parser/RustQueryParsing.cpp.
pub(crate) fn at_rule_is_supported(name: &[u16]) -> bool {
!matches!(
at_rule_kind(name),
@@ -2103,22 +2108,25 @@ pub enum FfiDeclarationRejection {
struct ParsedDeclarationList {
local_identity: u64,
- source_position: Option<(usize, usize)>,
- declaration_block: Option<Arc<DeclarationBlockData>>,
+ source_position: Option<(u32, u32)>,
+ declaration_block: Option<SharedDeclarationBlock>,
descriptor_block: Option<Arc<DescriptorBlockData>>,
}
enum ParsedRuleChild {
Rule(Arc<ParsedRule>),
- Declarations(ParsedDeclarationList),
+ /// Boxed, as most children are rules, which would otherwise each pay for a declaration list.
+ Declarations(Box<ParsedDeclarationList>),
}
fn declaration_block_from_blocks<'a>(
- blocks: impl Iterator<Item = &'a Arc<DeclarationBlockData>>,
-) -> Arc<DeclarationBlockData> {
+ blocks: impl Iterator<Item = &'a SharedDeclarationBlock>,
+) -> SharedDeclarationBlock {
// https://drafts.csswg.org/cssom/#parse-a-css-declaration-block
// 2. Let parsed declarations be a new empty list.
- let mut declarations: Option<Arc<DeclarationBlockData>> = None;
+ // NB: A single item's block is shared as is; a builder is made only once a second item appends.
+ let mut first: Option<&SharedDeclarationBlock> = None;
+ let mut declarations: Option<DeclarationBlockBuilder> = None;
// 3. For each item declaration in declarations, follow these substeps:
for block in blocks {
// 1. Let parsed declaration be the result of parsing declaration according to the appropriate CSS
@@ -2127,13 +2135,21 @@ fn declaration_block_from_blocks<'a>(
// 2. If parsed declaration is not null, append it to parsed declarations.
// NB: Each declaration-list item already owns its parsed, normalized properties.
if let Some(declarations) = &mut declarations {
- Arc::make_mut(declarations).append_block(block);
+ declarations.append_block(block);
+ } else if let Some(first) = first {
+ let mut builder = first.to_builder();
+ builder.append_block(block);
+ declarations = Some(builder);
} else {
- declarations = Some(block.clone());
+ first = Some(block);
}
}
// 4. Return parsed declarations.
- declarations.unwrap_or_default()
+ match (declarations, first) {
+ (Some(declarations), _) => declarations.finish(),
+ (None, Some(first)) => first.clone(),
+ (None, None) => SharedDeclarationBlock::default(),
+ }
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -2208,47 +2224,238 @@ struct ParsedDeclaration {
property_id: u16,
descriptor_id: u8,
rejection: FfiDeclarationRejection,
- parsed_value: Option<Arc<StyleValueData>>,
+ parsed_value: Option<StyleValueArc>,
font_feature_values_start: usize,
font_feature_value_count: usize,
}
struct ParsedRule {
- local_identity: u64,
+ local_identity: u32,
is_qualified: bool,
rule_kind: ParsedRuleKind,
- name_offset: usize,
- name_length: usize,
- declaration_block: Option<Arc<DeclarationBlockData>>,
- children: Box<[ParsedRuleChild]>,
- native_children: Box<[usize]>,
has_block: bool,
has_source_position: bool,
- start_line: usize,
- start_column: usize,
- page_selector_list: Option<Arc<PageSelectorList>>,
- import_rule: Option<Arc<ImportRuleData>>,
- supports_condition: Option<Arc<FfiQueryHandle>>,
- selector_list: Option<Arc<RustParsedSelectorList>>,
- descriptor_block: Option<Arc<DescriptorBlockData>>,
- layer_names: Option<Arc<LayerNames>>,
- container_conditions: Option<Arc<ContainerConditionsData>>,
- font_feature_values: Option<Arc<FontFeatureValuesData>>,
- keyframe: Option<Arc<KeyframeData>>,
- keyframes_name: Option<CssString>,
- position_try_name: Option<CssString>,
- scope_selectors: Option<Arc<ScopeSelectors>>,
- media_list: Option<Arc<MediaListData>>,
- counter_style: Option<Arc<CounterStyleData>>,
- namespace_rule: Option<Arc<NamespaceRuleData>>,
- property_rule: Option<Arc<PropertyRuleData>>,
- function_signature: Option<Arc<FunctionSignature>>,
+ start_line: u32,
+ start_column: u32,
+ /// None for a rule without child rules or declarations, as most style rules are.
+ children: Option<Box<ParsedRuleChildren>>,
+ payload: ParsedRulePayload,
+}
+
+// Most of a sheet's parse graph is its rules.
+const _: () = assert!(size_of::<ParsedRulePayload>() == 24);
+const _: () = assert!(size_of::<ParsedRule>() == 48);
+
+struct ParsedRuleChildren {
+ children: Box<[ParsedRuleChild]>,
+ /// The positions among `children` of the rules the CSSOM sees.
+ native_children: Box<[u32]>,
+}
+
+/// What a rule holds of its own kind: a style rule its selectors and declarations, an at-rule its
+/// condition, name or definition. Most of a sheet's rules are style rules, so each rule holds the
+/// payload of its own kind alone, rather than an empty slot for the payload of every other kind.
+enum ParsedRulePayload {
+ None,
+ Style {
+ selector_list: Option<Arc<RustParsedSelectorList>>,
+ declaration_block: SharedDeclarationBlock,
+ },
+ Keyframe(Arc<KeyframeData>),
+ Import {
+ import_rule: Arc<ImportRuleData>,
+ media_list: Arc<MediaListData>,
+ },
+ Media(Arc<MediaListData>),
+ Supports(Arc<FfiQueryHandle>),
+ Container(Arc<ContainerConditionsData>),
+ Scope(Arc<ScopeSelectors>),
+ Layer(Arc<LayerNames>),
+ Page {
+ selectors: Arc<PageSelectorList>,
+ descriptors: Arc<DescriptorBlockData>,
+ },
+ FontFace(Arc<DescriptorBlockData>),
+ FontFeatureValues(Arc<FontFeatureValuesData>),
+ /// A block of `@font-feature-values`, such as `@swash`, which its parent reads.
+ FontFeatureValuesRule(FontFeatureValuesRuleKind),
+ Keyframes(CssString),
+ Margin {
+ /// The rule's name, in ASCII lowercase.
+ name: CssString,
+ declaration_block: SharedDeclarationBlock,
+ },
+ PositionTry {
+ name: CssString,
+ declaration_block: SharedDeclarationBlock,
+ },
+ CounterStyle(Arc<CounterStyleData>),
+ Namespace(Arc<NamespaceRuleData>),
+ Property(Arc<PropertyRuleData>),
+ Function(Arc<FunctionSignature>),
+}
+
+impl ParsedRule {
+ fn children(&self) -> &[ParsedRuleChild] {
+ self.children.as_ref().map_or(&[], |children| &children.children)
+ }
+
+ fn native_children(&self) -> &[u32] {
+ self.children.as_ref().map_or(&[], |children| &children.native_children)
+ }
+
+ fn source_position(&self) -> Option<(usize, usize)> {
+ self.has_source_position
+ .then_some((self.start_line as usize, self.start_column as usize))
+ }
+
+ fn selector_list(&self) -> Option<&Arc<RustParsedSelectorList>> {
+ match &self.payload {
+ ParsedRulePayload::Style { selector_list, .. } => selector_list.as_ref(),
+ _ => None,
+ }
+ }
+
+ fn declaration_block(&self) -> Option<&SharedDeclarationBlock> {
+ match &self.payload {
+ ParsedRulePayload::Style { declaration_block, .. }
+ | ParsedRulePayload::Margin { declaration_block, .. }
+ | ParsedRulePayload::PositionTry { declaration_block, .. } => Some(declaration_block),
+ ParsedRulePayload::Keyframe(keyframe) => Some(&keyframe.declarations),
+ _ => None,
+ }
+ }
+
+ fn keyframe(&self) -> Option<&Arc<KeyframeData>> {
+ match &self.payload {
+ ParsedRulePayload::Keyframe(keyframe) => Some(keyframe),
+ _ => None,
+ }
+ }
+
+ fn import_rule(&self) -> Option<&Arc<ImportRuleData>> {
+ match &self.payload {
+ ParsedRulePayload::Import { import_rule, .. } => Some(import_rule),
+ _ => None,
+ }
+ }
+
+ fn media_list(&self) -> Option<&Arc<MediaListData>> {
+ match &self.payload {
+ ParsedRulePayload::Import { media_list, .. } | ParsedRulePayload::Media(media_list) => Some(media_list),
+ _ => None,
+ }
+ }
+
+ fn supports_condition(&self) -> Option<&Arc<FfiQueryHandle>> {
+ match &self.payload {
+ ParsedRulePayload::Supports(condition) => Some(condition),
+ _ => None,
+ }
+ }
+
+ fn container_conditions(&self) -> Option<&Arc<ContainerConditionsData>> {
+ match &self.payload {
+ ParsedRulePayload::Container(conditions) => Some(conditions),
+ _ => None,
+ }
+ }
+
+ fn scope_selectors(&self) -> Option<&Arc<ScopeSelectors>> {
+ match &self.payload {
+ ParsedRulePayload::Scope(selectors) => Some(selectors),
+ ParsedRulePayload::Import { import_rule, .. } => import_rule.scope.as_ref(),
+ _ => None,
+ }
+ }
+
+ fn layer_names(&self) -> Option<&Arc<LayerNames>> {
+ match &self.payload {
+ ParsedRulePayload::Layer(names) => Some(names),
+ _ => None,
+ }
+ }
+
+ fn page_selector_list(&self) -> Option<&Arc<PageSelectorList>> {
+ match &self.payload {
+ ParsedRulePayload::Page { selectors, .. } => Some(selectors),
+ _ => None,
+ }
+ }
+
+ /// The descriptors of a rule that holds them: `@font-face`, `@page` and `@counter-style`.
+ fn descriptor_block(&self) -> Option<&Arc<DescriptorBlockData>> {
+ match &self.payload {
+ ParsedRulePayload::FontFace(descriptors) | ParsedRulePayload::Page { descriptors, .. } => Some(descriptors),
+ ParsedRulePayload::CounterStyle(counter_style) => Some(&counter_style.descriptors),
+ _ => None,
+ }
+ }
+
+ fn margin_name(&self) -> Option<&CssString> {
+ match &self.payload {
+ ParsedRulePayload::Margin { name, .. } => Some(name),
+ _ => None,
+ }
+ }
+
+ fn font_feature_values(&self) -> Option<&Arc<FontFeatureValuesData>> {
+ match &self.payload {
+ ParsedRulePayload::FontFeatureValues(values) => Some(values),
+ _ => None,
+ }
+ }
+
+ fn keyframes_name(&self) -> Option<&CssString> {
+ match &self.payload {
+ ParsedRulePayload::Keyframes(name) => Some(name),
+ _ => None,
+ }
+ }
+
+ fn position_try_name(&self) -> Option<&CssString> {
+ match &self.payload {
+ ParsedRulePayload::PositionTry { name, .. } => Some(name),
+ _ => None,
+ }
+ }
+
+ fn counter_style(&self) -> Option<&Arc<CounterStyleData>> {
+ match &self.payload {
+ ParsedRulePayload::CounterStyle(counter_style) => Some(counter_style),
+ _ => None,
+ }
+ }
+
+ fn namespace_rule(&self) -> Option<&Arc<NamespaceRuleData>> {
+ match &self.payload {
+ ParsedRulePayload::Namespace(namespace) => Some(namespace),
+ _ => None,
+ }
+ }
+
+ fn property_rule(&self) -> Option<&Arc<PropertyRuleData>> {
+ match &self.payload {
+ ParsedRulePayload::Property(property) => Some(property),
+ _ => None,
+ }
+ }
+
+ fn function_signature(&self) -> Option<&Arc<FunctionSignature>> {
+ match &self.payload {
+ ParsedRulePayload::Function(signature) => Some(signature),
+ _ => None,
+ }
+ }
}
// Parser state is discarded before publishing the owned result.
struct SyntaxParseBuilder<'a> {
declarations_kind: NestedDeclarationsKind,
values: Vec<u16>,
+ /// The names and value texts of the declarations, which the parse keeps of only the few
+ /// declarations it reports: the rest are read while their blocks are built, then dropped.
+ declaration_text: Vec<u16>,
declarations: Vec<ParsedDeclaration>,
// Declaration ranges are builder state; published lists retain their normalized blocks.
declaration_ranges: Vec<std::ops::Range<usize>>,
@@ -2264,6 +2471,13 @@ struct SyntaxParseBuilder<'a> {
parse_context: Option<&'a ParseContext<'a>>,
preserve_property_source_text: bool,
dedup: DeclarationDedup,
+ /// The arena the selectors of the sheet's style rules go into, frozen as the parse finishes.
+ selectors: RefCell<crate::css::selector_arena::SheetSelectorsBuilder>,
+ /// What a `&` in the rules being appended names, or none outside every rule.
+ nesting: Cell<Option<NestingTarget>>,
+ /// What the rule the rules being appended are directly in is to a `&`, or none outside every
+ /// rule.
+ parent: Cell<Option<NestingTarget>>,
}
/// What was parsed for each key, by the key's hash.
@@ -2280,7 +2494,14 @@ struct DeclarationDedup {
/// The range of `keys` for each declaration, by index; `None` for one that is never shared.
declaration_keys: Vec<Option<std::ops::Range<usize>>>,
values: DedupBuckets<ParsedDeclarationValue>,
- blocks: DedupBuckets<Arc<DeclarationBlockData>>,
+ blocks: DedupBuckets<SharedDeclarationBlock>,
+ /// The values the sheet's declarations parsed to, by their content's hash, so that declarations
+ /// of different properties, or differently written, that parse to the same value hold one
+ /// allocation of it.
+ parsed_values: std::collections::HashMap<u64, Vec<StyleValueArc>>,
+ /// The names of the custom properties the sheet declares, so that the declarations of one name
+ /// hold one string of it.
+ custom_property_names: RefCell<std::collections::HashMap<Box<[u16]>, CssString>>,
/// Keyed at random, so that a page cannot make many keys fall into one bucket.
hasher: std::collections::hash_map::RandomState,
}
@@ -2298,6 +2519,17 @@ impl DeclarationDedup {
self.keys.extend_from_slice(units);
}
+ /// The allocation of a value equal to `value` the sheet already holds, or `value` itself, which
+ /// later equal values then share.
+ fn intern_value(&mut self, value: &StyleValueArc) -> StyleValueArc {
+ let candidates = self.parsed_values.entry(value.content_hash()).or_default();
+ if let Some(interned) = candidates.iter().find(|candidate| ***candidate == **value) {
+ return interned.clone();
+ }
+ candidates.push(value.clone());
+ value.clone()
+ }
+
fn find<'a, T>(&self, candidates: &'a DedupBuckets<T>, hash: u64, key: &std::ops::Range<usize>) -> Option<&'a T> {
candidates
.get(&hash)?
@@ -2307,7 +2539,7 @@ impl DeclarationDedup {
}
}
-type ParsedDeclarationValue = (u16, u8, FfiDeclarationRejection, Option<Arc<StyleValueData>>);
+type ParsedDeclarationValue = (u16, u8, FfiDeclarationRejection, Option<StyleValueArc>);
/// Whether parsing `values` may do more than produce a value, which sharing the result would skip: `attr()` records
/// the attribute names it reads, and `random()` values have an identity of their own.
@@ -2326,20 +2558,23 @@ fn value_may_not_be_shared(values: &[ComponentValue]) -> bool {
// The shared graph owns typed Rust payloads, independently of any FFI views.
pub struct ParsedStyleSheet {
identity_count: u64,
+ /// The text the sheet was parsed from, which DevTools shows: one copy for every document the
+ /// parse cache gives this parse.
+ source_text: RetainedString,
pub(super) cache_metadata: Option<CachedParseMetadata>,
declarations_kind: NestedDeclarationsKind,
values: Box<[u16]>,
// Raw declarations remain only for root callbacks and diagnostics.
declarations: Box<[ParsedDeclaration]>,
- root_declarations: Box<[usize]>,
+ root_declarations: Box<[u32]>,
rules: Box<[Arc<ParsedRule>]>,
items: Box<[ParsedRuleChild]>,
- native_roots: Box<[usize]>,
+ native_roots: Box<[u32]>,
/// The positions among `native_roots` of the rules that are, or hold, a rule a media evaluation reads: all of the
/// sheet an evaluation reaches while the sheet's own media holds as it did.
- media_holding_roots: Box<[usize]>,
+ media_holding_roots: Box<[u32]>,
diagnostics: Box<[FfiSyntaxDiagnostic]>,
- declaration_errors: Box<[usize]>,
+ declaration_errors: Box<[u32]>,
}
const _: () = {
@@ -2354,10 +2589,23 @@ enum NestedDeclarationsKind {
}
impl ParsedStyleSheet {
+ /// About how many bytes the parse holds beside its text: its values, and a rule for each identity.
+ pub(super) fn bytes_kept_past_release(&self) -> usize {
+ size_of::<Self>()
+ + size_of_val(&*self.values)
+ + size_of_val(&*self.declarations)
+ + size_of_val(&*self.items)
+ + usize::try_from(self.identity_count).expect("a parse fits in memory") * size_of::<ParsedRule>()
+ }
+
pub(crate) fn identity_count(&self) -> u64 {
self.identity_count
}
+ pub(crate) fn source_text(&self) -> &RetainedString {
+ &self.source_text
+ }
+
fn native_declarations(
&self,
declarations: &ParsedDeclarationList,
@@ -2370,7 +2618,9 @@ impl ParsedStyleSheet {
RulePayload::NestedDeclarations(Box::new(DeclarationBlock::new(
declarations.declaration_block.as_ref().unwrap().clone(),
))),
- declarations.source_position,
+ declarations
+ .source_position
+ .map(|(line, column)| (line as usize, column as usize)),
),
NestedDeclarationsKind::Function => (
NativeRuleType::FunctionDeclarations,
@@ -2396,78 +2646,65 @@ impl ParsedStyleSheet {
list: &NativeRuleList,
) -> Option<Rc<NativeRule>> {
let kind = rule.native_type()?;
+ // NB: A style rule without nested rules makes its empty list only if the CSSOM asks for it.
let child_rules = kind
.child_declarations_kind(declarations_kind)
+ .filter(|_| kind != NativeRuleType::Style || !rule.children().is_empty())
.map(|kind| list.parsed_children(ParsedRuleList::children(self.clone(), rule.clone(), kind)));
- let position =
- (kind == NativeRuleType::Style && rule.has_source_position).then_some((rule.start_line, rule.start_column));
+ let position = rule.source_position().filter(|_| kind == NativeRuleType::Style);
let payload = match kind {
NativeRuleType::Style => RulePayload::Style(StyleRule::new(
- rule.selector_list.as_ref().unwrap().clone(),
- rule.declaration_block.as_ref().unwrap().clone(),
+ rule.selector_list().unwrap().clone(),
+ rule.declaration_block().unwrap().clone(),
)),
NativeRuleType::Keyframe => {
- RulePayload::Keyframe(Box::new(FfiKeyframe::new(rule.keyframe.as_ref().unwrap().clone())))
+ RulePayload::Keyframe(Box::new(FfiKeyframe::new(rule.keyframe().unwrap().clone())))
}
NativeRuleType::Import => RulePayload::Import {
- data: rule.import_rule.as_ref().unwrap().clone(),
+ data: rule.import_rule().unwrap().clone(),
media: list
- .import_media_for(list.identity_for(rule.local_identity))
- .unwrap_or_else(|| MediaList::new(rule.media_list.as_ref().unwrap().clone())),
- scope: rule.scope_selectors.clone(),
+ .import_media_for(list.identity_for(u64::from(rule.local_identity)))
+ .unwrap_or_else(|| MediaList::new(rule.media_list().unwrap().clone())),
+ scope: rule.scope_selectors().cloned(),
},
NativeRuleType::Media => RulePayload::Media {
- list: MediaList::new(rule.media_list.as_ref().unwrap().clone()),
+ list: MediaList::new(rule.media_list().unwrap().clone()),
},
- NativeRuleType::Supports => RulePayload::Supports(rule.supports_condition.as_ref().unwrap().clone()),
- NativeRuleType::Container => RulePayload::Container(rule.container_conditions.as_ref().unwrap().clone()),
- NativeRuleType::Scope => RulePayload::Scope(rule.scope_selectors.as_ref().unwrap().clone()),
+ NativeRuleType::Supports => RulePayload::Supports(rule.supports_condition().unwrap().clone()),
+ NativeRuleType::Container => RulePayload::Container(rule.container_conditions().unwrap().clone()),
+ NativeRuleType::Scope => RulePayload::Scope(RefCell::new(rule.scope_selectors().unwrap().clone())),
NativeRuleType::LayerBlock | NativeRuleType::LayerStatement => {
- RulePayload::LayerNames(rule.layer_names.as_ref().unwrap().clone())
+ RulePayload::LayerNames(rule.layer_names().unwrap().clone())
}
- NativeRuleType::Function => RulePayload::Function(rule.function_signature.as_ref().unwrap().clone()),
+ NativeRuleType::Function => RulePayload::Function(rule.function_signature().unwrap().clone()),
NativeRuleType::Page => RulePayload::Page {
- selectors: RefCell::new(rule.page_selector_list.as_ref().unwrap().clone()),
- descriptors: Box::new(FfiDescriptorBlock::new(rule.descriptor_block.as_ref().unwrap().clone())),
+ selectors: RefCell::new(rule.page_selector_list().unwrap().clone()),
+ descriptors: Box::new(FfiDescriptorBlock::new(rule.descriptor_block().unwrap().clone())),
+ },
+ NativeRuleType::Margin => RulePayload::Margin {
+ name: rule.margin_name().unwrap().clone(),
+ declarations: Box::new(DeclarationBlock::new(rule.declaration_block().unwrap().clone())),
},
- NativeRuleType::Margin => {
- let name: Vec<u16> = self.values[rule.name_offset..rule.name_offset + rule.name_length]
- .iter()
- .map(|&unit| {
- if (u16::from(b'A')..=u16::from(b'Z')).contains(&unit) {
- unit + u16::from(b'a' - b'A')
- } else {
- unit
- }
- })
- .collect();
- RulePayload::Margin {
- name: CssString::from_utf16(&name),
- declarations: Box::new(DeclarationBlock::new(rule.declaration_block.as_ref().unwrap().clone())),
- }
- }
NativeRuleType::PositionTry => RulePayload::PositionTry {
- name: rule.position_try_name.as_ref().unwrap().clone(),
- declarations: Box::new(DeclarationBlock::new(rule.declaration_block.as_ref().unwrap().clone())),
+ name: rule.position_try_name().unwrap().clone(),
+ declarations: Box::new(DeclarationBlock::new(rule.declaration_block().unwrap().clone())),
},
NativeRuleType::FontFace => RulePayload::FontFace(Box::new(FfiDescriptorBlock::new(
- rule.descriptor_block.as_ref().unwrap().clone(),
+ rule.descriptor_block().unwrap().clone(),
))),
NativeRuleType::FontFeatureValues => RulePayload::FontFeatureValues(Box::new(FontFeatureValuesRule::new(
- rule.font_feature_values.as_ref().unwrap().clone(),
+ rule.font_feature_values().unwrap().clone(),
))),
- NativeRuleType::Keyframes => {
- RulePayload::Keyframes(RefCell::new(rule.keyframes_name.as_ref().unwrap().clone()))
+ NativeRuleType::Keyframes => RulePayload::Keyframes(RefCell::new(rule.keyframes_name().unwrap().clone())),
+ NativeRuleType::Namespace => RulePayload::Namespace(rule.namespace_rule().unwrap().clone()),
+ NativeRuleType::CounterStyle => {
+ RulePayload::CounterStyle(Box::new(FfiCounterStyle::new(rule.counter_style().unwrap().clone())))
}
- NativeRuleType::Namespace => RulePayload::Namespace(rule.namespace_rule.as_ref().unwrap().clone()),
- NativeRuleType::CounterStyle => RulePayload::CounterStyle(Box::new(FfiCounterStyle::new(
- rule.counter_style.as_ref().unwrap().clone(),
- ))),
- NativeRuleType::Property => RulePayload::Property(rule.property_rule.as_ref().unwrap().clone()),
+ NativeRuleType::Property => RulePayload::Property(rule.property_rule().unwrap().clone()),
NativeRuleType::NestedDeclarations | NativeRuleType::FunctionDeclarations => unreachable!(),
};
Some(NativeRule::with_identity(
- list.identity_for(rule.local_identity),
+ list.identity_for(u64::from(rule.local_identity)),
kind,
payload,
child_rules,
@@ -2497,6 +2734,12 @@ pub extern "C" fn rust_css_syntax_visit_diagnostics(
}
}
+/// Whether the parse reported nothing: no diagnostics and no rejected declarations.
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_css_syntax_parse_is_clean(parse: &ParsedStyleSheet) -> bool {
+ parse.diagnostics.is_empty() && parse.declaration_errors.is_empty()
+}
+
#[unsafe(no_mangle)]
pub extern "C" fn rust_css_syntax_visit_declaration_errors(
parse: &ParsedStyleSheet,
@@ -2506,7 +2749,7 @@ pub extern "C" fn rust_css_syntax_visit_declaration_errors(
callback(
parse.values.as_ptr(),
parse.values.len(),
- &parse.declarations[index].ffi_view(),
+ &parse.declarations[index as usize].ffi_view(),
);
}
}
@@ -2522,7 +2765,7 @@ pub extern "C" fn rust_css_syntax_visit_root_declarations(
context,
parse.values.as_ptr(),
parse.values.len(),
- &parse.declarations[index].ffi_view(),
+ &parse.declarations[index as usize].ffi_view(),
);
}
}
@@ -2542,7 +2785,11 @@ impl ParsedDeclaration {
property_id: self.property_id,
descriptor_id: self.descriptor_id,
rejection: self.rejection,
- parsed_value: self.parsed_value.as_ref().map_or(std::ptr::null(), Arc::as_ptr).cast(),
+ parsed_value: self
+ .parsed_value
+ .as_ref()
+ .map_or(std::ptr::null(), StyleValueArc::as_ptr)
+ .cast(),
}
}
}
@@ -2600,10 +2847,11 @@ fn collect_descriptors<'a>(
};
let longhands = descriptor_longhands(at_rule, descriptor.id);
if !longhands.is_empty()
- && let StyleValueData::Shorthand {
- sub_properties, values, ..
- } = descriptor.value.as_ref()
+ && let StyleValueData::Shorthand(shorthand_payload) = descriptor.value.as_ref()
{
+ let ShorthandPayload {
+ sub_properties, values, ..
+ } = &**shorthand_payload;
for longhand in longhands {
let Some(index) = sub_properties
.as_slice()
@@ -2654,8 +2902,6 @@ fn parse_font_feature_values(declaration: &Declaration, maximum_value_count: usi
(!values.is_empty() && values.len() <= maximum_value_count).then_some(values)
}
-// NB: Mirrors the rule structural validation and top-level ordering that this series removed from
-// Libraries/LibWeb/CSS/Parser/RuleParsing.cpp and Libraries/LibWeb/CSS/Parser/Parser.cpp.
fn structural_validation_code(
rule: &Rule,
rule_kind: ParsedRuleKind,
@@ -2868,10 +3114,10 @@ impl<'a> SyntaxParseBuilder<'a> {
}
}
ParsedRuleChild::Rule(rule) => {
- if rule.is_qualified && rule.selector_list.is_none() {
+ if rule.is_qualified && rule.selector_list().is_none() {
return;
}
- for child in &rule.children {
+ for child in rule.children() {
visit_item(sheet, child, errors);
}
}
@@ -2879,7 +3125,7 @@ impl<'a> SyntaxParseBuilder<'a> {
}
fn visit_rule(sheet: &SyntaxParseBuilder<'_>, rule: &ParsedRule, errors: &mut Vec<usize>) {
match rule.rule_kind {
- ParsedRuleKind::Qualified if rule.selector_list.is_some() => {}
+ ParsedRuleKind::Qualified if rule.selector_list().is_some() => {}
ParsedRuleKind::Container
| ParsedRuleKind::Media
| ParsedRuleKind::Supports
@@ -2889,7 +3135,7 @@ impl<'a> SyntaxParseBuilder<'a> {
| ParsedRuleKind::Page => {}
_ => return,
}
- for child in &rule.children {
+ for child in rule.children() {
match child {
ParsedRuleChild::Declarations(_) => visit_item(sheet, child, errors),
ParsedRuleChild::Rule(rule) => visit_rule(sheet, rule, errors),
@@ -2907,6 +3153,8 @@ impl<'a> SyntaxParseBuilder<'a> {
}
fn finish(self) -> ParsedStyleSheet {
+ // NB: Every handle to the sheet's selectors reads them once the arena is frozen.
+ drop(self.selectors.take());
let mut declaration_errors = self.collect_declaration_errors().into_vec();
let mut root_declarations = Vec::new();
for item in &self.items {
@@ -2919,9 +3167,21 @@ impl<'a> SyntaxParseBuilder<'a> {
new_indices[index] = 0;
}
let mut declarations = Vec::new();
- for (index, declaration) in self.declarations.into_iter().enumerate() {
+ let mut values = self.values;
+ for (index, mut declaration) in self.declarations.into_iter().enumerate() {
if new_indices[index] != usize::MAX {
new_indices[index] = declarations.len();
+ // NB: A kept declaration's text moves beside the rest of the text the parse keeps.
+ for (offset, length) in [
+ (&mut declaration.name_offset, declaration.name_length),
+ (&mut declaration.value_source_offset, declaration.value_source_length),
+ ] {
+ if length != 0 {
+ let start = values.len();
+ values.extend_from_slice(&self.declaration_text[*offset..*offset + length]);
+ *offset = start;
+ }
+ }
declarations.push(declaration);
}
}
@@ -2929,39 +3189,47 @@ impl<'a> SyntaxParseBuilder<'a> {
*index = new_indices[*index];
assert_ne!(*index, usize::MAX, "published declaration metadata must be retained");
}
+ let narrow = |indices: Vec<usize>| -> Box<[u32]> {
+ indices
+ .into_iter()
+ .map(|index| u32::try_from(index).expect("style sheet has too many declarations"))
+ .collect()
+ };
let mut parsed = ParsedStyleSheet {
identity_count: self.identity_count,
+ source_text: RetainedString::from_ascii(String::new()),
cache_metadata: None,
declarations_kind: self.declarations_kind,
- values: self.values.into_boxed_slice(),
+ values: values.into_boxed_slice(),
declarations: declarations.into_boxed_slice(),
- root_declarations: root_declarations.into_boxed_slice(),
+ root_declarations: narrow(root_declarations),
rules: self.rules.into_boxed_slice(),
items: self.items.into_boxed_slice(),
native_roots: Box::default(),
media_holding_roots: Box::default(),
diagnostics: self.diagnostics.into_boxed_slice(),
- declaration_errors: declaration_errors.into_boxed_slice(),
+ declaration_errors: narrow(declaration_errors),
};
parsed.native_roots = if parsed.items.is_empty() {
parsed
.rules
.iter()
.enumerate()
- .filter_map(|(index, rule)| rule.native_type().map(|_| index))
+ .filter_map(|(index, rule)| rule.native_type().map(|_| shared_rules::narrow_index(index)))
.collect()
} else {
shared_rules::native_child_indices(&parsed.items, None)
};
parsed.media_holding_roots = (0..parsed.native_roots.len())
.filter(|&position| {
- let index = parsed.native_roots[position];
+ let index = parsed.native_roots[position] as usize;
if parsed.items.is_empty() {
parsed.rules[index].holds_media_rules()
} else {
matches!(&parsed.items[index], ParsedRuleChild::Rule(rule) if rule.holds_media_rules())
}
})
+ .map(shared_rules::narrow_index)
.collect();
parsed
}
@@ -2979,6 +3247,7 @@ impl<'a> SyntaxParseBuilder<'a> {
.collect();
Self {
values: Vec::new(),
+ declaration_text: Vec::new(),
declarations_kind: NestedDeclarationsKind::Style,
declarations: Vec::new(),
declaration_ranges: Vec::new(),
@@ -2993,6 +3262,15 @@ impl<'a> SyntaxParseBuilder<'a> {
parse_context,
preserve_property_source_text,
dedup: DeclarationDedup::default(),
+ selectors: RefCell::new({
+ let mut selectors = crate::css::selector_arena::SheetSelectorsBuilder::default();
+ if let Some(declared) = parse_context.and_then(|context| context.declared_namespaces) {
+ selectors.declare_namespaces(declared.declarations());
+ }
+ selectors
+ }),
+ nesting: Cell::new(None),
+ parent: Cell::new(None),
}
}
@@ -3054,12 +3332,22 @@ impl<'a> SyntaxParseBuilder<'a> {
value.map_or((usize::MAX, 0), |value| self.append_value(value))
}
+ fn append_declaration_text(&mut self, text: &[u16]) -> (usize, usize) {
+ let offset = self.declaration_text.len();
+ self.declaration_text.extend_from_slice(text);
+ (offset, text.len())
+ }
+
+ fn declaration_name(&self, declaration: &ParsedDeclaration) -> &[u16] {
+ &self.declaration_text[declaration.name_offset..declaration.name_offset + declaration.name_length]
+ }
+
fn append_declaration(
&mut self,
declaration: &Declaration,
font_feature_maximum_value_count: Option<usize>,
) -> usize {
- let (name_offset, name_length) = self.append_value(declaration.name.as_ref());
+ let (name_offset, name_length) = self.append_declaration_text(declaration.name.as_ref());
let value_source = component_list_source(&declaration.value);
let shareable = declaration.is_property && !value_may_not_be_shared(&declaration.value);
let value_key = shareable.then(|| {
@@ -3075,7 +3363,21 @@ impl<'a> SyntaxParseBuilder<'a> {
let (property_id, descriptor_id, rejection, parsed_value) = match shared_value {
Some(value) => value,
None => {
- let value = self.parse_declaration_value(declaration, value_source.as_ref());
+ let mut value = self.parse_declaration_value(declaration, value_source.as_ref());
+ // NB: A value taking part in a substitution keeps its own: it is resolved for the
+ // property declaring it, and the longhands a shorthand awaiting substitution
+ // expands to name it by identity.
+ if shareable
+ && let Some(parsed) = &mut value.3
+ && !matches!(
+ **parsed,
+ StyleValueData::Unresolved(_)
+ | StyleValueData::PendingSubstitution { .. }
+ | StyleValueData::Shorthand(_)
+ )
+ {
+ *parsed = self.dedup.intern_value(parsed);
+ }
if let Some((hash, key)) = &value_key {
self.dedup
.values
@@ -3107,7 +3409,7 @@ impl<'a> SyntaxParseBuilder<'a> {
};
let needs_value_text = self.preserve_property_source_text || rejection == FfiDeclarationRejection::InvalidValue;
let (value_source_offset, value_source_length) = if needs_value_text {
- self.append_value(value_source.as_ref())
+ self.append_declaration_text(value_source.as_ref())
} else {
(0, 0)
};
@@ -3136,7 +3438,7 @@ impl<'a> SyntaxParseBuilder<'a> {
&mut self,
declaration: &Declaration,
source_utf16: &[u16],
- ) -> (u16, u8, FfiDeclarationRejection, Option<Arc<StyleValueData>>) {
+ ) -> (u16, u8, FfiDeclarationRejection, Option<StyleValueArc>) {
let Some(parse_context) = self.parse_context else {
return (u16::MAX, u8::MAX, FfiDeclarationRejection::None, None);
};
@@ -3194,7 +3496,7 @@ impl<'a> SyntaxParseBuilder<'a> {
}
fn append_collected_declaration(&mut self, descriptor: &DescriptorData) {
- let (name_offset, name_length) = self.append_value(descriptor.name.units());
+ let (name_offset, name_length) = self.append_declaration_text(descriptor.name.units());
self.declarations.push(ParsedDeclaration {
name_offset,
name_length,
@@ -3232,7 +3534,9 @@ impl<'a> SyntaxParseBuilder<'a> {
return (
start,
self.declarations.len() - start,
- Some(Arc::new(DescriptorBlockData { descriptors })),
+ Some(Arc::new(DescriptorBlockData {
+ descriptors: descriptors.into_iter().collect(),
+ })),
);
}
for declaration in declarations {
@@ -3254,7 +3558,7 @@ impl<'a> SyntaxParseBuilder<'a> {
fn append_declaration_block(
&self,
- block: &mut DeclarationBlockData,
+ block: &mut DeclarationBlockBuilder,
start: usize,
count: usize,
ignore_important: bool,
@@ -3278,8 +3582,15 @@ impl<'a> SyntaxParseBuilder<'a> {
value: value.clone(),
};
if declaration.property_id == property_id::CUSTOM {
- let name = &self.values[declaration.name_offset..declaration.name_offset + declaration.name_length];
- block.set_custom_property(CssString::from_utf16(name), property);
+ let name = self.declaration_name(declaration);
+ let name = self
+ .dedup
+ .custom_property_names
+ .borrow_mut()
+ .entry(name.into())
+ .or_insert_with(|| CssString::from_utf16(name))
+ .clone();
+ block.set_custom_property(name, property);
} else {
block.append_in_specified_order(property);
}
@@ -3321,7 +3632,7 @@ impl<'a> SyntaxParseBuilder<'a> {
RuleOrDeclarations::Declarations(declarations) => declarations,
};
let (start, count, descriptor_block) = self.append_declarations(declarations, font_feature_maximum_value_count);
- let mut block = DeclarationBlockData::default();
+ let mut block = DeclarationBlockBuilder::default();
self.append_declaration_block(
&mut block,
start,
@@ -3336,8 +3647,7 @@ impl<'a> SyntaxParseBuilder<'a> {
)
}),
);
- block.compact();
- let declaration_block = Some(Arc::new(block));
+ let declaration_block = Some(block.finish());
let local_identity = self.next_identity();
let identity_index = usize::try_from(local_identity).expect("parsed declaration identity overflow");
self.declaration_ranges
@@ -3345,14 +3655,15 @@ impl<'a> SyntaxParseBuilder<'a> {
self.declaration_ranges[identity_index] = start..start + count;
let source_position = (count != 0).then(|| {
let first = &self.declarations[start];
- (first.start_line, first.start_column)
+ let narrow = |value: usize| u32::try_from(value).expect("style sheet text exceeds u32");
+ (narrow(first.start_line), narrow(first.start_column))
});
- ParsedRuleChild::Declarations(ParsedDeclarationList {
+ ParsedRuleChild::Declarations(Box::new(ParsedDeclarationList {
local_identity,
source_position,
declaration_block,
descriptor_block,
- })
+ }))
}
fn parse_selector_list(
@@ -3360,7 +3671,8 @@ impl<'a> SyntaxParseBuilder<'a> {
values: &[ComponentValue],
selector_type: SelectorType,
nesting_parent: StyleNestingParent,
- ) -> Option<Arc<RustParsedSelectorList>> {
+ nesting: NestingTarget,
+ ) -> Option<(Arc<RustParsedSelectorList>, Option<RuleOrdinal>)> {
let declared_namespaces = self
.declared_namespaces
.iter()
@@ -3368,24 +3680,39 @@ impl<'a> SyntaxParseBuilder<'a> {
.collect::<Vec<_>>();
let selector_list =
parse_selector_list_from_component_values(values, &declared_namespaces, selector_type).ok()?;
- Some(Arc::new(selector_list.adapt_for_nesting(nesting_parent)))
+ let (list, ordinal) = selector_list
+ .adapt_for_nesting(nesting_parent)
+ .into_rule_list_in(&mut self.selectors.borrow_mut(), nesting);
+ Some((Arc::new(list), ordinal))
}
fn rule_descriptors(children: &[ParsedRuleChild], kind: ParsedRuleKind) -> Option<Arc<DescriptorBlockData>> {
- let mut data: Option<Arc<DescriptorBlockData>> = None;
+ // NB: A single list's block is shared as is; the descriptors are merged only once a second list appends.
+ let mut first: Option<&Arc<DescriptorBlockData>> = None;
+ let mut merged: Option<Vec<DescriptorData>> = None;
for child in children {
let ParsedRuleChild::Declarations(child) = child else {
continue;
};
let Some(block) = &child.descriptor_block else { continue };
- if let Some(data) = &mut data {
- for descriptor in &block.descriptors {
- append_collected_descriptor(&mut Arc::make_mut(data).descriptors, descriptor.clone());
+ let merged = match (&mut merged, first) {
+ (Some(merged), _) => merged,
+ (None, Some(first)) => merged.insert(first.descriptors.to_vec()),
+ (None, None) => {
+ first = Some(block);
+ continue;
}
- } else {
- data = Some(block.clone());
+ };
+ for descriptor in &block.descriptors {
+ append_collected_descriptor(merged, descriptor.clone());
}
}
+ let data = match merged {
+ Some(merged) => Some(Arc::new(DescriptorBlockData {
+ descriptors: merged.into_iter().collect(),
+ })),
+ None => first.cloned(),
+ };
if data.as_ref().is_none_or(|data| data.descriptors.is_empty())
&& !matches!(
kind,
@@ -3419,27 +3746,50 @@ impl<'a> SyntaxParseBuilder<'a> {
rule.source_position,
),
};
- let (name_offset, name_length) = self.append_value(name);
let prelude_source = component_list_source(prelude);
let font_feature_maximum_value_count = match rule {
Rule::At(rule) => font_feature_values_rule(rule.name.as_ref()).map(|(_, maximum)| maximum),
Rule::Qualified(_) => None,
};
let (declarations_start, declaration_count, _) = self.append_declarations(declarations, None);
+ // NB: A rule's selectors go into the sheet's arena before those of the rules nested in it,
+ // whose `&` names them by their ordinal there.
+ let outer_nesting = self.nesting.get().unwrap_or(match rule_nesting_parent(rule) {
+ StyleNestingParent::None => NestingTarget::Root,
+ StyleNestingParent::Scope => NestingTarget::Scope,
+ StyleNestingParent::Style => NestingTarget::Unbound,
+ });
+ let (selector_list, rule_ordinal) = match rule {
+ Rule::Qualified(rule) if rule.prelude_is_selector => self
+ .parse_selector_list(
+ &rule.prelude,
+ if rule.nesting_parent != StyleNestingParent::None {
+ SelectorType::Relative
+ } else {
+ SelectorType::Standalone
+ },
+ rule.nesting_parent,
+ outer_nesting,
+ )
+ .map_or((None, None), |(list, ordinal)| (Some(list), ordinal)),
+ _ => (None, None),
+ };
+ // NB: A `&` in a `<scope-start>` names the rule the `@scope` is directly in.
+ let outer_parent = self.parent.get().unwrap_or(outer_nesting);
+ let (inner_nesting, inner_parent) = match rule {
+ Rule::Qualified(rule) if rule.prelude_is_selector => {
+ let nesting = rule_ordinal.map_or(NestingTarget::Unbound, NestingTarget::Rule);
+ (nesting, nesting)
+ }
+ Rule::At(_) if original_rule_kind == ParsedRuleKind::Scope => (NestingTarget::Scope, NestingTarget::Scope),
+ _ => (outer_nesting, NestingTarget::Root),
+ };
+ self.nesting.set(Some(inner_nesting));
+ self.parent.set(Some(inner_parent));
let children = self.append_items(children, font_feature_maximum_value_count);
+ self.nesting.set(Some(outer_nesting));
+ self.parent.set(Some(outer_parent));
let descriptor_block = Self::rule_descriptors(&children, original_rule_kind);
- let selector_list = match rule {
- Rule::Qualified(rule) if rule.prelude_is_selector => self.parse_selector_list(
- &rule.prelude,
- if rule.nesting_parent != StyleNestingParent::None {
- SelectorType::Relative
- } else {
- SelectorType::Standalone
- },
- rule.nesting_parent,
- ),
- _ => None,
- };
let parse_context = self.parse_context;
let declared_namespaces = self
.declared_namespaces
@@ -3524,12 +3874,10 @@ impl<'a> SyntaxParseBuilder<'a> {
let ParsedRuleChild::Rule(child) = child else {
continue;
};
- if child.rule_kind != ParsedRuleKind::FontFeatureValuesRule {
+ let ParsedRulePayload::FontFeatureValuesRule(kind) = child.payload else {
continue;
- }
- let name = &self.values[child.name_offset..child.name_offset + child.name_length];
- let (kind, _) = font_feature_values_rule(name).unwrap();
- for item in &child.children {
+ };
+ for item in child.children() {
let ParsedRuleChild::Declarations(item) = item else {
continue;
};
@@ -3539,8 +3887,7 @@ impl<'a> SyntaxParseBuilder<'a> {
if declaration.font_feature_value_count == 0 {
continue;
}
- let name = &self.values
- [declaration.name_offset..declaration.name_offset + declaration.name_length];
+ let name = self.declaration_name(declaration);
let values = &self.font_feature_values[declaration.font_feature_values_start
..declaration.font_feature_values_start + declaration.font_feature_value_count];
data.set(kind, name, values.to_vec());
@@ -3550,9 +3897,15 @@ impl<'a> SyntaxParseBuilder<'a> {
font_feature_values = Some(Arc::new(data));
}
ParsedRulePrelude::Scope { start, end } => {
+ // NB: The prelude goes into the sheet's arena, where a `&` in its start names what
+ // encloses the `@scope`.
+ let mut selectors = self.selectors.borrow_mut();
+ let mut repack = |list: RustParsedSelectorList, nesting| RustParsedSelectorList {
+ selectors: selectors.push_copy(&list.selectors, nesting),
+ };
scope_selectors = Some(Arc::new(ScopeSelectors {
- start: start.map(Arc::new),
- end: end.map(Arc::new),
+ start: start.map(|start| Arc::new(repack(start, outer_parent))),
+ end: end.map(|end| Arc::new(repack(end, NestingTarget::Root))),
}));
}
ParsedRulePrelude::Import(import) => {
@@ -3570,9 +3923,7 @@ impl<'a> SyntaxParseBuilder<'a> {
.map(|supports| expression_query_handle(supports, QueryKind::Supports)),
scope: scope_selectors.clone(),
}));
- media_list = Some(Arc::new(MediaListData {
- queries: import.media_queries.into_iter().map(media_query_handle).collect(),
- }));
+ media_list = Some(Arc::new(MediaListData::from_queries(import.media_queries)));
}
ParsedRulePrelude::Function {
name,
@@ -3608,9 +3959,7 @@ impl<'a> SyntaxParseBuilder<'a> {
}));
}
ParsedRulePrelude::MediaQueries(queries) => {
- media_list = Some(Arc::new(MediaListData {
- queries: queries.into_iter().map(media_query_handle).collect(),
- }));
+ media_list = Some(Arc::new(MediaListData::from_queries(queries)));
}
ParsedRulePrelude::SupportsCondition(expression) => {
supports_condition = Some(expression_query_handle(expression, QueryKind::Supports));
@@ -3641,9 +3990,9 @@ impl<'a> SyntaxParseBuilder<'a> {
.as_ref()
.and_then(|(hash, key)| self.dedup.find(&self.dedup.blocks, *hash, key))
{
- Some(Arc::clone(shared))
+ Some(shared.clone())
} else {
- let mut block = DeclarationBlockData::default();
+ let mut block = DeclarationBlockBuilder::default();
self.append_declaration_block(
&mut block,
declarations_start,
@@ -3658,14 +4007,9 @@ impl<'a> SyntaxParseBuilder<'a> {
}
}
}
- block.compact();
- let block = Arc::new(block);
+ let block = block.finish();
if let Some((hash, key)) = block_key {
- self.dedup
- .blocks
- .entry(hash)
- .or_default()
- .push((key, Arc::clone(&block)));
+ self.dedup.blocks.entry(hash).or_default().push((key, block.clone()));
}
Some(block)
}
@@ -3706,36 +4050,84 @@ impl<'a> SyntaxParseBuilder<'a> {
} else {
shared_rules::native_child_indices(&children, Some(rule_kind))
};
+ // NB: A rule's prelude, or its kind, gives it one payload at most.
+ let payload = if let Some(keyframe) = keyframe {
+ ParsedRulePayload::Keyframe(keyframe)
+ } else if is_qualified {
+ ParsedRulePayload::Style {
+ selector_list,
+ declaration_block: declaration_block.unwrap(),
+ }
+ } else if let Some(import_rule) = import_rule {
+ ParsedRulePayload::Import {
+ import_rule,
+ media_list: media_list.unwrap(),
+ }
+ } else if let Some(media_list) = media_list {
+ ParsedRulePayload::Media(media_list)
+ } else if let Some(condition) = supports_condition {
+ ParsedRulePayload::Supports(condition)
+ } else if let Some(conditions) = container_conditions {
+ ParsedRulePayload::Container(conditions)
+ } else if let Some(selectors) = scope_selectors {
+ ParsedRulePayload::Scope(selectors)
+ } else if let Some(names) = layer_names {
+ ParsedRulePayload::Layer(names)
+ } else if let Some(selectors) = page_selector_list {
+ ParsedRulePayload::Page {
+ selectors,
+ descriptors: descriptor_block.expect("a page rule has descriptors"),
+ }
+ } else if rule_kind == ParsedRuleKind::FontFace {
+ ParsedRulePayload::FontFace(descriptor_block.expect("a font-face rule has descriptors"))
+ } else if rule_kind == ParsedRuleKind::FontFeatureValuesRule {
+ ParsedRulePayload::FontFeatureValuesRule(font_feature_values_rule(name).unwrap().0)
+ } else if let Some(values) = font_feature_values {
+ ParsedRulePayload::FontFeatureValues(values)
+ } else if let Some(name) = keyframes_name {
+ ParsedRulePayload::Keyframes(name)
+ } else if let Some(name) = position_try_name {
+ ParsedRulePayload::PositionTry {
+ name,
+ declaration_block: declaration_block.unwrap(),
+ }
+ } else if let Some(declaration_block) = declaration_block {
+ ParsedRulePayload::Margin {
+ name: CssString::from_utf16(
+ &name
+ .iter()
+ .map(|&unit| crate::css::ffi_support::ascii_lowercase(unit))
+ .collect::<Vec<_>>(),
+ ),
+ declaration_block,
+ }
+ } else if let Some(counter_style) = counter_style {
+ ParsedRulePayload::CounterStyle(counter_style)
+ } else if let Some(namespace) = namespace_rule {
+ ParsedRulePayload::Namespace(namespace)
+ } else if let Some(property) = property_rule {
+ ParsedRulePayload::Property(property)
+ } else if let Some(signature) = function_signature {
+ ParsedRulePayload::Function(signature)
+ } else {
+ ParsedRulePayload::None
+ };
+ let narrow = |value: usize| u32::try_from(value).expect("style sheet text exceeds u32");
Arc::new(ParsedRule {
- local_identity: self.next_identity(),
+ local_identity: u32::try_from(self.next_identity()).expect("style sheet has too many rules"),
is_qualified,
rule_kind,
- name_offset,
- name_length,
- declaration_block,
- children,
- native_children,
has_block,
has_source_position: source_position.is_some(),
- start_line: source_position.map_or(0, |position| position.line),
- start_column: source_position.map_or(0, |position| position.column),
- page_selector_list,
- import_rule,
- supports_condition,
- selector_list,
- descriptor_block,
- layer_names,
- container_conditions,
- font_feature_values,
- keyframe,
- keyframes_name,
- position_try_name,
- scope_selectors,
- media_list,
- counter_style,
- namespace_rule,
- property_rule,
- function_signature,
+ start_line: narrow(source_position.map_or(0, |position| position.line)),
+ start_column: narrow(source_position.map_or(0, |position| position.column)),
+ children: (!children.is_empty()).then(|| {
+ Box::new(ParsedRuleChildren {
+ children,
+ native_children,
+ })
+ }),
+ payload,
})
}
@@ -3747,9 +4139,7 @@ impl<'a> SyntaxParseBuilder<'a> {
}
fn append_root(&mut self, rule: &Rule) {
- // NB: Mirrors the top-level rule ordering that this series removed from
- // Libraries/LibWeb/CSS/Parser/Parser.cpp.
- // Invalid rules do not close either ordering window, and statement @layer rules do not
+ // NB: Invalid rules do not close either ordering window, and statement @layer rules do not
// close the import or namespace window.
let mut parsed = self.append_rule(rule);
let rule_kind = parsed.rule_kind;
@@ -3772,7 +4162,11 @@ impl<'a> SyntaxParseBuilder<'a> {
}
ParsedRuleKind::Namespace if self.namespace_rules_valid => {
self.import_rules_valid = false;
- let prefix = parsed.namespace_rule.as_ref().unwrap().prefix.units();
+ let namespace = parsed.namespace_rule().unwrap();
+ self.selectors
+ .borrow_mut()
+ .declare_namespace(namespace.prefix.units(), namespace.uri.units());
+ let prefix = namespace.prefix.units();
if !self
.declared_namespaces
.iter()
@@ -3839,17 +4233,27 @@ pub(crate) fn parse_shared_stylesheet(
parse_context: Option<&ParseContext<'_>>,
) -> Arc<ParsedStyleSheet> {
parse_with_cache(source, parse_context, || {
- let mut parser = Parser::streaming(source);
- let mut parse = SyntaxParseBuilder::new(parse_context, false);
- while let Some(rule) = parser.consume_next_stylesheet_rule() {
- parse.append_root(&rule);
- }
- // As in every other parse, the tokens' own diagnostics come ahead of the rules'.
- parse.diagnostics.splice(0..0, parser.tokens.diagnostics);
- parse.finish()
+ parse_stylesheet_uncached(source, parse_context)
})
}
+/// Parses a style sheet without asking the process's parse cache, or offering it the result.
+pub(crate) fn parse_stylesheet_uncached(
+ source: TokenizerInput<'_>,
+ parse_context: Option<&ParseContext<'_>>,
+) -> ParsedStyleSheet {
+ let mut parser = Parser::streaming(source);
+ let mut parse = SyntaxParseBuilder::new(parse_context, false);
+ while let Some(rule) = parser.consume_next_stylesheet_rule() {
+ parse.append_root(&rule);
+ }
+ // As in every other parse, the tokens' own diagnostics come ahead of the rules'.
+ parse.diagnostics.splice(0..0, parser.tokens.diagnostics);
+ let mut parsed = parse.finish();
+ parsed.source_text = RetainedString::from_text(source);
+ parsed
+}
+
/// Every rule context, at the index of its discriminant.
const RULE_CONTEXTS: [RuleContext; RuleContext::AtPositionTry as usize + 1] = {
use RuleContext::*;
@@ -4035,9 +4439,8 @@ pub extern "C" fn rust_css_syntax_parse_descriptor_block(
// 2. If parsed declaration is not null, append it to parsed declarations.
// NB: Declaration-list items already own their parsed descriptors.
if let Some(descriptors) = &mut descriptors {
- Arc::make_mut(descriptors)
- .descriptors
- .extend(block.descriptors.iter().cloned());
+ let data = Arc::make_mut(descriptors);
+ data.descriptors = data.descriptors.iter().chain(&block.descriptors).cloned().collect();
} else {
descriptors = Some(block.clone());
}
@@ -4199,7 +4602,7 @@ mod tests {
.declaration_errors
.iter()
.map(|&index| {
- let declaration = &parsed.declarations[index];
+ let declaration = &parsed.declarations[index as usize];
parsed.values[declaration.name_offset..declaration.name_offset + declaration.name_length].to_vec()
})
.collect();
@@ -4273,42 +4676,54 @@ mod tests {
let values = parse
.rules
.iter()
- .filter_map(|rule| rule.declaration_block.as_ref())
- .flat_map(|block| block.properties.iter().map(|property| &property.value))
+ .filter_map(|rule| rule.declaration_block())
+ .flat_map(|block| block.properties().values())
.chain(
parse
.rules
.iter()
- .filter_map(|rule| rule.property_rule.as_ref()?.initial_value.as_ref()),
+ .filter_map(|rule| rule.property_rule()?.initial_value.as_ref()),
)
.filter(|value| matches!(value.as_ref(), crate::css::style_value::StyleValueData::Length { .. }))
- .map(std::sync::Arc::downgrade)
+ .cloned()
.collect::<Vec<_>>();
assert!(values.len() >= 2);
let syntaxes = parse
.rules
.iter()
- .filter_map(|rule| rule.property_rule.as_ref().map(|rule| &rule.syntax))
+ .filter_map(|rule| rule.property_rule().map(|rule| &rule.syntax))
.map(std::sync::Arc::downgrade)
.collect::<Vec<_>>();
assert!(!syntaxes.is_empty());
drop(parse);
- assert!(values.iter().all(|value| value.upgrade().is_none()));
+ assert!(
+ values
+ .iter()
+ .all(|value| crate::css::style_value_arc::StyleValueArc::strong_count(value) == 1)
+ );
assert!(syntaxes.iter().all(|syntax| syntax.upgrade().is_none()));
}
#[test]
fn consumers_can_retain_the_same_parsed_value_independently() {
let parse = parse_test_stylesheet(b"a { width: 13.25px }");
- let pointer = std::sync::Arc::as_ptr(&parse.rules[0].declaration_block.as_ref().unwrap().properties[0].value);
+ let pointer = crate::css::style_value_arc::StyleValueArc::as_ptr(
+ &parse.rules[0]
+ .declaration_block()
+ .unwrap()
+ .properties()
+ .get(0)
+ .unwrap()
+ .value,
+ );
let retain = || unsafe {
- std::sync::Arc::increment_strong_count(pointer);
- std::sync::Arc::from_raw(pointer)
+ crate::css::style_value_arc::StyleValueArc::increment_strong_count(pointer);
+ crate::css::style_value_arc::StyleValueArc::from_raw(pointer)
};
let first = retain();
let second = retain();
drop(parse);
- assert!(std::sync::Arc::ptr_eq(&first, &second));
+ assert!(crate::css::style_value_arc::StyleValueArc::ptr_eq(&first, &second));
drop(first);
assert!(matches!(
*second,
@@ -4405,11 +4820,11 @@ mod tests {
);
let parse = parse_test_stylesheet(b"@media all { @styleset {} } @font-feature-values Family { @styleset {} }");
- let ParsedRuleChild::Rule(media_child) = &parse.rules[0].children[0] else {
+ let ParsedRuleChild::Rule(media_child) = &parse.rules[0].children()[0] else {
panic!("expected rule")
};
assert_eq!(media_child.rule_kind, ParsedRuleKind::Invalid);
- let ParsedRuleChild::Rule(font_feature_values_child) = &parse.rules[1].children[0] else {
+ let ParsedRuleChild::Rule(font_feature_values_child) = &parse.rules[1].children()[0] else {
panic!("expected rule")
};
assert_eq!(
@@ -4424,7 +4839,7 @@ mod tests {
let layer_rules = parse
.rules
.iter()
- .flat_map(|rule| rule.children.iter())
+ .flat_map(|rule| rule.children().iter())
.filter_map(|child| match child {
ParsedRuleChild::Rule(rule) => Some(rule),
_ => None,
@@ -4620,27 +5035,27 @@ mod tests {
let mut parse = SyntaxParseBuilder::new(None, false);
parse.append_roots(&rules);
- assert!(parse.rules[0].selector_list.is_some());
- assert!(parse.rules[1].selector_list.is_none());
+ assert!(parse.rules[0].selector_list().is_some());
+ assert!(parse.rules[1].selector_list().is_none());
- assert!(parse.rules[2].selector_list.is_some());
- let [ParsedRuleChild::Rule(child), ParsedRuleChild::Rule(scope_rule)] = &*parse.rules[2].children else {
+ assert!(parse.rules[2].selector_list().is_some());
+ let [ParsedRuleChild::Rule(child), ParsedRuleChild::Rule(scope_rule)] = parse.rules[2].children() else {
panic!("expected nested style and scope rules")
};
- assert!(child.selector_list.is_some());
- let selectors = scope_rule.scope_selectors.as_ref().unwrap();
+ assert!(child.selector_list().is_some());
+ let selectors = scope_rule.scope_selectors().unwrap();
assert!(selectors.start.is_some());
assert!(selectors.end.is_some());
let rules = parse_stylesheet(b"@media all { > b {} @scope (> .start) {} }");
let mut parse = SyntaxParseBuilder::new(None, false);
parse.append_roots(&rules);
- let [ParsedRuleChild::Rule(group_child), ParsedRuleChild::Rule(scope_rule)] = &*parse.rules[0].children else {
+ let [ParsedRuleChild::Rule(group_child), ParsedRuleChild::Rule(scope_rule)] = parse.rules[0].children() else {
panic!("expected nested style and scope rules")
};
- assert!(group_child.selector_list.is_none());
+ assert!(group_child.selector_list().is_none());
assert_eq!(scope_rule.rule_kind, ParsedRuleKind::Invalid);
- assert!(scope_rule.scope_selectors.is_none());
+ assert!(scope_rule.scope_selectors().is_none());
}
#[test]
@@ -4694,15 +5109,15 @@ mod tests {
let media = &parse.rules[0];
assert_eq!(media.rule_kind, ParsedRuleKind::Media);
- assert_eq!(media.media_list.as_ref().unwrap().queries.len(), 1);
+ assert_eq!(media.media_list().unwrap().queries.len(), 1);
let supports = &parse.rules[1];
assert_eq!(supports.rule_kind, ParsedRuleKind::Supports);
- assert!(supports.supports_condition.is_some());
+ assert!(supports.supports_condition().is_some());
let container = &parse.rules[2];
assert_eq!(container.rule_kind, ParsedRuleKind::Container);
- let conditions = &container.container_conditions.as_ref().unwrap().conditions;
+ let conditions = &container.container_conditions().unwrap().conditions;
assert_eq!(conditions.len(), 2);
assert!(conditions[0].name.is_some());
assert!(conditions[0].query.is_some());
@@ -4711,7 +5126,7 @@ mod tests {
let invalid_supports = &parse.rules[3];
assert_eq!(invalid_supports.rule_kind, ParsedRuleKind::Invalid);
- assert!(invalid_supports.supports_condition.is_none());
+ assert!(invalid_supports.supports_condition().is_none());
}
#[test]
@@ -4800,7 +5215,7 @@ mod tests {
let sheet = parse_test_stylesheet(
b"@page { margin: 1px 2px 3px 4px; @top-left { content: 'page'; } margin-right: 5px; size: a4; size: invalid; }",
);
- let descriptors = &sheet.rules[0].descriptor_block.as_ref().unwrap().descriptors;
+ let descriptors = &sheet.rules[0].descriptor_block().unwrap().descriptors;
let id = |name: &str| descriptor_metadata(1, &utf16(name)).unwrap().id;
assert_eq!(
descriptors.iter().map(|descriptor| descriptor.id).collect::<Vec<_>>(),
diff --git a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/ownership_tests.rs b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/ownership_tests.rs
index b2a6c9babd5..2f92bcca5a1 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/ownership_tests.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/ownership_tests.rs
@@ -6,12 +6,16 @@
use super::{PageSelectorList, ParsedRuleChild, ParsedRuleKind, ParsedStyleSheet, parse_shared_stylesheet};
use crate::css::css_tokenizer::TokenizerInput;
+use crate::css::declaration_block::SharedDeclarationBlock;
use crate::css::ffi_support::FfiUtf16View;
use crate::css::parser::query_parser::css_query_evaluate_supports;
use crate::css::parser::syntax::{SyntaxNode, SyntaxType};
use crate::css::selector_parser::StyleNestingParent;
use crate::css::serialize::serialize_style_value_to_utf16;
use crate::css::style_rule::StyleRule;
+use crate::css::style_value::StyleValueBox;
+use crate::css::style_value::{AnchorPayload, AnchorSizePayload, FontSourcePayload, RandomValueSharingPayload};
+use crate::css::style_value_arc::StyleValueArc;
use std::sync::Arc;
fn declarations(source: &str) -> crate::css::declaration_block::DeclarationBlock {
@@ -28,12 +32,12 @@ fn declarations(source: &str) -> crate::css::declaration_block::DeclarationBlock
}
}
-fn first_rule_block(sheet: &ParsedStyleSheet) -> &crate::css::declaration_block::DeclarationBlockData {
- sheet.rules[0].declaration_block.as_ref().unwrap()
+fn first_rule_block(sheet: &ParsedStyleSheet) -> &crate::css::declaration_block::SharedDeclarationBlock {
+ sheet.rules[0].declaration_block().unwrap()
}
fn first_value(block: &crate::css::declaration_block::DeclarationBlock) -> Vec<u16> {
- serialize_style_value_to_utf16(&block.data().properties[0].value)
+ serialize_style_value_to_utf16(&block.data().properties().get(0).unwrap().value)
}
fn utf16(value: &str) -> Vec<u16> {
@@ -68,8 +72,8 @@ fn parse_shared_on_worker(source: &'static str) -> Arc<ParsedStyleSheet> {
fn builder_constructs_one_rule_tree_with_dense_unique_identities() {
fn visit(rule: &Arc<super::ParsedRule>, identities: &mut std::collections::BTreeSet<u64>) {
assert_eq!(Arc::strong_count(rule), 1);
- assert!(identities.insert(rule.local_identity));
- for child in &rule.children {
+ assert!(identities.insert(u64::from(rule.local_identity)));
+ for child in rule.children() {
match child {
ParsedRuleChild::Rule(rule) => visit(rule, identities),
ParsedRuleChild::Declarations(declarations) => assert!(identities.insert(declarations.local_identity)),
@@ -92,11 +96,11 @@ fn builder_constructs_one_rule_tree_with_dense_unique_identities() {
(0..builder.identity_count).collect::<Vec<_>>()
);
let font = &builder.rules[1];
- let ParsedRuleChild::Declarations(declarations) = &font.children[0] else {
+ let ParsedRuleChild::Declarations(declarations) = &font.children()[0] else {
panic!("expected descriptors")
};
assert!(Arc::ptr_eq(
- font.descriptor_block.as_ref().unwrap(),
+ font.descriptor_block().unwrap(),
declarations.descriptor_block.as_ref().unwrap()
));
}
@@ -107,12 +111,12 @@ fn style_rule_mutation_forks_current_selectors_and_declarations() {
assert_eq!(sheet.rules.len(), 1);
let parsed = &sheet.rules[0];
let rule = StyleRule::new(
- parsed.selector_list.clone().unwrap(),
- parsed.declaration_block.clone().unwrap(),
+ parsed.selector_list().cloned().unwrap(),
+ parsed.declaration_block().cloned().unwrap(),
);
let independent = StyleRule::new(
- parsed.selector_list.clone().unwrap(),
- parsed.declaration_block.clone().unwrap(),
+ parsed.selector_list().cloned().unwrap(),
+ parsed.declaration_block().cloned().unwrap(),
);
drop(sheet);
let shared = StyleRule::new(rule.selectors(), rule.declarations.data());
@@ -123,10 +127,20 @@ fn style_rule_mutation_forks_current_selectors_and_declarations() {
block.replace(&declarations("width: 31px; --色: 青"));
assert_eq!(block.identity(), retained_block.identity());
assert_eq!(first_value(&retained_block), utf16("31px"));
- assert!(rule.set_selector_text(TokenizerInput::Utf16(&utf16(".子")), &[], StyleNestingParent::Style));
+ assert!(rule.set_selector_text(
+ TokenizerInput::Utf16(&utf16(".子")),
+ &[],
+ Default::default(),
+ StyleNestingParent::Style
+ ));
let changed_selectors = rule.selectors();
assert!(!Arc::ptr_eq(&changed_selectors, &original_selectors));
- assert!(!rule.set_selector_text(TokenizerInput::Utf16(&utf16("[")), &[], StyleNestingParent::None));
+ assert!(!rule.set_selector_text(
+ TokenizerInput::Utf16(&utf16("[")),
+ &[],
+ Default::default(),
+ StyleNestingParent::None
+ ));
assert!(Arc::ptr_eq(&changed_selectors, &rule.selectors()));
let snapshot = StyleRule::new(rule.selectors(), rule.declarations.data());
assert!(Arc::ptr_eq(&changed_selectors, &snapshot.selectors()));
@@ -145,8 +159,8 @@ fn counter_style_mutation_preserves_names_and_descriptor_snapshots() {
use crate::css::counter_style::*;
use crate::css::descriptor_block::{rust_descriptor_block_remove, rust_descriptor_block_set};
let sheet = parse_shared_on_worker("@counter-style 初 { prefix: 'A'; } @counter-style 別 { prefix: 'B'; }");
- let rule = FfiCounterStyle::new(sheet.rules[0].counter_style.clone().unwrap());
- let other = FfiCounterStyle::new(sheet.rules[1].counter_style.clone().unwrap());
+ let rule = FfiCounterStyle::new(sheet.rules[0].counter_style().cloned().unwrap());
+ let other = FfiCounterStyle::new(sheet.rules[1].counter_style().cloned().unwrap());
drop(sheet);
assert_eq!(rule.name().units(), utf16("初"));
unsafe {
@@ -283,13 +297,16 @@ fn keyframe_mutation_preserves_exposed_declarations_and_snapshots() {
let sheet = parse_shared_on_worker(
"@keyframes 色 { from, 50% { width: 13px !important; height: 17px; } 25% { width: 19px; } to { width: 29px; } }",
);
- let ParsedRuleChild::Rule(first) = &sheet.rules[0].children[0] else {
+ let ParsedRuleChild::Rule(first) = &sheet.rules[0].children()[0] else {
unreachable!()
};
- let data = first.keyframe.as_ref().unwrap();
+ let data = first.keyframe().unwrap();
assert_eq!(&*data.keys, [0.0, 50.0]);
- assert_eq!(data.declarations.properties.len(), 1);
- assert_eq!(data.declarations.properties[0].property_id, property_id::HEIGHT);
+ assert_eq!(data.declarations.properties().len(), 1);
+ assert_eq!(
+ data.declarations.properties().get(0).unwrap().property_id,
+ property_id::HEIGHT
+ );
let rules = NativeRuleList::from_parsed(sheet.clone());
let shared = NativeRuleList::from_parsed(sheet);
let frames = rules.rule_at(0);
@@ -328,7 +345,7 @@ fn keyframe_mutation_preserves_exposed_declarations_and_snapshots() {
children.insert(1, exposed.clone());
assert_eq!(identity(&declarations_at(children, 1)), identity(&exposed_declarations));
assert_eq!(
- serialize_style_value_to_utf16(&snapshot.properties[0].value),
+ serialize_style_value_to_utf16(&snapshot.properties().get(0).unwrap().value),
utf16("31px")
);
rust_keyframes_set_name(&frames, view(&utf16("新しい名前")));
@@ -359,30 +376,30 @@ fn worker_block_merging_and_shorthand_expansion_only_use_thread_safe_callbacks()
std::thread::spawn(|| {
let block = declarations("color: red !important; --色: first; @unknown {} color: blue; --色: last");
let data = block.data();
- assert_eq!(data.properties.len(), 1);
- assert_eq!(data.properties[0].property_id, property_id::COLOR);
- assert!(data.properties[0].important);
- assert_eq!(data.custom_properties.len(), 1);
+ assert_eq!(data.properties().len(), 1);
+ assert_eq!(data.properties().get(0).unwrap().property_id, property_id::COLOR);
+ assert!(data.properties().get(0).unwrap().important);
+ assert_eq!(data.custom_properties().len(), 1);
let sheet = parse(
&utf16("@page { @top-left { color: red !important; @unknown {} color: blue; } }"),
&super::tests::parse_context(),
);
- let ParsedRuleChild::Rule(margin) = &sheet.rules[0].children[0] else {
+ let ParsedRuleChild::Rule(margin) = &sheet.rules[0].children()[0] else {
panic!()
};
assert_eq!(margin.rule_kind, ParsedRuleKind::Margin);
- let margin = margin.declaration_block.clone().unwrap();
+ let margin = margin.declaration_block().cloned().unwrap();
drop(sheet);
- assert_eq!(margin.properties.len(), 1);
- assert!(margin.properties[0].important);
+ assert_eq!(margin.properties().len(), 1);
+ assert!(margin.properties().get(0).unwrap().important);
let sheet = parse(&utf16("a { margin: var(--gap) }"), &super::tests::parse_context());
assert!(sheet.declarations.is_empty());
- let expanded = sheet.rules[0].declaration_block.clone().unwrap();
+ let expanded = sheet.rules[0].declaration_block().cloned().unwrap();
drop(sheet);
- assert_eq!(expanded.properties.len(), 5);
- assert_eq!(expanded.properties[0].property_id, property_id::MARGIN);
- for property in &expanded.properties[1..] {
- assert!(matches!(&*property.value, StyleValueData::PendingSubstitution { .. }));
+ assert_eq!(expanded.properties().len(), 5);
+ assert_eq!(expanded.properties().get(0).unwrap().property_id, property_id::MARGIN);
+ for property in expanded.properties().iter().skip(1) {
+ assert!(matches!(&**property.value, StyleValueData::PendingSubstitution { .. }));
}
drop((block, data, margin, expanded));
assert_eq!(crate::css::ffi_stats::THREAD_UNSAFE_CPP_CALLBACK_COUNT.get(), 0);
@@ -400,12 +417,12 @@ fn value_graphs_are_shared_and_destroyed_without_worker_callbacks() {
assert!(sheet.declarations.is_empty());
let block = first_rule_block(&sheet);
let values: Vec<_> = block
- .properties
+ .properties()
.iter()
.map(|property| property.value.clone())
.chain(
block
- .custom_properties
+ .custom_properties()
.iter()
.map(|property| property.declaration.value.clone()),
)
@@ -434,8 +451,8 @@ fn value_graphs_are_shared_and_destroyed_without_worker_callbacks() {
"a { position-anchor: --shared-name; color: ReD; grid-template-columns: [shared-name] 1fr; content: 'text' }",
);
assert!(sheet.declarations.is_empty());
- assert_eq!(first_rule_block(&sheet).properties.len(), 4);
- let value = first_rule_block(&sheet).properties[0].value.clone();
+ assert_eq!(first_rule_block(&sheet).properties().len(), 4);
+ let value = first_rule_block(&sheet).properties().get(0).unwrap().value.clone();
drop(sheet);
let StyleValueData::CustomIdent { custom_ident } = &*value else {
panic!()
@@ -446,7 +463,7 @@ fn value_graphs_are_shared_and_destroyed_without_worker_callbacks() {
&super::tests::parse_context(),
);
assert!(second.declarations.is_empty());
- let other = &first_rule_block(&second).properties[0].value;
+ let other = &first_rule_block(&second).properties().get(0).unwrap().value;
assert!(rust_style_value_equals(Some(&value), Some(other)));
}
@@ -488,16 +505,16 @@ fn worker_selector_normalization_survives_publication() {
serialize_selector_without_namespaces(&selector)
}
fn visit(rule: &super::ParsedRule, selectors: &mut Vec<Vec<u16>>, scopes: &mut Vec<Vec<u16>>) {
- for child in &rule.children {
+ for child in rule.children() {
if let ParsedRuleChild::Rule(child) = child {
visit(child, selectors, scopes);
}
}
- if let Some(parsed) = &rule.selector_list {
+ if let Some(parsed) = rule.selector_list() {
selectors.push(text(parsed));
}
if rule.rule_kind == ParsedRuleKind::Scope {
- let scope = rule.scope_selectors.as_ref().unwrap();
+ let scope = rule.scope_selectors().unwrap();
scopes.push(text(scope.start.as_ref().unwrap()));
scopes.push(text(scope.end.as_ref().unwrap()));
}
@@ -534,10 +551,10 @@ fn import_preludes_outlive_the_worker_and_shared_sheet() {
"@import 'a.css' layer(雪) supports(display: grid); @import url('b.css') layer supports(display: unknown); @import 'c.css'; @supports (display: grid) {}",
);
assert_eq!(sheet.rules.len(), 4);
- let named = sheet.rules[0].import_rule.clone().unwrap();
- let anonymous = sheet.rules[1].import_rule.clone().unwrap();
- let unlayered = sheet.rules[2].import_rule.clone().unwrap();
- let supports = sheet.rules[3].supports_condition.clone().unwrap();
+ let named = sheet.rules[0].import_rule().cloned().unwrap();
+ let anonymous = sheet.rules[1].import_rule().cloned().unwrap();
+ let unlayered = sheet.rules[2].import_rule().cloned().unwrap();
+ let supports = sheet.rules[3].supports_condition().cloned().unwrap();
drop(sheet);
assert_eq!(named.layer.as_ref().unwrap().units(), utf16("雪"));
assert!(anonymous.layer.as_ref().unwrap().units().is_empty());
@@ -564,8 +581,8 @@ fn page_text(selectors: &PageSelectorList) -> Vec<u16> {
fn page_selectors_outlive_the_sheet_and_replace_independently() {
let sheet = parse_shared_on_worker("@page 雪:left:first, :blank { margin: 7px; } @page {}");
assert_eq!(sheet.rules.len(), 2);
- let selectors = sheet.rules[0].page_selector_list.clone().unwrap();
- let empty = sheet.rules[1].page_selector_list.clone().unwrap();
+ let selectors = sheet.rules[0].page_selector_list().cloned().unwrap();
+ let empty = sheet.rules[1].page_selector_list().cloned().unwrap();
drop(sheet);
assert_eq!(selectors.selectors.len(), 2);
assert_eq!(page_text(&selectors), utf16("雪:left:first, :blank"));
@@ -591,8 +608,8 @@ fn function_signatures_own_parameters_after_the_sheet_is_dropped() {
"@function --幅(--長さ <length>: 8px, --名: '雪', --未) returns <length> { result: var(--長さ); } @function --空() {}",
);
assert_eq!(sheet.rules.len(), 2);
- let signature = sheet.rules[0].function_signature.clone().unwrap();
- let empty = sheet.rules[1].function_signature.clone().unwrap();
+ let signature = sheet.rules[0].function_signature().cloned().unwrap();
+ let empty = sheet.rules[1].function_signature().cloned().unwrap();
drop(sheet);
assert_eq!(signature.name.units(), utf16("--幅"));
assert_eq!(signature.parameters.len(), 3);
@@ -617,8 +634,8 @@ fn property_rules_own_syntax_and_initial_values_after_the_sheet_is_dropped() {
"@property --色 { syntax: '<length>'; inherits: false; initial-value: 8px; } @property --自由 { syntax: '*'; inherits: true; }",
);
assert_eq!(sheet.rules.len(), 2);
- let typed = sheet.rules[0].property_rule.clone().unwrap();
- let universal = sheet.rules[1].property_rule.clone().unwrap();
+ let typed = sheet.rules[0].property_rule().cloned().unwrap();
+ let universal = sheet.rules[1].property_rule().cloned().unwrap();
drop(sheet);
assert_eq!(typed.name.units(), utf16("--色"));
assert_eq!(typed.syntax_source.units(), utf16("<length>"));
@@ -638,9 +655,9 @@ fn property_rules_own_syntax_and_initial_values_after_the_sheet_is_dropped() {
fn namespace_rules_own_native_names_after_the_sheet_is_dropped() {
let sheet = parse_shared_on_worker("@namespace ''; @namespace 色 'urn:名前'; 色|x {}");
assert_eq!(sheet.rules.len(), 3);
- assert!(sheet.rules[2].selector_list.is_some());
- let default = sheet.rules[0].namespace_rule.clone().unwrap();
- let prefixed = sheet.rules[1].namespace_rule.clone().unwrap();
+ assert!(sheet.rules[2].selector_list().is_some());
+ let default = sheet.rules[0].namespace_rule().cloned().unwrap();
+ let prefixed = sheet.rules[1].namespace_rule().cloned().unwrap();
drop(sheet);
assert!(default.prefix.units().is_empty());
assert!(default.uri.units().is_empty());
@@ -754,14 +771,17 @@ fn retained_values_do_not_keep_the_sheet_in_the_cache() {
let context = super::tests::parse_context();
let first = parse(&source, &context);
assert!(first.declarations.is_empty());
- let retained = first_rule_block(&first).properties[0].value.clone();
+ let retained = first_rule_block(&first).properties().get(0).unwrap().value.clone();
let second_reference = retained.clone();
let weak = Arc::downgrade(&first);
drop(first);
assert!(weak.upgrade().is_none());
let second = parse(&source, &context);
assert!(second.declarations.is_empty());
- assert!(!Arc::ptr_eq(&retained, &first_rule_block(&second).properties[0].value));
+ assert!(!StyleValueArc::ptr_eq(
+ &retained,
+ &first_rule_block(&second).properties().get(0).unwrap().value
+ ));
assert_eq!(serialize_style_value_to_utf16(&retained), utf16("13.25px"));
drop(retained);
assert_eq!(serialize_style_value_to_utf16(&second_reference), utf16("13.25px"));
@@ -772,13 +792,18 @@ fn published_sheet_owns_non_ascii_declarations() {
let sheet = parse_shared_on_worker(".é😀 { width: 13px; --é😀: value }");
assert_eq!(sheet.rules.len(), 1);
assert!(sheet.declarations.is_empty());
- assert!(sheet.rules[0].selector_list.is_some());
+ assert!(sheet.rules[0].selector_list().is_some());
assert_eq!(
- first_rule_block(&sheet).custom_properties[0].name.units(),
+ first_rule_block(&sheet)
+ .custom_properties()
+ .get(0)
+ .unwrap()
+ .name
+ .units(),
utf16("--é😀")
);
assert_eq!(
- serialize_style_value_to_utf16(&first_rule_block(&sheet).properties[0].value),
+ serialize_style_value_to_utf16(&first_rule_block(&sheet).properties().get(0).unwrap().value),
utf16("13px")
);
}
@@ -789,38 +814,35 @@ fn independent_workers_read_the_same_immutable_graph() {
let sheet = parse_shared_on_worker(
".é😀 { width: 13px } @supports (display: grid) { a { height: 7px } } @property --size { syntax: '<length>'; inherits: false; initial-value: 3px } @page :left { margin: 2px }",
);
- let expected_value = first_rule_block(&sheet).properties[0].value.clone();
+ let expected_value = first_rule_block(&sheet).properties().get(0).unwrap().value.clone();
let copies = [sheet.clone(), sheet.clone()];
drop(sheet);
let threads = copies.map(|sheet| {
let expected_value = expected_value.clone();
std::thread::spawn(move || {
- assert!(Arc::ptr_eq(
- &first_rule_block(&sheet).properties[0].value,
+ assert!(StyleValueArc::ptr_eq(
+ &first_rule_block(&sheet).properties().get(0).unwrap().value,
&expected_value
));
assert_eq!(serialize_style_value_to_utf16(&expected_value), utf16("13px"));
assert_eq!(sheet.rules.len(), 4);
assert_eq!(
- rust_parsed_selector_list_length(sheet.rules[0].selector_list.as_ref().unwrap()),
+ rust_parsed_selector_list_length(sheet.rules[0].selector_list().unwrap()),
1
);
assert_eq!(
- css_query_evaluate_supports(sheet.rules[1].supports_condition.as_deref()),
+ css_query_evaluate_supports(sheet.rules[1].supports_condition().map(|value| &**value)),
1
);
- let ParsedRuleChild::Rule(nested) = &sheet.rules[1].children[0] else {
+ let ParsedRuleChild::Rule(nested) = &sheet.rules[1].children()[0] else {
panic!()
};
+ assert_eq!(rust_parsed_selector_list_length(nested.selector_list().unwrap()), 1);
assert_eq!(
- rust_parsed_selector_list_length(nested.selector_list.as_ref().unwrap()),
- 1
- );
- assert_eq!(
- *sheet.rules[2].property_rule.as_ref().unwrap().syntax,
+ *sheet.rules[2].property_rule().unwrap().syntax,
SyntaxNode::Type(SyntaxType::Length)
);
- assert_eq!(sheet.rules[3].page_selector_list.as_ref().unwrap().selectors.len(), 1);
+ assert_eq!(sheet.rules[3].page_selector_list().unwrap().selectors.len(), 1);
drop(sheet);
drop(expected_value);
assert_eq!(crate::css::ffi_stats::THREAD_UNSAFE_CPP_CALLBACK_COUNT.get(), 0);
@@ -838,10 +860,10 @@ fn scope_presence_and_native_selector_names_survive_worker_exit() {
"@import 'data:text/css,'; @import 'data:text/css,' scope; @import 'data:text/css,' scope((.親) to (.限界)); @scope {} @scope (.親) to (.限界) {}",
);
assert_eq!(sheet.rules.len(), 5);
- assert!(sheet.rules[0].scope_selectors.is_none());
+ assert!(sheet.rules[0].scope_selectors().is_none());
let scopes: Vec<_> = sheet.rules[1..]
.iter()
- .map(|rule| rule.scope_selectors.clone().unwrap())
+ .map(|rule| rule.scope_selectors().cloned().unwrap())
.collect();
drop(sheet);
for (index, scope) in scopes.iter().enumerate() {
@@ -854,14 +876,13 @@ fn scope_presence_and_native_selector_names_survive_worker_exit() {
(scope.end.as_ref().unwrap(), "限界"),
] {
assert_eq!(rust_parsed_selector_list_length(selectors), 1);
- let selector = &selectors.selectors()[0].compound_selectors[0].simple_selectors[0];
+ let compounds = selectors.selectors().iter().next().unwrap().compound_selectors();
+ let selector = &compounds[0].simple_selectors.first().unwrap();
let crate::css::selector::SimpleSelector::Class(name) = selector else {
panic!("expected class selector")
};
- assert_eq!(
- name.name,
- crate::css::retained_fly_string::RetainedUtf16FlyString::from_utf16(&utf16(expected))
- );
+ let text = crate::css::style::process_atoms().text(name.name).unwrap();
+ assert_eq!(*text.to_utf16(), *utf16(expected));
}
}
}
@@ -877,28 +898,28 @@ fn shared_rule_tree_preserves_nested_declaration_lists() {
let last = sheet.rules[1].clone();
drop(sheet);
assert_eq!(media.rule_kind, ParsedRuleKind::Media);
- assert_eq!(media.children.len(), 1);
- let ParsedRuleChild::Rule(style) = &media.children[0] else {
+ assert_eq!(media.children().len(), 1);
+ let ParsedRuleChild::Rule(style) = &media.children()[0] else {
panic!()
};
- assert!(style.selector_list.is_some());
- assert_eq!(style.children.len(), 2);
- let ParsedRuleChild::Rule(supports) = &style.children[0] else {
+ assert!(style.selector_list().is_some());
+ assert_eq!(style.children().len(), 2);
+ let ParsedRuleChild::Rule(supports) = &style.children()[0] else {
panic!()
};
assert_eq!(supports.rule_kind, ParsedRuleKind::Supports);
- assert_eq!(supports.children.len(), 3);
- for child in [&supports.children[0], &supports.children[2], &style.children[1]] {
+ assert_eq!(supports.children().len(), 3);
+ for child in [&supports.children()[0], &supports.children()[2], &style.children()[1]] {
let ParsedRuleChild::Declarations(list) = child else {
panic!()
};
assert!(list.declaration_block.is_some());
}
- let ParsedRuleChild::Rule(nested) = &supports.children[1] else {
+ let ParsedRuleChild::Rule(nested) = &supports.children()[1] else {
panic!()
};
- assert!(nested.selector_list.is_some());
- assert!(last.selector_list.is_some());
+ assert!(nested.selector_list().is_some());
+ assert!(last.selector_list().is_some());
}
#[test]
@@ -907,7 +928,7 @@ fn container_conditions_own_names_and_queries_after_the_sheet_is_dropped() {
let sheet =
parse_shared_on_worker("@container 色😀 (width > 10px), 名前, style(--状態: 有効) { div { width: 13px } }");
assert_eq!(sheet.rules.len(), 1);
- let conditions = sheet.rules[0].container_conditions.clone().unwrap();
+ let conditions = sheet.rules[0].container_conditions().cloned().unwrap();
drop(sheet);
let entries = &conditions.conditions;
assert_eq!(entries.len(), 3);
@@ -932,9 +953,9 @@ fn container_conditions_own_names_and_queries_after_the_sheet_is_dropped() {
fn layer_names_outlive_the_shared_sheet() {
let sheet = parse_shared_on_worker("@layer 色.子, emoji😀; @layer 色.子 {} @layer {}");
assert_eq!(sheet.rules.len(), 3);
- let statement = sheet.rules[0].layer_names.clone().unwrap();
- let block = sheet.rules[1].layer_names.clone().unwrap();
- let anonymous = sheet.rules[2].layer_names.clone().unwrap();
+ let statement = sheet.rules[0].layer_names().cloned().unwrap();
+ let block = sheet.rules[1].layer_names().cloned().unwrap();
+ let anonymous = sheet.rules[2].layer_names().cloned().unwrap();
drop(sheet);
assert_eq!(statement.names.len(), 2);
assert_eq!(statement.names[0].units(), utf16("色.子"));
@@ -950,19 +971,20 @@ fn parsed_anchor_and_font_values_retain_their_children() {
use crate::css::style_value::StyleValueData;
let block = declarations("width: anchor-size(width, 1px); left: anchor(left, 2px)");
let data = block.data();
- assert_eq!(data.properties.len(), 2);
- let StyleValueData::AnchorSize { fallback_value, .. } = &*data.properties[0].value else {
+ assert_eq!(data.properties().len(), 2);
+ let StyleValueData::AnchorSize(anchor_size_payload) = &**data.properties().get(0).unwrap().value else {
panic!()
};
+ let AnchorSizePayload { fallback_value, .. } = &**anchor_size_payload;
let fallback = fallback_value.clone();
- let StyleValueData::Anchor {
+ let StyleValueData::Anchor(anchor_payload) = &**data.properties().get(1).unwrap().value else {
+ panic!()
+ };
+ let AnchorPayload {
anchor_side,
fallback_value,
..
- } = &*data.properties[1].value
- else {
- panic!()
- };
+ } = &**anchor_payload;
let side = anchor_side.clone();
let second_fallback = fallback_value.clone();
drop((block, data));
@@ -971,15 +993,16 @@ fn parsed_anchor_and_font_values_retain_their_children() {
assert_eq!(serialize_style_value_to_utf16(second_fallback.data()), utf16("2px"));
let sheet = parse_shared_on_worker("@font-face { font-family: Graph; src: local('Font Name'); }");
- let descriptors = sheet.rules[0].descriptor_block.clone().unwrap();
+ let descriptors = sheet.rules[0].descriptor_block().cloned().unwrap();
let value = &*descriptors.descriptors[1].value;
assert_eq!(serialize_style_value_to_utf16(value), utf16("local(\"Font Name\")"));
let StyleValueData::ValueList { values, .. } = value else {
panic!()
};
- let StyleValueData::FontSource { local_name, .. } = values.as_slice()[0].data() else {
+ let StyleValueData::FontSource(font_source_payload) = values.as_slice()[0].data() else {
panic!()
};
+ let FontSourcePayload { local_name, .. } = &**font_source_payload;
let name = local_name.clone();
drop((sheet, descriptors));
assert_eq!(serialize_style_value_to_utf16(name.data()), utf16("\"Font Name\""));
@@ -999,13 +1022,15 @@ fn calculation_nodes_retain_native_function_values() {
number_type: 0,
})),
step: None,
- sharing: RetainedStyleValueData::from_owned(StyleValueData::RandomValueSharing {
- fixed_value: RetainedStyleValueData::from_owned(StyleValueData::Number { value: 0.25 }),
- is_auto: false,
- has_name: false,
- name: crate::css::css_string::CssString::from_utf16(&[]),
- element_shared: false,
- }),
+ sharing: RetainedStyleValueData::from_owned(StyleValueData::RandomValueSharing(StyleValueBox::new(
+ RandomValueSharingPayload {
+ fixed_value: RetainedStyleValueData::from_owned(StyleValueData::Number { value: 0.25 }),
+ is_auto: false,
+ has_name: false,
+ name: crate::css::css_string::CssString::from_utf16(&[]),
+ element_shared: false,
+ },
+ ))),
};
let CalcNode::Random { sharing, .. } = &node else {
panic!()
@@ -1056,46 +1081,46 @@ fn declaration_mutation_does_not_change_cached_or_nested_shared_blocks() {
let context = super::tests::parse_context();
let first = parse(&source, &context);
let second = parse(&source, &context);
- let original = first.rules[0].declaration_block.clone().unwrap();
- assert!(Arc::ptr_eq(
+ let original = first.rules[0].declaration_block().cloned().unwrap();
+ assert!(SharedDeclarationBlock::ptr_eq(
&original,
- second.rules[0].declaration_block.as_ref().unwrap()
+ second.rules[0].declaration_block().unwrap()
));
let mut changed = DeclarationBlock::new(original.clone());
let independent = DeclarationBlock::new(original.clone());
- assert_eq!(changed.data().properties.len(), 4);
+ assert_eq!(changed.data().properties().len(), 4);
assert!(rust_declaration_block_remove(&mut changed, property_id::MARGIN_TOP));
assert!(rust_declaration_block_remove_custom(&mut changed, view(&utf16("--色"))));
- assert_eq!(independent.data().properties.len(), 4);
- assert_eq!(independent.data().custom_properties.len(), 1);
+ assert_eq!(independent.data().properties().len(), 4);
+ assert_eq!(independent.data().custom_properties().len(), 1);
let third = parse(&source, &context);
- assert!(Arc::ptr_eq(
+ assert!(SharedDeclarationBlock::ptr_eq(
&original,
- third.rules[0].declaration_block.as_ref().unwrap()
+ third.rules[0].declaration_block().unwrap()
));
drop((first, second, third, original));
assert_eq!(
- serialize_style_value_to_utf16(&independent.data().properties[0].value),
+ serialize_style_value_to_utf16(&independent.data().properties().get(0).unwrap().value),
utf16("13px")
);
assert_eq!(
- serialize_style_value_to_utf16(&independent.data().custom_properties[0].declaration.value),
+ serialize_style_value_to_utf16(&independent.data().custom_properties().get(0).unwrap().declaration.value),
utf16("green")
);
let nested = parse_shared_on_worker(".parent { .child {} margin: var(--gap); --色: green; }");
- assert_eq!(nested.rules[0].children.len(), 2);
- let ParsedRuleChild::Declarations(list) = &nested.rules[0].children[1] else {
+ assert_eq!(nested.rules[0].children().len(), 2);
+ let ParsedRuleChild::Declarations(list) = &nested.rules[0].children()[1] else {
panic!()
};
let original = list.declaration_block.clone().unwrap();
drop(nested);
let mut changed = DeclarationBlock::new(original.clone());
let shared = DeclarationBlock::new(original);
- assert_eq!(changed.data().properties.len(), 5);
- assert_eq!(changed.data().custom_properties.len(), 1);
+ assert_eq!(changed.data().properties().len(), 5);
+ assert_eq!(changed.data().custom_properties().len(), 1);
assert!(rust_declaration_block_remove(&mut changed, property_id::MARGIN_LEFT));
- assert_eq!(shared.data().properties.len(), 5);
+ assert_eq!(shared.data().properties().len(), 5);
}
#[test]
@@ -1108,8 +1133,8 @@ fn media_mutation_preserves_live_owners_and_shared_snapshots() {
}
let sheet = parse_shared_on_worker("@import 'data:text/css,' screen, écran; @media all, print {}");
assert_eq!(sheet.rules.len(), 2);
- let imported = MediaList::new(sheet.rules[0].media_list.clone().unwrap());
- let media = MediaList::new(sheet.rules[1].media_list.clone().unwrap());
+ let imported = MediaList::new(sheet.rules[0].media_list().cloned().unwrap());
+ let media = MediaList::new(sheet.rules[1].media_list().cloned().unwrap());
drop(sheet);
assert_eq!(text(&imported), utf16("screen, écran"));
assert_eq!(text(&media), utf16("all, print"));
@@ -1180,7 +1205,7 @@ fn function_descriptor_blocks_retain_worker_parsed_values() {
let data = list.descriptor_block.clone().unwrap();
let block = unsafe { Box::from_raw(super::rust_css_syntax_parse_descriptor_block(&*parse)) };
assert_eq!(block.data().descriptors.len(), 2);
- assert!(Arc::ptr_eq(
+ assert!(StyleValueArc::ptr_eq(
&data.descriptors[0].value,
&block.data().descriptors[0].value
));
@@ -1193,7 +1218,7 @@ fn function_descriptor_blocks_retain_worker_parsed_values() {
.unwrap();
let descriptors = FfiDescriptorBlock::new(data);
assert_eq!(descriptors.data().descriptors.len(), 2);
- assert!(Arc::ptr_eq(
+ assert!(StyleValueArc::ptr_eq(
&descriptors.data().descriptors[1].value,
&parsed_values.descriptors[1].value
));
@@ -1211,9 +1236,9 @@ fn descriptor_mutation_forks_worker_parsed_data() {
"@page { margin-top: 13px; margin-left: 29px; margin-top: 17px } @font-face { font-family: 色; src: local(色) }",
);
assert_eq!(sheet.rules.len(), 2);
- let mut page = FfiDescriptorBlock::new(sheet.rules[0].descriptor_block.clone().unwrap());
- let shared = FfiDescriptorBlock::new(sheet.rules[0].descriptor_block.clone().unwrap());
- let font = sheet.rules[1].descriptor_block.clone().unwrap();
+ let mut page = FfiDescriptorBlock::new(sheet.rules[0].descriptor_block().cloned().unwrap());
+ let shared = FfiDescriptorBlock::new(sheet.rules[0].descriptor_block().cloned().unwrap());
+ let font = sheet.rules[1].descriptor_block().cloned().unwrap();
drop(sheet);
let data = page.data();
assert_eq!(data.descriptors.len(), 2);
@@ -1231,12 +1256,12 @@ fn descriptor_mutation_forks_worker_parsed_data() {
let replacement = crate::css::descriptor_block::FfiDescriptor {
name: original.name,
id: original.id,
- value: Arc::as_ptr(&data.descriptors[0].value).cast(),
+ value: StyleValueArc::as_ptr(&data.descriptors[0].value).cast(),
};
assert!(rust_descriptor_block_set(&mut page, &replacement));
}
- assert!(Arc::ptr_eq(&shared.data().descriptors[1].value, &original));
- assert!(Arc::ptr_eq(
+ assert!(StyleValueArc::ptr_eq(&shared.data().descriptors[1].value, &original));
+ assert!(StyleValueArc::ptr_eq(
&page.data().descriptors[1].value,
&data.descriptors[0].value
));
diff --git a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/shared_rules.rs b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/shared_rules.rs
index 66b1efe56d3..aa268de27a5 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/shared_rules.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/shared_rules.rs
@@ -10,7 +10,7 @@ use super::{
};
use crate::css::container_conditions::ContainerConditionsData;
use crate::css::css_string::CssString;
-use crate::css::declaration_block::DeclarationBlockData;
+use crate::css::declaration_block::SharedDeclarationBlock;
use crate::css::descriptor_block::DescriptorBlockData;
use crate::css::font_feature_values::FontFeatureValuesData;
use crate::css::function_signature::FunctionSignature;
@@ -26,7 +26,12 @@ use crate::css::selector_parser::RustParsedSelectorList;
use std::ops::ControlFlow;
use std::sync::Arc;
-pub(super) fn native_child_indices(children: &[ParsedRuleChild], parent: Option<ParsedRuleKind>) -> Box<[usize]> {
+/// A position among a sheet's rules or a rule's children, which fits in 32 bits.
+pub(super) fn narrow_index(index: usize) -> u32 {
+ u32::try_from(index).expect("style sheet has too many rules")
+}
+
+pub(super) fn native_child_indices(children: &[ParsedRuleChild], parent: Option<ParsedRuleKind>) -> Box<[u32]> {
if !matches!(
parent,
None | Some(
@@ -56,7 +61,7 @@ pub(super) fn native_child_indices(children: &[ParsedRuleChild], parent: Option<
{
return None;
}
- Some(index)
+ Some(narrow_index(index))
})
.collect()
}
@@ -108,7 +113,7 @@ impl ParsedRuleList {
return self.visit_rules(visit);
}
for &position in &self.sheet.media_holding_roots {
- visit(self.rule_at(position))?;
+ visit(self.rule_at(position as usize))?;
}
ControlFlow::Continue(())
}
@@ -117,17 +122,17 @@ impl ParsedRuleList {
self.parent
.as_ref()
.map_or(self.sheet.native_roots.len(), |(parent, _)| {
- parent.native_children.len()
+ parent.native_children().len()
})
}
pub(crate) fn rule_at(&self, index: usize) -> SharedRule<'_> {
match &self.parent {
Some((parent, kind)) => {
- SharedRule::from_child(&parent.children[parent.native_children[index]], *kind).unwrap()
+ SharedRule::from_child(&parent.children()[parent.native_children()[index] as usize], *kind).unwrap()
}
None => {
- let index = self.sheet.native_roots[index];
+ let index = self.sheet.native_roots[index] as usize;
if self.sheet.items.is_empty() {
SharedRule::from_rule(&self.sheet.rules[index], self.sheet.declarations_kind).unwrap()
} else {
@@ -191,7 +196,7 @@ impl ParsedRule {
| ParsedRuleKind::Unknown
| ParsedRuleKind::IgnoredVendor
| ParsedRuleKind::FontFeatureValuesRule => return None,
- ParsedRuleKind::Qualified if self.keyframe.is_some() => NativeRuleType::Keyframe,
+ ParsedRuleKind::Qualified if self.keyframe().is_some() => NativeRuleType::Keyframe,
ParsedRuleKind::Qualified => NativeRuleType::Style,
ParsedRuleKind::Import => NativeRuleType::Import,
ParsedRuleKind::Media => NativeRuleType::Media,
@@ -220,7 +225,7 @@ impl ParsedRule {
pub(super) fn holds_media_rules(&self) -> bool {
matches!(self.rule_kind, ParsedRuleKind::Media | ParsedRuleKind::Import)
|| self
- .children
+ .children()
.iter()
.any(|child| matches!(child, ParsedRuleChild::Rule(rule) if rule.holds_media_rules()))
}
@@ -255,7 +260,7 @@ impl<'a> SharedRule<'a> {
pub(crate) fn local_identity(self) -> u64 {
match self.data {
- SharedRuleData::Rule(rule) => rule.local_identity,
+ SharedRuleData::Rule(rule) => u64::from(rule.local_identity),
SharedRuleData::Declarations(declarations) => declarations.local_identity,
}
}
@@ -264,47 +269,47 @@ impl<'a> SharedRule<'a> {
let SharedRuleData::Rule(rule) = self.data else {
return None;
};
- rule.namespace_rule.as_ref()
+ rule.namespace_rule()
}
pub(crate) fn property(self) -> Option<&'a PropertyRuleData> {
let SharedRuleData::Rule(rule) = self.data else {
return None;
};
- rule.property_rule.as_deref()
+ rule.property_rule().map(|value| &**value)
}
pub(crate) fn import(self) -> Option<&'a Arc<ImportRuleData>> {
let SharedRuleData::Rule(rule) = self.data else {
return None;
};
- rule.import_rule.as_ref()
+ rule.import_rule()
}
pub(crate) fn media_data(self) -> Arc<MediaListData> {
let SharedRuleData::Rule(rule) = self.data else {
unreachable!()
};
- rule.media_list.as_ref().unwrap().clone()
+ rule.media_list().unwrap().clone()
}
pub(crate) fn function_signature(self) -> Option<Arc<FunctionSignature>> {
let SharedRuleData::Rule(rule) = self.data else {
return None;
};
- rule.function_signature.clone()
+ rule.function_signature().cloned()
}
pub(crate) fn font_feature_values(self) -> Option<Arc<FontFeatureValuesData>> {
let SharedRuleData::Rule(rule) = self.data else {
return None;
};
- rule.font_feature_values.clone()
+ rule.font_feature_values().cloned()
}
pub(crate) fn descriptors(self) -> Option<Arc<DescriptorBlockData>> {
match self.data {
- SharedRuleData::Rule(rule) => rule.descriptor_block.clone(),
+ SharedRuleData::Rule(rule) => rule.descriptor_block().cloned(),
SharedRuleData::Declarations(declarations) => declarations.descriptor_block.clone(),
}
}
@@ -313,28 +318,28 @@ impl<'a> SharedRule<'a> {
let SharedRuleData::Rule(rule) = self.data else {
return None;
};
- rule.keyframe.as_deref()
+ rule.keyframe().map(|value| &**value)
}
pub(crate) fn selectors(self) -> Option<Arc<RustParsedSelectorList>> {
let SharedRuleData::Rule(rule) = self.data else {
return None;
};
- rule.selector_list.clone()
+ rule.selector_list().cloned()
}
pub(crate) fn scope(self) -> Option<Arc<ScopeSelectors>> {
let SharedRuleData::Rule(rule) = self.data else {
return None;
};
- rule.scope_selectors.clone()
+ rule.scope_selectors().cloned()
}
pub(crate) fn container(self) -> Option<&'a Arc<ContainerConditionsData>> {
let SharedRuleData::Rule(rule) = self.data else {
return None;
};
- rule.container_conditions.as_ref()
+ rule.container_conditions()
}
pub(crate) fn layer_name(self) -> Option<&'a [u16]> {
@@ -342,8 +347,8 @@ impl<'a> SharedRule<'a> {
return None;
};
match self.rule_type {
- NativeRuleType::LayerBlock => Some(rule.layer_names.as_ref().unwrap().names[0].units()),
- NativeRuleType::Import => Some(rule.import_rule.as_ref().unwrap().layer.as_ref()?.units()),
+ NativeRuleType::LayerBlock => Some(rule.layer_names().unwrap().names[0].units()),
+ NativeRuleType::Import => Some(rule.import_rule().unwrap().layer.as_ref()?.units()),
_ => None,
}
}
@@ -353,10 +358,10 @@ impl<'a> SharedRule<'a> {
return None;
};
match self.rule_type {
- NativeRuleType::Property => Some(rule.property_rule.as_ref().unwrap().name.clone()),
- NativeRuleType::Keyframes => rule.keyframes_name.clone(),
- NativeRuleType::PositionTry => rule.position_try_name.clone(),
- NativeRuleType::CounterStyle => Some(rule.counter_style.as_ref().unwrap().name.clone()),
+ NativeRuleType::Property => Some(rule.property_rule().unwrap().name.clone()),
+ NativeRuleType::Keyframes => rule.keyframes_name().cloned(),
+ NativeRuleType::PositionTry => rule.position_try_name().cloned(),
+ NativeRuleType::CounterStyle => Some(rule.counter_style().unwrap().name.clone()),
_ => None,
}
}
@@ -365,14 +370,14 @@ impl<'a> SharedRule<'a> {
let SharedRuleData::Rule(rule) = self.data else {
return None;
};
- rule.layer_names.as_deref()
+ rule.layer_names().map(|value| &**value)
}
pub(crate) fn media(self) -> Option<&'a MediaListData> {
let SharedRuleData::Rule(rule) = self.data else {
return None;
};
- rule.media_list.as_deref()
+ rule.media_list().map(|value| &**value)
}
pub(crate) fn supports(self) -> Option<&'a Arc<FfiQueryHandle>> {
@@ -380,15 +385,15 @@ impl<'a> SharedRule<'a> {
return None;
};
if self.rule_type == NativeRuleType::Import {
- rule.import_rule.as_ref().unwrap().supports.as_ref()
+ rule.import_rule().unwrap().supports.as_ref()
} else {
- rule.supports_condition.as_ref()
+ rule.supports_condition()
}
}
- pub(crate) fn cascade_declarations(self) -> Option<Arc<DeclarationBlockData>> {
+ pub(crate) fn cascade_declarations(self) -> Option<SharedDeclarationBlock> {
match self.data {
- SharedRuleData::Rule(rule) if self.rule_type == NativeRuleType::Style => rule.declaration_block.clone(),
+ SharedRuleData::Rule(rule) if self.rule_type == NativeRuleType::Style => rule.declaration_block().cloned(),
SharedRuleData::Declarations(declarations) if self.rule_type == NativeRuleType::NestedDeclarations => {
declarations.declaration_block.clone()
}
@@ -396,10 +401,10 @@ impl<'a> SharedRule<'a> {
}
}
- pub(crate) fn position_try_declarations(self) -> Option<Arc<DeclarationBlockData>> {
+ pub(crate) fn position_try_declarations(self) -> Option<SharedDeclarationBlock> {
match self.data {
SharedRuleData::Rule(rule) if self.rule_type == NativeRuleType::PositionTry => {
- rule.declaration_block.clone()
+ rule.declaration_block().cloned()
}
_ => None,
}
@@ -412,8 +417,8 @@ impl<'a> SharedRule<'a> {
let Some(declarations_kind) = self.rule_type.child_declarations_kind(self.declarations_kind) else {
return ControlFlow::Continue(());
};
- for &index in &rule.native_children {
- let child = Self::from_child(&rule.children[index], declarations_kind).unwrap();
+ for &index in rule.native_children() {
+ let child = Self::from_child(&rule.children()[index as usize], declarations_kind).unwrap();
visit(child)?;
}
ControlFlow::Continue(())
diff --git a/Libraries/LibWeb/Rust/src/css/parser/transforms_effects_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/transforms_effects_parser.rs
index ad89735230a..413215b361d 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/transforms_effects_parser.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/transforms_effects_parser.rs
@@ -5,7 +5,6 @@
*/
// Parsed values use the thread-confined shared graph owned by the C++ style objects.
-#![allow(clippy::arc_with_non_send_sync)]
use super::component_value::{ComponentKind, ComponentValue};
use super::token_stream::TokenStream;
@@ -21,12 +20,13 @@ use crate::css::math_functions::math_function_from_name;
use crate::css::parser::color_parser::parse_color_value;
use crate::css::property_metadata::{property_accepted_keywords, property_id};
use crate::css::style_compute::px_length_unit;
+use crate::css::style_value::{EasingPayload, ShadowPayload, StyleValueBox, TransformationPayload};
use crate::css::style_value::{
RetainedLinearEasingStop, RetainedLinearEasingStopList, RetainedStyleValueData, RetainedStyleValueDataList,
StyleValueData,
};
+use crate::css::style_value_arc::StyleValueArc;
use crate::css::value_codes::{VALUE_TYPE_ANGLE, VALUE_TYPE_INTEGER, VALUE_TYPE_NUMBER, VALUE_TYPE_PERCENTAGE};
-use std::sync::Arc;
pub(crate) use crate::css::transform_functions::*;
@@ -42,12 +42,12 @@ fn retained(value: StyleValueData) -> RetainedStyleValueData {
}
fn transformation(property: u16, transform_function: u8, values: Vec<StyleValueData>) -> StyleValueData {
- StyleValueData::Transformation {
+ StyleValueData::Transformation(StyleValueBox::new(TransformationPayload {
property,
transform_function,
values: RetainedStyleValueDataList::from_retained_values(values.into_iter().map(retained).collect()),
matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
- }
+ }))
}
fn value_list(values: Vec<StyleValueData>, separator: u8, collapsible: bool) -> StyleValueData {
@@ -364,7 +364,7 @@ fn easing(
is_keyword: bool,
) -> StyleValueData {
let [x1, y1, x2, y2] = coordinates.map(|value| value.map_or_else(RetainedStyleValueData::none, retained));
- StyleValueData::Easing {
+ StyleValueData::Easing(StyleValueBox::new(EasingPayload {
kind,
linear_stops: RetainedLinearEasingStopList::from_retained_elements(linear_stops),
x1,
@@ -374,7 +374,7 @@ fn easing(
number_of_intervals: number_of_intervals.map_or_else(RetainedStyleValueData::none, retained),
step_position,
is_keyword,
- }
+ }))
}
fn parse_numeric_component(
@@ -661,7 +661,7 @@ fn parse_drop_shadow(context: &ParseContext, property: u16, values: &[ComponentV
Some(filter(
1,
0,
- StyleValueData::Shadow {
+ StyleValueData::Shadow(StyleValueBox::new(ShadowPayload {
shadow_type: 1,
color: color.map_or_else(RetainedStyleValueData::none, retained),
offset_x: retained(offset_x),
@@ -669,7 +669,7 @@ fn parse_drop_shadow(context: &ParseContext, property: u16, values: &[ComponentV
blur_radius: blur_radius.map_or_else(RetainedStyleValueData::none, retained),
spread_distance: RetainedStyleValueData::none(),
placement: 0,
- },
+ })),
))
}
@@ -818,7 +818,9 @@ pub(crate) fn parse_transform_effect_property(
// this parser does not have the context needed to parse it.
return ParseOutcome::NotHandled;
}
- parsed.map_or(ParseOutcome::Invalid, |value| ParseOutcome::Parsed(Arc::new(value)))
+ parsed.map_or(ParseOutcome::Invalid, |value| {
+ ParseOutcome::Parsed(StyleValueArc::new(value))
+ })
}
#[cfg(test)]
diff --git a/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs
index 02e73e2ab83..9e2844a46f9 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs
@@ -51,13 +51,18 @@ use crate::css::property_metadata::{
};
use crate::css::style_compute::{LENGTH_UNIT_NAMES, px_length_unit};
use crate::css::style_value::{
- RetainedByteList, RetainedComponentValueList, RetainedCounterDefinition, RetainedCounterDefinitionList,
- RetainedNumericRangeList, RetainedPropertyIdList, RetainedRequestUrlModifier, RetainedRequestUrlModifierList,
- RetainedString, RetainedStyleValueData, RetainedStyleValueDataList, StyleValueData, shared_style_value,
+ BackgroundSizePayload, BorderImageSlicePayload, CalculatedPayload, ColorSchemePayload, ContentPayload,
+ CounterDefinitionsPayload, CounterPayload, CounterStylePayload, CursorPayload, FunctionPayload, RatioPayload,
+ ScrollbarColorPayload, ShadowPayload, ShorthandPayload, StyleValueBox, UrlPayload,
};
+use crate::css::style_value::{
+ RetainedByteList, RetainedCounterDefinition, RetainedCounterDefinitionList, RetainedNumericRangeList,
+ RetainedPropertyIdList, RetainedRequestUrlModifier, RetainedRequestUrlModifierList, RetainedString,
+ RetainedStyleValueData, RetainedStyleValueDataList, StyleValueData, UnresolvedValueComponents, shared_style_value,
+};
+use crate::css::style_value_arc::StyleValueArc;
use crate::css::value_codes::*;
use std::ffi::c_void;
-use std::sync::Arc;
pub(crate) use crate::css::dimension_units::*;
@@ -175,7 +180,7 @@ impl Default for ParseContext<'_> {
}
pub(crate) enum ParseOutcome {
- Parsed(Arc<StyleValueData>),
+ Parsed(StyleValueArc),
Invalid,
NotHandled,
}
@@ -461,11 +466,11 @@ pub(crate) fn parse_url_value(context: &ParseContext, value: &ComponentValue) ->
}
_ => return None,
};
- Some(StyleValueData::Url {
+ Some(StyleValueData::Url(StyleValueBox::new(UrlPayload {
url: RetainedString::from_utf16(url)?,
url_type,
modifiers: RetainedRequestUrlModifierList::from_retained_modifiers(modifiers),
- })
+ })))
}
pub(crate) fn value_list(values: Vec<StyleValueData>, separator: u8, collapsible: bool) -> StyleValueData {
@@ -896,10 +901,10 @@ fn parse_ratio_value(values: &[&ComponentValue]) -> Option<StyleValueData> {
[_, slash, denominator] if slash.is_delim(b'/') => parse_number_value(denominator, NumericRange::NON_NEGATIVE)?,
_ => return None,
};
- Some(StyleValueData::Ratio {
+ Some(StyleValueData::Ratio(StyleValueBox::new(RatioPayload {
numerator: RetainedStyleValueData::from_owned(numerator),
denominator: RetainedStyleValueData::from_owned(denominator),
- })
+ })))
}
pub(crate) fn parse_ratio_value_with_context(
@@ -930,10 +935,10 @@ pub(crate) fn parse_ratio_value_with_context(
[_, slash, denominator] if slash.is_delim(b'/') => parse_component(denominator)?,
_ => return None,
};
- Some(StyleValueData::Ratio {
+ Some(StyleValueData::Ratio(StyleValueBox::new(RatioPayload {
numerator: RetainedStyleValueData::from_owned(numerator),
denominator: RetainedStyleValueData::from_owned(denominator),
- })
+ })))
}
fn parse_opacity_value(value: &ComponentValue) -> Option<StyleValueData> {
@@ -1320,7 +1325,7 @@ pub(crate) fn parse_calculated_numeric_value_allowing_size_keyword(
let (range_value_type, range) = opacity_resolved_type
.map(|value_type| (value_type, NumericRange::INFINITE))
.unwrap_or((value_type, range));
- let calculated = StyleValueData::Calculated {
+ let calculated = StyleValueData::Calculated(StyleValueBox::new(CalculatedPayload {
rust_calculation: crate::css::calc::CalcNodeHandle::from_arc(root),
resolve_as_is_number: percentages_resolve_as == Some(VALUE_TYPE_NUMBER),
resolve_as_base: resolve_as
@@ -1334,7 +1339,7 @@ pub(crate) fn parse_calculated_numeric_value_allowing_size_keyword(
percentages_resolve_as: percentages_resolve_as.unwrap_or(0),
resolve_numbers_as_integers: value_type == VALUE_TYPE_INTEGER,
accepted_ranges: RetainedNumericRangeList::from_single_numeric_range(range_value_type, range.min, range.max),
- };
+ }));
if value_type == VALUE_TYPE_OPACITY_VALUE {
Some(StyleValueData::OpacityValue {
value: RetainedStyleValueData::from_owned(calculated),
@@ -1714,13 +1719,15 @@ fn parse_contain_intrinsic_size_shorthand(
[width, height] => vec![width.clone(), height.clone()],
_ => return ParseOutcome::Invalid,
};
- ParseOutcome::Parsed(shared_style_value(StyleValueData::Shorthand {
- shorthand_property: property,
- sub_properties: RetainedPropertyIdList::from_property_ids(longhands.to_vec()),
- values: RetainedStyleValueDataList::from_retained_values(
- expanded.into_iter().map(RetainedStyleValueData::from_owned).collect(),
- ),
- }))
+ ParseOutcome::Parsed(shared_style_value(StyleValueData::Shorthand(StyleValueBox::new(
+ ShorthandPayload {
+ shorthand_property: property,
+ sub_properties: RetainedPropertyIdList::from_property_ids(longhands.to_vec()),
+ values: RetainedStyleValueDataList::from_retained_values(
+ expanded.into_iter().map(RetainedStyleValueData::from_owned).collect(),
+ ),
+ },
+ ))))
}
// https://drafts.csswg.org/css-sizing-4/#intrinsic-size-override
@@ -1840,10 +1847,12 @@ fn parse_math_depth_property(context: &ParseContext, property: u16, values: &[Co
return ParseOutcome::Invalid;
}
let name = CssString::from_utf16(&"add".encode_utf16().collect::<Vec<_>>());
- ParseOutcome::Parsed(shared_style_value(StyleValueData::Function {
- name,
- value: RetainedStyleValueData::from_owned(integer),
- }))
+ ParseOutcome::Parsed(shared_style_value(StyleValueData::Function(StyleValueBox::new(
+ FunctionPayload {
+ name,
+ value: RetainedStyleValueData::from_owned(integer),
+ },
+ ))))
}
fn parse_scrollbar_color_property(context: &ParseContext, property: u16, values: &[ComponentValue]) -> ParseOutcome {
@@ -1865,10 +1874,12 @@ fn parse_scrollbar_color_property(context: &ParseContext, property: u16, values:
if stream.has_next_token() {
return ParseOutcome::Invalid;
}
- ParseOutcome::Parsed(shared_style_value(StyleValueData::ScrollbarColor {
- thumb_color: RetainedStyleValueData::from_owned(thumb_color),
- track_color: RetainedStyleValueData::from_owned(track_color),
- }))
+ ParseOutcome::Parsed(shared_style_value(StyleValueData::ScrollbarColor(StyleValueBox::new(
+ ScrollbarColorPayload {
+ thumb_color: RetainedStyleValueData::from_owned(thumb_color),
+ track_color: RetainedStyleValueData::from_owned(track_color),
+ },
+ ))))
}
fn parse_stroke_dasharray_property(context: &ParseContext, property: u16, values: &[ComponentValue]) -> ParseOutcome {
@@ -2283,10 +2294,12 @@ fn parse_background_size_item(
} else {
StyleValueData::Keyword { keyword: keyword::AUTO }
};
- Some(StyleValueData::BackgroundSize {
- size_x: RetainedStyleValueData::from_owned(size_x),
- size_y: RetainedStyleValueData::from_owned(size_y),
- })
+ Some(StyleValueData::BackgroundSize(StyleValueBox::new(
+ BackgroundSizePayload {
+ size_x: RetainedStyleValueData::from_owned(size_x),
+ size_y: RetainedStyleValueData::from_owned(size_y),
+ },
+ )))
}
fn parse_background_size_property(context: &ParseContext, property: u16, values: &[ComponentValue]) -> ParseOutcome {
@@ -2356,13 +2369,15 @@ fn parse_border_image_slice_property(context: &ParseContext, property: u16, valu
[top, right, bottom, left] => (top, right, bottom, left),
_ => return ParseOutcome::Invalid,
};
- ParseOutcome::Parsed(shared_style_value(StyleValueData::BorderImageSlice {
- top: RetainedStyleValueData::from_owned(top.clone()),
- right: RetainedStyleValueData::from_owned(right.clone()),
- bottom: RetainedStyleValueData::from_owned(bottom.clone()),
- left: RetainedStyleValueData::from_owned(left.clone()),
- fill,
- }))
+ ParseOutcome::Parsed(shared_style_value(StyleValueData::BorderImageSlice(
+ StyleValueBox::new(BorderImageSlicePayload {
+ top: RetainedStyleValueData::from_owned(top.clone()),
+ right: RetainedStyleValueData::from_owned(right.clone()),
+ bottom: RetainedStyleValueData::from_owned(bottom.clone()),
+ left: RetainedStyleValueData::from_owned(left.clone()),
+ fill,
+ }),
+ )))
}
fn parse_shadow_item(
@@ -2435,7 +2450,7 @@ fn parse_shadow_item(
return None;
}
- Some(StyleValueData::Shadow {
+ Some(StyleValueData::Shadow(StyleValueBox::new(ShadowPayload {
shadow_type: u8::from(is_text_shadow),
color: color.map_or_else(RetainedStyleValueData::none, RetainedStyleValueData::from_owned),
offset_x: RetainedStyleValueData::from_owned(offset_x?),
@@ -2443,7 +2458,7 @@ fn parse_shadow_item(
blur_radius: blur_radius.map_or_else(RetainedStyleValueData::none, RetainedStyleValueData::from_owned),
spread_distance: spread_distance.map_or_else(RetainedStyleValueData::none, RetainedStyleValueData::from_owned),
placement: u8::from(inset),
- })
+ })))
}
fn parse_shadow_property(context: &ParseContext, property: u16, values: &[ComponentValue]) -> ParseOutcome {
@@ -2935,11 +2950,13 @@ fn parse_color_scheme_property(_context: &ParseContext, values: &[ComponentValue
.ident()
.is_some_and(|ident| equals_ascii_case_insensitive(ident, b"normal"))
{
- return ParseOutcome::Parsed(shared_style_value(StyleValueData::ColorScheme {
- schemes: CssStringList::from_strings(Vec::new()),
- scheme_codes: RetainedByteList::from_bytes(Vec::new()),
- only: false,
- }));
+ return ParseOutcome::Parsed(shared_style_value(StyleValueData::ColorScheme(StyleValueBox::new(
+ ColorSchemePayload {
+ schemes: CssStringList::from_strings(Vec::new()),
+ scheme_codes: RetainedByteList::from_bytes(Vec::new()),
+ only: false,
+ },
+ ))));
}
let mut only = false;
@@ -2972,11 +2989,13 @@ fn parse_color_scheme_property(_context: &ParseContext, values: &[ComponentValue
if schemes.is_empty() {
return ParseOutcome::Invalid;
}
- ParseOutcome::Parsed(shared_style_value(StyleValueData::ColorScheme {
- schemes: CssStringList::from_strings(schemes),
- scheme_codes: RetainedByteList::from_bytes(scheme_codes),
- only,
- }))
+ ParseOutcome::Parsed(shared_style_value(StyleValueData::ColorScheme(StyleValueBox::new(
+ ColorSchemePayload {
+ schemes: CssStringList::from_strings(schemes),
+ scheme_codes: RetainedByteList::from_bytes(scheme_codes),
+ only,
+ },
+ ))))
}
fn parse_quotes_property(_context: &ParseContext, values: &[ComponentValue]) -> ParseOutcome {
@@ -3065,9 +3084,11 @@ fn parse_counter_definitions_property(
if definitions.is_empty() {
return ParseOutcome::Invalid;
}
- ParseOutcome::Parsed(shared_style_value(StyleValueData::CounterDefinitions {
- counter_definitions: RetainedCounterDefinitionList::from_retained_elements(definitions),
- }))
+ ParseOutcome::Parsed(shared_style_value(StyleValueData::CounterDefinitions(
+ StyleValueBox::new(CounterDefinitionsPayload {
+ counter_definitions: RetainedCounterDefinitionList::from_retained_elements(definitions),
+ }),
+ )))
}
fn parse_counter_style(_context: &ParseContext, value: &ComponentValue) -> Option<StyleValueData> {
@@ -3092,12 +3113,12 @@ fn parse_counter_style(_context: &ParseContext, value: &ComponentValue) -> Optio
} else {
identifier.to_vec()
};
- return Some(StyleValueData::CounterStyle {
+ return Some(StyleValueData::CounterStyle(StyleValueBox::new(CounterStylePayload {
is_symbols: false,
name: CssString::from_utf16(&name),
symbols_type: symbols_type::SYMBOLIC,
symbols: CssStringList::from_strings(Vec::new()),
- });
+ })));
}
let (name, arguments) = value.function()?;
@@ -3129,12 +3150,12 @@ fn parse_counter_style(_context: &ParseContext, value: &ComponentValue) -> Optio
{
return None;
}
- Some(StyleValueData::CounterStyle {
+ Some(StyleValueData::CounterStyle(StyleValueBox::new(CounterStylePayload {
is_symbols: true,
name: CssString::none(),
symbols_type: symbol_type,
symbols: CssStringList::from_strings(symbols),
- })
+ })))
}
fn parse_list_style_type_property(context: &ParseContext, values: &[ComponentValue]) -> ParseOutcome {
@@ -3174,19 +3195,19 @@ fn parse_counter_function(context: &ParseContext, value: &ComponentValue) -> Opt
let counter_style = if parts.len() > style_index {
parse_counter_style(context, single_non_whitespace_value(parts[style_index])?)?
} else {
- StyleValueData::CounterStyle {
+ StyleValueData::CounterStyle(StyleValueBox::new(CounterStylePayload {
is_symbols: false,
name: CssString::from_utf16(&"decimal".encode_utf16().collect::<Vec<_>>()),
symbols_type: symbols_type::SYMBOLIC,
symbols: CssStringList::from_strings(Vec::new()),
- }
+ }))
};
- Some(StyleValueData::Counter {
+ Some(StyleValueData::Counter(StyleValueBox::new(CounterPayload {
function: function as u8,
counter_name: CssString::from_utf16(counter_name),
counter_style: RetainedStyleValueData::from_owned(counter_style),
join_string,
- })
+ })))
}
fn parse_content_property(context: &ParseContext, values: &[ComponentValue]) -> ParseOutcome {
@@ -3257,14 +3278,16 @@ fn parse_content_property(context: &ParseContext, values: &[ComponentValue]) ->
if content.is_empty() || (in_alt_text && alt_text.is_empty()) {
return ParseOutcome::Invalid;
}
- ParseOutcome::Parsed(shared_style_value(StyleValueData::Content {
- content: RetainedStyleValueData::from_owned(value_list(content, 0, true)),
- alt_text: if alt_text.is_empty() {
- RetainedStyleValueData::none()
- } else {
- RetainedStyleValueData::from_owned(value_list(alt_text, 0, true))
+ ParseOutcome::Parsed(shared_style_value(StyleValueData::Content(StyleValueBox::new(
+ ContentPayload {
+ content: RetainedStyleValueData::from_owned(value_list(content, 0, true)),
+ alt_text: if alt_text.is_empty() {
+ RetainedStyleValueData::none()
+ } else {
+ RetainedStyleValueData::from_owned(value_list(alt_text, 0, true))
+ },
},
- }))
+ ))))
}
fn parse_cursor_property(context: &ParseContext, values: &[ComponentValue]) -> ParseOutcome {
@@ -3317,11 +3340,11 @@ fn parse_cursor_property(context: &ParseContext, values: &[ComponentValue]) -> P
if tokens.has_next_token() {
return ParseOutcome::Invalid;
}
- cursors.push(StyleValueData::Cursor {
+ cursors.push(StyleValueData::Cursor(StyleValueBox::new(CursorPayload {
image: RetainedStyleValueData::from_owned(image),
x,
y,
- });
+ })));
}
ParseOutcome::Parsed(shared_style_value(match cursors.as_slice() {
[_] => cursors.remove(0),
@@ -3362,12 +3385,12 @@ fn parse_view_timeline_inset_from_stream(
}
fn retained_function(name: &[u8], arguments: Vec<RetainedStyleValueData>) -> StyleValueData {
- StyleValueData::Function {
+ StyleValueData::Function(StyleValueBox::new(FunctionPayload {
name: CssString::from_utf16(&name.iter().map(|byte| u16::from(*byte)).collect::<Vec<_>>()),
value: RetainedStyleValueData::from_owned(StyleValueData::Tuple {
values: RetainedStyleValueDataList::from_retained_values(arguments),
}),
- }
+ }))
}
fn parse_scroll_function(_context: &ParseContext, value: &ComponentValue) -> Option<StyleValueData> {
@@ -3996,18 +4019,20 @@ fn parse_positional_value_list_shorthand(
},
_ => return ParseOutcome::Invalid,
};
- ParseOutcome::Parsed(shared_style_value(StyleValueData::Shorthand {
- shorthand_property: property,
- sub_properties: RetainedPropertyIdList::from_property_ids(longhands.to_vec()),
- values: RetainedStyleValueDataList::from_retained_values(
- expanded.into_iter().map(RetainedStyleValueData::from_owned).collect(),
- ),
- }))
+ ParseOutcome::Parsed(shared_style_value(StyleValueData::Shorthand(StyleValueBox::new(
+ ShorthandPayload {
+ shorthand_property: property,
+ sub_properties: RetainedPropertyIdList::from_property_ids(longhands.to_vec()),
+ values: RetainedStyleValueDataList::from_retained_values(
+ expanded.into_iter().map(RetainedStyleValueData::from_owned).collect(),
+ ),
+ },
+ ))))
}
/// A longhand's initial value from Properties.json, parsed as a value of that property outside any
/// document.
-pub(crate) fn parse_initial_value(property: u16) -> Option<Arc<StyleValueData>> {
+pub(crate) fn parse_initial_value(property: u16) -> Option<StyleValueArc> {
let property_context = FfiValueParsingContext {
kind: FfiValueParsingContextKind::Property,
value: property,
@@ -4061,11 +4086,11 @@ fn retained_shorthand_value(
sub_properties: Vec<u16>,
values: Vec<RetainedStyleValueData>,
) -> StyleValueData {
- StyleValueData::Shorthand {
+ StyleValueData::Shorthand(StyleValueBox::new(ShorthandPayload {
shorthand_property: property,
sub_properties: RetainedPropertyIdList::from_property_ids(sub_properties),
values: RetainedStyleValueDataList::from_retained_values(values),
- }
+ }))
}
fn shorthand_with_initial_longhands(context: &ParseContext, property: u16) -> Option<StyleValueData> {
@@ -4183,18 +4208,20 @@ fn parse_unordered_shorthand(context: &ParseContext, property: u16, values: &[Co
}
parsed_order
};
- ParseOutcome::Parsed(shared_style_value(StyleValueData::Shorthand {
- shorthand_property: property,
- sub_properties: RetainedPropertyIdList::from_property_ids(
- order.iter().map(|&index| longhands[index]).collect(),
- ),
- values: RetainedStyleValueDataList::from_retained_values(
- order
- .into_iter()
- .map(|index| RetainedStyleValueData::from_owned(parsed[index].clone()))
- .collect(),
- ),
- }))
+ ParseOutcome::Parsed(shared_style_value(StyleValueData::Shorthand(StyleValueBox::new(
+ ShorthandPayload {
+ shorthand_property: property,
+ sub_properties: RetainedPropertyIdList::from_property_ids(
+ order.iter().map(|&index| longhands[index]).collect(),
+ ),
+ values: RetainedStyleValueDataList::from_retained_values(
+ order
+ .into_iter()
+ .map(|index| RetainedStyleValueData::from_owned(parsed[index].clone()))
+ .collect(),
+ ),
+ },
+ ))))
}
// https://drafts.csswg.org/css-overflow-4/#line-clamp
@@ -5451,9 +5478,10 @@ fn parse_background_shorthand(context: &ParseContext, values: &[ComponentValue])
return ParseOutcome::Invalid;
}
let (position_x, position_y) = if let Some(position) = parsed[5].take() {
- let StyleValueData::Shorthand { values, .. } = position else {
+ let StyleValueData::Shorthand(shorthand_payload) = position else {
return ParseOutcome::Invalid;
};
+ let ShorthandPayload { values, .. } = &*shorthand_payload;
let [x, y] = values.as_slice() else {
return ParseOutcome::Invalid;
};
@@ -5877,28 +5905,31 @@ pub(crate) fn unresolved_value_from_string(
unresolved_value(unresolved_source, values, presence)
}
+/// An unresolved value of `values`, whose source text `unresolved_source` is, and which it tokenizes again when its
+/// components are read.
pub(crate) fn unresolved_value(
unresolved_source: &[u16],
values: impl Into<ComponentValueList>,
presence: SubstitutionFunctionsPresence,
+) -> StyleValueData {
+ let values = values.into();
+ unresolved_value_with_components(unresolved_source, UnresolvedValueComponents::OfText(&values), presence)
+}
+
+/// An unresolved value whose source text is `unresolved_source`, made of `components`.
+fn unresolved_value_with_components(
+ unresolved_source: &[u16],
+ components: UnresolvedValueComponents<'_>,
+ presence: SubstitutionFunctionsPresence,
) -> StyleValueData {
let source_text = trim_component_value_boundary_whitespace(unresolved_source);
- let components = RetainedComponentValueList::from_values(values);
- if presence.attr {
- crate::css::parser::arbitrary_substitution::note_attr_names_read_by(components.as_slice());
- }
- StyleValueData::Unresolved {
+ StyleValueData::Unresolved(crate::css::style_value::UnresolvedBox::new(
+ TokenizerInput::Utf16(source_text),
components,
- source_text: CssString::from_utf16(source_text),
- presence_attr: presence.attr,
- presence_dashed_function: presence.dashed_function,
- presence_env: presence.env,
- presence_if: presence.if_,
- presence_inherit: presence.inherit,
- presence_var: presence.var,
- contains_attr_tainted_values: false,
- parsed_value: RetainedStyleValueData::none(),
- }
+ presence,
+ false,
+ RetainedStyleValueData::none(),
+ ))
}
pub(crate) fn unresolved_value_from_component_values(
@@ -5909,7 +5940,7 @@ pub(crate) fn unresolved_value_from_component_values(
&values,
crate::css::parser::component_value::ComponentSerializationMode::Retokenize,
);
- unresolved_value(&source, values, presence)
+ unresolved_value_with_components(&source, UnresolvedValueComponents::OfSerialization(&values), presence)
}
pub(crate) fn parse_css_value_with_source(
@@ -5950,20 +5981,37 @@ fn parse_css_value_after_substitution_scan(
if !declaration_values.is_empty() && !declaration_value_is_valid(declaration_values) {
return ParseOutcome::Invalid;
}
- let mut unresolved = unresolved_value(unresolved_source, values.to_vec(), substitution_presence);
- if let StyleValueData::Unresolved {
- source_text,
- contains_attr_tainted_values,
- ..
- } = &mut unresolved
- {
- *contains_attr_tainted_values = context.contains_attr_tainted_values;
+ // NB: A declaration's own text tokenizes to its values. A substituted value's text is the serialization of what
+ // it substituted to, which tokenizes back to it where its comments only keep tokens apart. Values without
+ // text are written as that serialization.
+ let serialization;
+ let mut unresolved = if context.is_substituted_value || unresolved_source.is_empty() {
+ let text = if context.is_substituted_value {
+ unresolved_source
+ } else {
+ serialization = crate::css::serialize::serialize_component_values_to_utf16(
+ values,
+ crate::css::parser::component_value::ComponentSerializationMode::Retokenize,
+ );
+ &serialization
+ };
+ unresolved_value_with_components(
+ text,
+ UnresolvedValueComponents::OfSerialization(values),
+ substitution_presence,
+ )
+ } else {
+ unresolved_value(unresolved_source, values.to_vec(), substitution_presence)
+ };
+ if let StyleValueData::Unresolved(unresolved_payload) = &mut unresolved {
+ unresolved_payload.payload_mut().contains_attr_tainted_values = context.contains_attr_tainted_values;
if property_id == property_id::CUSTOM && context.is_substituted_value {
let first_non_whitespace = unresolved_source
.iter()
.position(|unit| !matches!(*unit, 0x09 | 0x0a | 0x0c | 0x0d | 0x20))
.unwrap_or(unresolved_source.len());
- *source_text = CssString::from_utf16(&unresolved_source[first_non_whitespace..]);
+ *unresolved_payload = unresolved_payload
+ .with_source_text(TokenizerInput::Utf16(&unresolved_source[first_non_whitespace..]));
}
}
return ParseOutcome::Parsed(shared_style_value(unresolved));
@@ -6384,7 +6432,7 @@ pub unsafe extern "C" fn rust_parse_css_value(
Err(()) => ParseOutcome::NotHandled,
};
let (status, value) = match outcome {
- ParseOutcome::Parsed(value) => (FfiParseStatus::Parsed, Arc::into_raw(value).cast()),
+ ParseOutcome::Parsed(value) => (FfiParseStatus::Parsed, StyleValueArc::into_raw(value).cast()),
ParseOutcome::Invalid => (FfiParseStatus::Invalid, std::ptr::null()),
ParseOutcome::NotHandled => (FfiParseStatus::NotHandled, std::ptr::null()),
};
@@ -6580,7 +6628,8 @@ pub unsafe extern "C" fn rust_parse_entire_css_primitive_from_source(
return std::ptr::null();
};
if values[consumed..].iter().all(ComponentValue::is_whitespace) {
- Arc::into_raw(Arc::new(parsed)).cast()
+ crate::css::style_value_arc::StyleValueArc::into_raw(crate::css::style_value_arc::StyleValueArc::new(parsed))
+ .cast()
} else {
std::ptr::null()
}
@@ -6612,8 +6661,10 @@ mod tests {
source.encode_utf16().collect()
}
- fn retained_utf16(source: &CssString) -> Vec<u16> {
- source.units().to_vec()
+ fn retained_utf16(source: TokenizerInput<'_>) -> Vec<u16> {
+ let mut units = Vec::with_capacity(source.len());
+ source.append_to(&mut units);
+ units
}
fn context() -> ParseContext<'static> {
@@ -6688,14 +6739,14 @@ mod tests {
let ParseOutcome::Parsed(value) = parse(property, source) else {
panic!("shorthand should parse: {source}");
};
- let StyleValueData::Shorthand {
+ let StyleValueData::Shorthand(shorthand_payload) = &*value else {
+ panic!("value should be a shorthand: {source}");
+ };
+ let ShorthandPayload {
shorthand_property,
sub_properties,
values,
- } = &*value
- else {
- panic!("value should be a shorthand: {source}");
- };
+ } = &**shorthand_payload;
assert_eq!(*shorthand_property, property);
assert_eq!(sub_properties.as_slice(), longhands_for_shorthand(property));
assert_eq!(values.as_slice().len(), expected_values);
@@ -6715,12 +6766,12 @@ mod tests {
let ParseOutcome::Parsed(value) = parse(property, source) else {
panic!("shorthand should parse: {source}");
};
- let StyleValueData::Shorthand {
- sub_properties, values, ..
- } = &*value
- else {
+ let StyleValueData::Shorthand(shorthand_payload) = &*value else {
panic!("value should be a shorthand: {source}");
};
+ let ShorthandPayload {
+ sub_properties, values, ..
+ } = &**shorthand_payload;
if property == property_id::FLEX_FLOW {
assert_eq!(sub_properties.as_slice(), longhands_for_shorthand(property));
}
@@ -6798,12 +6849,12 @@ mod tests {
let ParseOutcome::Parsed(value) = parse(property, source) else {
panic!("shorthand should parse: {source}");
};
- let StyleValueData::Shorthand {
- sub_properties, values, ..
- } = &*value
- else {
+ let StyleValueData::Shorthand(shorthand_payload) = &*value else {
panic!("value should be a shorthand: {source}");
};
+ let ShorthandPayload {
+ sub_properties, values, ..
+ } = &**shorthand_payload;
assert_eq!(sub_properties.as_slice().len(), expected_properties);
assert_eq!(values.as_slice().len(), expected_properties);
}
@@ -6880,9 +6931,10 @@ mod tests {
let ParseOutcome::Parsed(value) = parse(property_id::BORDER_IMAGE, source) else {
panic!("shorthand should parse: {source}");
};
- let StyleValueData::Shorthand { values, .. } = &*value else {
+ let StyleValueData::Shorthand(shorthand_payload) = &*value else {
panic!("value should be a shorthand: {source}");
};
+ let ShorthandPayload { values, .. } = &**shorthand_payload;
assert_eq!(values.as_slice().len(), 5);
}
for source in ["10 /", "10 / /", "10 / 2 /", "round round round"] {
@@ -6916,9 +6968,10 @@ mod tests {
let ParseOutcome::Parsed(value) = parse(property, source) else {
panic!("shorthand should parse: {source}");
};
- let StyleValueData::Shorthand { values, .. } = &*value else {
+ let StyleValueData::Shorthand(shorthand_payload) = &*value else {
panic!("value should be a shorthand: {source}");
};
+ let ShorthandPayload { values, .. } = &**shorthand_payload;
assert_eq!(values.as_slice().len(), expected_values);
}
for (property, source) in [
@@ -6957,9 +7010,10 @@ mod tests {
let ParseOutcome::Parsed(value) = parse(property, source) else {
panic!("shorthand should parse: {source}");
};
- let StyleValueData::Shorthand { values, .. } = &*value else {
+ let StyleValueData::Shorthand(shorthand_payload) = &*value else {
panic!("value should be a shorthand: {source}");
};
+ let ShorthandPayload { values, .. } = &**shorthand_payload;
assert_eq!(values.as_slice().len(), expected_values);
}
for (property, source) in [
@@ -7069,7 +7123,7 @@ mod tests {
));
assert!(matches!(
parse(property_id::COLOR_SCHEME, "var(--scheme)"),
- ParseOutcome::Parsed(value) if matches!(&*value, StyleValueData::Unresolved { presence_var: true, .. })
+ ParseOutcome::Parsed(value) if matches!(&*value, StyleValueData::Unresolved(unresolved) if unresolved.presence().var)
));
}
@@ -7188,22 +7242,22 @@ mod tests {
panic!("URL token should parse");
};
assert!(
- matches!(&*value, StyleValueData::Url { url, url_type: 0, .. } if url.ascii_bytes() == b"images/mask.svg#shape")
+ matches!(&*value, StyleValueData::Url(url) if url.url_type == 0 && url.url.ascii_bytes() == b"images/mask.svg#shape")
);
let value = component(
"src(\"font.woff2\" referrer-policy(no-referrer) integrity(\"sha256-value\") cross-origin(anonymous))",
);
- let StyleValueData::Url {
+ let StyleValueData::Url(url_payload) = parse_url_value(&context(), &value).expect("src() should parse") else {
+ panic!("src() should produce a URL");
+ };
+ let UrlPayload {
url,
url_type,
modifiers,
- } = parse_url_value(&context(), &value).expect("src() should parse")
- else {
- panic!("src() should produce a URL");
- };
+ } = &*url_payload;
assert_eq!(url.ascii_bytes(), b"font.woff2");
- assert_eq!(url_type, 1);
+ assert_eq!(*url_type, 1);
assert_eq!(
modifiers
.as_slice()
@@ -7268,7 +7322,7 @@ mod tests {
}
assert!(matches!(
parse(property_id::ANCHOR_NAME, "var(--anchor)"),
- ParseOutcome::Parsed(value) if matches!(&*value, StyleValueData::Unresolved { presence_var: true, .. })
+ ParseOutcome::Parsed(value) if matches!(&*value, StyleValueData::Unresolved(unresolved) if unresolved.presence().var)
));
}
@@ -7634,9 +7688,10 @@ mod tests {
.filter(|value| !value.is_whitespace())
.collect::<Vec<_>>();
let references = values.iter().collect::<Vec<_>>();
- let StyleValueData::Ratio { numerator, denominator } = parse_ratio_value(&references).unwrap() else {
+ let StyleValueData::Ratio(ratio_payload) = parse_ratio_value(&references).unwrap() else {
panic!("ratio should use its specialized wrapper");
};
+ let RatioPayload { numerator, denominator } = &*ratio_payload;
assert!(matches!(numerator.data(), StyleValueData::Number { value } if *value == 16.0));
assert!(matches!(denominator.data(), StyleValueData::Number { value } if *value == 9.0));
assert!(parse_ratio_value(&[&component("-1")]).is_none());
@@ -7752,15 +7807,13 @@ mod tests {
let ParseOutcome::Parsed(value) = parse(property, source) else {
panic!("substitution function should parse: {source}");
};
- let StyleValueData::Unresolved {
- source_text,
- presence_attr,
- presence_var,
- ..
- } = &*value
- else {
+ let StyleValueData::Unresolved(unresolved_payload) = &*value else {
panic!("substitution function should produce an unresolved value: {source}");
};
+ let unresolved_payload: &crate::css::style_value::UnresolvedPayload = unresolved_payload;
+ let source_text = unresolved_payload.source_text();
+ let presence_attr = &unresolved_payload.presence().attr;
+ let presence_var = &unresolved_payload.presence().var;
assert_eq!(retained_utf16(source_text), utf16(source));
assert_eq!(*presence_attr, expected_attr);
assert_eq!(*presence_var, expected_var);
@@ -7784,9 +7837,11 @@ mod tests {
else {
panic!("attr() should parse");
};
- let StyleValueData::Unresolved { source_text, .. } = &*value else {
+ let StyleValueData::Unresolved(unresolved_payload) = &*value else {
panic!("attr() should remain unresolved");
};
+ let unresolved_payload: &crate::css::style_value::UnresolvedPayload = unresolved_payload;
+ let source_text = unresolved_payload.source_text();
assert_eq!(retained_utf16(source_text), utf16("attr( foo )"));
}
@@ -7799,16 +7854,16 @@ mod tests {
else {
panic!("custom property should parse");
};
- let StyleValueData::Unresolved {
- components,
- source_text,
- ..
- } = &*value
- else {
+ let StyleValueData::Unresolved(unresolved_payload) = &*value else {
panic!("custom property should produce an unresolved value");
};
+ let source_text = unresolved_payload.source_text();
assert_eq!(retained_utf16(source_text), utf16("10\\70 x"));
- assert_eq!(components.as_slice(), values.as_slice());
+ // NB: The value's source text is its declaration's, without the whitespace around it.
+ assert!(crate::css::style_value::components_equal(
+ &unresolved_payload.components(),
+ crate::css::parser::component_value::trim_whitespace(&values)
+ ));
let source = utf16("a/* comment */");
let values = consume_a_list_of_component_values(tokenize_for_parser(&source)).unwrap();
@@ -7817,10 +7872,13 @@ mod tests {
else {
panic!("custom property should parse");
};
- let StyleValueData::Unresolved { components, .. } = &*value else {
+ let StyleValueData::Unresolved(unresolved_payload) = &*value else {
panic!("custom property should produce an unresolved value");
};
- assert_eq!(components.as_slice(), values.as_slice());
+ assert!(crate::css::style_value::components_equal(
+ &unresolved_payload.components(),
+ &values
+ ));
assert!(matches!(
parse(property_id::CUSTOM, "inherit"),
ParseOutcome::Parsed(value) if matches!(&*value, StyleValueData::Keyword { keyword: keyword::INHERIT })
diff --git a/Libraries/LibWeb/Rust/src/css/property_rule.rs b/Libraries/LibWeb/Rust/src/css/property_rule.rs
index e928e4788cb..07a16328e0d 100644
--- a/Libraries/LibWeb/Rust/src/css/property_rule.rs
+++ b/Libraries/LibWeb/Rust/src/css/property_rule.rs
@@ -7,7 +7,7 @@
use crate::css::css_string::CssString;
use crate::css::ffi_support::FfiUtf16View;
use crate::css::parser::syntax::SyntaxNode;
-use crate::css::style_value::StyleValueData;
+use crate::css::style_value_arc::StyleValueArc;
use std::ffi::c_void;
use std::sync::Arc;
@@ -16,7 +16,7 @@ pub struct PropertyRuleData {
pub(crate) syntax_source: CssString,
pub(crate) syntax: Arc<SyntaxNode>,
pub(crate) inherits: bool,
- pub(crate) initial_value: Option<Arc<StyleValueData>>,
+ pub(crate) initial_value: Option<StyleValueArc>,
}
const _: () = {
@@ -45,6 +45,6 @@ pub extern "C" fn rust_property_rule_view(rule: &PropertyRuleData) -> FfiPropert
initial_value: rule
.initial_value
.as_ref()
- .map_or(std::ptr::null(), |value| Arc::as_ptr(value).cast()),
+ .map_or(std::ptr::null(), |value| StyleValueArc::as_ptr(value).cast()),
}
}
diff --git a/Libraries/LibWeb/Rust/src/css/retained_fly_string.rs b/Libraries/LibWeb/Rust/src/css/retained_fly_string.rs
index 306aecd5251..7fb5b464285 100644
--- a/Libraries/LibWeb/Rust/src/css/retained_fly_string.rs
+++ b/Libraries/LibWeb/Rust/src/css/retained_fly_string.rs
@@ -32,11 +32,6 @@ impl RetainedUtf16FlyString {
self.raw
}
- /// Return the retained identity, excluding the no-string sentinel.
- pub(crate) fn optional_raw(&self) -> Option<usize> {
- (self.raw != 0).then_some(self.raw)
- }
-
pub(crate) fn raw_word(&self) -> &usize {
&self.raw
}
diff --git a/Libraries/LibWeb/Rust/src/css/rule.rs b/Libraries/LibWeb/Rust/src/css/rule.rs
index e67c4a40f44..6c6a375bd9b 100644
--- a/Libraries/LibWeb/Rust/src/css/rule.rs
+++ b/Libraries/LibWeb/Rust/src/css/rule.rs
@@ -22,13 +22,15 @@ use crate::css::parser::query_parser::{FfiQueryHandle, MatchResult};
use crate::css::parser::syntax_parser::{PageSelectorList, ParsedRuleList, ParsedStyleSheet};
use crate::css::property_rule::PropertyRuleData;
use crate::css::scope_selectors::ScopeSelectors;
+use crate::css::selector::{SelectorListRef, SelectorListView};
+use crate::css::selector_arena::{Nesting, NestingContext};
use crate::css::selector_operations::{
absolutize_selector_list, adapt_scope_end_selector_list, scope_root_selector_list,
};
use crate::css::selector_parser::{RustParsedSelectorList, StyleNestingParent};
use crate::css::style_rule::StyleRule;
use std::borrow::Cow;
-use std::cell::{Cell, Ref, RefCell, RefMut};
+use std::cell::{Cell, OnceCell, Ref, RefCell, RefMut};
use std::collections::{HashMap, HashSet};
use std::ffi::c_void;
use std::rc::{Rc, Weak};
@@ -133,7 +135,8 @@ pub(crate) enum RulePayload {
Function(Arc<FunctionSignature>),
FunctionDeclarations(Box<FfiDescriptorBlock>),
Container(Arc<ContainerConditionsData>),
- Scope(Arc<ScopeSelectors>),
+ /// The scope's selectors, which binding the rule's `&` to what encloses it replaces.
+ Scope(RefCell<Arc<ScopeSelectors>>),
}
// Parsed data remains immutable and thread-shareable. These records are
@@ -142,11 +145,44 @@ pub struct NativeRule {
identity: u64,
rule_type: NativeRuleType,
pub(crate) payload: RulePayload,
- children: Option<Rc<NativeRuleList>>,
- source_position: Option<(usize, usize)>,
- parent: RefCell<Weak<NativeRule>>,
- matching_selectors: RefCell<Option<MatchingSelectorCache>>,
- scope_end_selectors: RefCell<Option<Rc<RustParsedSelectorList>>>,
+ /// The rule's child rules: set as it is made for a group rule, and made empty when first asked
+ /// for, for a style rule without nested rules, as most are.
+ children: OnceCell<Rc<NativeRuleList>>,
+ /// The line and column the rule starts at, when it was parsed from text.
+ source_position: Option<(u32, u32)>,
+ parent: Cell<Weak<NativeRule>>,
+}
+
+/// `list` with each `&` replaced by what it names, and a selector relative to a scoping root
+/// prefixed with it, or `list` itself where nothing is.
+fn absolutized(list: &SelectorListRef) -> SelectorListRef {
+ fn tree(list: SelectorListView<'_>) -> Option<crate::css::selector_tree::SelectorList> {
+ let (kind, parents) = match list.nesting() {
+ Some(Nesting::Rule(parent)) => (
+ StyleNestingParent::Style,
+ tree(parent).unwrap_or_else(|| parent.to_tree()),
+ ),
+ Some(Nesting::Scope) => (StyleNestingParent::Scope, Default::default()),
+ // NB: A `&` outside any style rule or `@scope` names the scoping root.
+ Some(Nesting::Root) => (StyleNestingParent::None, Default::default()),
+ // NB: Only the selectors of a rule directly in `@scope` start with a combinator.
+ _ if list.iter().any(|selector| {
+ selector.compound_selectors().first().is_some_and(|first| {
+ !matches!(
+ first.combinator,
+ crate::css::selector::Combinator::None | crate::css::selector::Combinator::Descendant
+ )
+ })
+ }) =>
+ {
+ (StyleNestingParent::Scope, Default::default())
+ }
+ _ => return None,
+ };
+ absolutize_selector_list(&list.to_tree(), kind, &parents)
+ }
+ // NB: The trees name the atoms of the arenas they came from, which are live while it is packed.
+ tree(list.view()).map_or_else(|| list.clone(), |tree| SelectorListRef::pack(&tree))
}
#[cfg(test)]
@@ -154,16 +190,9 @@ thread_local! {
pub(crate) static RULE_OWNER_ALLOCATIONS: Cell<u64> = const { Cell::new(0) };
}
-struct MatchingSelectorCache {
- source: Arc<RustParsedSelectorList>,
- parent_kind: StyleNestingParent,
- parents: Option<Rc<RustParsedSelectorList>>,
- selectors: Rc<RustParsedSelectorList>,
-}
-
pub struct NativeRuleList {
rules: RefCell<Option<Vec<Rc<NativeRule>>>>,
- exposed_rules: RefCell<HashMap<usize, Rc<NativeRule>>>,
+ exposed_rules: RefCell<ExposedRules>,
identity_base: Cell<u64>,
// Document media results, never rule or declaration owners in the shared parsed graph.
media_results: Rc<RefCell<HashMap<u64, RuleMediaResults>>>,
@@ -174,6 +203,48 @@ pub struct NativeRuleList {
parsed_source: RefCell<Option<ParsedRuleList>>,
}
+/// The rules of a list the CSSOM has materialized one by one, by their index, before it
+/// materializes the whole list. Boxed, as most lists, those of the style rules among them, never
+/// expose one.
+#[derive(Clone, Default)]
+#[allow(clippy::box_collection, reason = "a box is one word where a map is six")]
+struct ExposedRules(Option<Box<HashMap<usize, Rc<NativeRule>>>>);
+
+impl ExposedRules {
+ fn get(&self, index: &usize) -> Option<&Rc<NativeRule>> {
+ self.0.as_ref()?.get(index)
+ }
+
+ fn insert(&mut self, index: usize, rule: Rc<NativeRule>) {
+ self.0.get_or_insert_default().insert(index, rule);
+ }
+
+ fn is_empty(&self) -> bool {
+ self.0.as_ref().is_none_or(|rules| rules.is_empty())
+ }
+
+ #[cfg(test)]
+ fn len(&self) -> usize {
+ self.0.as_ref().map_or(0, |rules| rules.len())
+ }
+
+ fn capacity(&self) -> usize {
+ self.0.as_ref().map_or(0, |rules| rules.capacity())
+ }
+
+ fn clear(&mut self) {
+ self.0 = None;
+ }
+
+ fn values(&self) -> impl Iterator<Item = &Rc<NativeRule>> {
+ self.0.iter().flat_map(|rules| rules.values())
+ }
+
+ fn drain(&mut self) -> impl Iterator<Item = Rc<NativeRule>> {
+ self.0.take().into_iter().flat_map(|rules| rules.into_values())
+ }
+}
+
#[derive(Clone, Default)]
struct RuleMediaResults {
matches: Vec<bool>,
@@ -195,22 +266,22 @@ impl NativeRule {
// Keyframe blocks contribute through their enclosing keyframes definition. Function
// declaration blocks can be nested in conditional groups, but belong to the function.
if self.rule_type == NativeRuleType::Keyframe {
- return self.parent.borrow().upgrade().map(|parent| parent.identity);
+ return self.parent().map(|parent| parent.identity);
}
if self.rule_type == NativeRuleType::FunctionDeclarations {
- let mut parent = self.parent.borrow().upgrade();
+ let mut parent = self.parent();
while let Some(rule) = parent {
if rule.rule_type == NativeRuleType::Function {
return Some(rule.identity);
}
- parent = rule.parent.borrow().upgrade();
+ parent = rule.parent();
}
return None;
}
Some(self.identity)
}
- pub(crate) fn cascade_declarations(&self) -> Option<Arc<crate::css::declaration_block::DeclarationBlockData>> {
+ pub(crate) fn cascade_declarations(&self) -> Option<crate::css::declaration_block::SharedDeclarationBlock> {
match &self.payload {
RulePayload::Style(style) => Some(style.declarations.data()),
RulePayload::NestedDeclarations(declarations) => Some(declarations.data()),
@@ -226,16 +297,96 @@ impl NativeRule {
}
pub(crate) fn set_selector_text(&self, input: TokenizerInput<'_>, sheet_rules: Option<&NativeRuleList>) -> bool {
- let mut prefixes = Vec::new();
+ let mut declared = Vec::new();
if let Some(sheet_rules) = sheet_rules {
- sheet_rules.for_each_namespace(|namespace| prefixes.push(namespace.prefix.clone()));
+ sheet_rules
+ .for_each_namespace(|namespace| declared.push((namespace.prefix.clone(), namespace.uri.clone())));
}
- let namespaces: Vec<_> = prefixes
+ let namespaces: Vec<_> = declared
.iter()
- .map(|prefix| TokenizerInput::Utf16(prefix.units()))
+ .map(|(prefix, _)| TokenizerInput::Utf16(prefix.units()))
.collect();
- self.style_rule()
- .set_selector_text(input, &namespaces, self.nesting_parent_kind())
+ let declarations = crate::css::selector_arena::NamespaceDeclarations::of_texts(
+ declared.iter().map(|(prefix, uri)| (prefix.units(), uri.units())),
+ );
+ if !self
+ .style_rule()
+ .set_selector_text(input, &namespaces, declarations, self.nesting_parent_kind())
+ {
+ return false;
+ }
+ // NB: The new selectors name the parent with `&`, and the nested rules' name these.
+ self.bind_nesting();
+ true
+ }
+
+ /// Binds each `&` in the selectors of the rule, and of the rules nested in it, to what encloses
+ /// it, as placing the rule or changing what encloses it does. Selectors already naming that
+ /// stay as they are.
+ pub(crate) fn bind_nesting(&self) {
+ let parent = self.parent();
+ let parent_selectors = parent
+ .as_ref()
+ .filter(|parent| parent.rule_type == NativeRuleType::Style)
+ .map(|parent| parent.style_rule().selectors());
+ let parent = match (&parent, &parent_selectors) {
+ (_, Some(selectors)) => NestingContext::Rule(&selectors.selectors),
+ (Some(parent), None) if parent.rule_type == NativeRuleType::Scope => NestingContext::Scope,
+ _ => NestingContext::Root,
+ };
+ let nesting = self.nesting_parent();
+ let nesting_selectors = nesting
+ .as_ref()
+ .filter(|rule| rule.rule_type == NativeRuleType::Style)
+ .map(|rule| rule.style_rule().selectors());
+ let context = match (&nesting, &nesting_selectors) {
+ (_, Some(selectors)) => NestingContext::Rule(&selectors.selectors),
+ (Some(_), None) => NestingContext::Scope,
+ (None, _) => NestingContext::Root,
+ };
+ self.bind_nesting_in(context, parent);
+ }
+
+ /// Binds as [`Self::bind_nesting`] does, where a `&` names `context`, and one in a
+ /// `<scope-start>` names `parent`, what the rule is directly in.
+ fn bind_nesting_in(&self, context: NestingContext<'_>, parent: NestingContext<'_>) {
+ match &self.payload {
+ RulePayload::Style(style) => {
+ let selectors = style.selectors();
+ if !selectors.selectors.is_nested_in(context) {
+ style.replace_selectors(Arc::new(RustParsedSelectorList {
+ selectors: selectors.selectors.nested_in(context),
+ }));
+ }
+ let selectors = style.selectors();
+ let own = NestingContext::Rule(&selectors.selectors);
+ self.bind_children(own, own);
+ }
+ RulePayload::Scope(scope) => {
+ let current = scope.borrow().clone();
+ if let Some(start) = &current.start
+ && !start.selectors.is_nested_in(parent)
+ {
+ *scope.borrow_mut() = Arc::new(ScopeSelectors {
+ start: Some(Arc::new(RustParsedSelectorList {
+ selectors: start.selectors.nested_in(parent),
+ })),
+ end: current.end.clone(),
+ });
+ }
+ self.bind_children(NestingContext::Scope, NestingContext::Scope);
+ }
+ _ => self.bind_children(context, NestingContext::Root),
+ }
+ }
+
+ fn bind_children(&self, context: NestingContext<'_>, parent: NestingContext<'_>) {
+ let Some(children) = self.children.get() else {
+ return;
+ };
+ for index in 0..children.len() {
+ children.rule_at(index).bind_nesting_in(context, parent);
+ }
}
fn nesting_parent_kind(&self) -> StyleNestingParent {
@@ -249,126 +400,85 @@ impl NativeRule {
}
fn nesting_parent(&self) -> Option<Rc<NativeRule>> {
- let mut parent = self.parent.borrow().upgrade();
+ let mut parent = self.parent();
while let Some(rule) = parent {
if matches!(rule.rule_type, NativeRuleType::Style | NativeRuleType::Scope) {
return Some(rule);
}
- parent = rule.parent.borrow().upgrade();
+ parent = rule.parent();
}
None
}
+ /// The rule that holds this one, while it is held.
+ pub(crate) fn parent(&self) -> Option<Rc<NativeRule>> {
+ let parent = self.parent.take();
+ let upgraded = parent.upgrade();
+ self.parent.set(parent);
+ upgraded
+ }
+
+ pub(crate) fn set_parent(&self, parent: Weak<NativeRule>) {
+ self.parent.set(parent);
+ }
+
/// The rule's child rules, for a grouping rule.
pub(crate) fn child_rules(&self) -> Option<&Rc<NativeRuleList>> {
- self.children.as_ref()
+ if self.rule_type != NativeRuleType::Style {
+ return self.children.get();
+ }
+ Some(self.children.get_or_init(|| {
+ let children = NativeRuleList::new(Vec::new(), None);
+ // SAFETY: Every rule lives in the Rc `with_identity` made it in.
+ let this = unsafe {
+ Rc::increment_strong_count(std::ptr::from_ref(self));
+ Rc::from_raw(std::ptr::from_ref(self))
+ };
+ *children.owner.borrow_mut() = Rc::downgrade(&this);
+ children
+ }))
}
- pub(crate) fn matching_selectors(&self) -> Rc<RustParsedSelectorList> {
- let parent = self.nesting_parent();
- let parent_kind = parent.as_ref().map_or(StyleNestingParent::None, |parent| {
- if parent.rule_type == NativeRuleType::Style {
- StyleNestingParent::Style
- } else {
- StyleNestingParent::Scope
- }
- });
- let parents = if parent_kind == StyleNestingParent::Style {
- Some(parent.as_ref().unwrap().matching_selectors())
- } else {
- None
- };
+ /// The selectors the rule matches by with each `&` replaced by what it names, as DevTools and
+ /// rule dumps show them. Nested declarations match by their parent's.
+ pub(crate) fn absolutized_selectors(&self) -> SelectorListRef {
if self.rule_type == NativeRuleType::NestedDeclarations {
- if let Some(parents) = parents {
- return parents;
+ let parent = self
+ .nesting_parent()
+ .expect("nested declarations are inside a style rule or `@scope`");
+ if parent.rule_type == NativeRuleType::Style {
+ return parent.absolutized_selectors();
}
- assert_eq!(parent_kind, StyleNestingParent::Scope);
// https://drafts.csswg.org/css-cascade-6/#scoped-declarations
// Declarations may be used directly with the body of a @scope rule. Contiguous runs of declarations are
// wrapped in nested declarations rules, which match the scoping root with zero specificity.
- return Rc::new(RustParsedSelectorList {
- selectors: scope_root_selector_list(),
- });
- }
- let RulePayload::Style(style) = &self.payload else {
- unreachable!()
- };
- let source = style.selectors();
- self.cached_matching_selectors(source, parent_kind, parents)
- }
-
- fn cached_matching_selectors(
- &self,
- source: Arc<RustParsedSelectorList>,
- parent_kind: StyleNestingParent,
- parents: Option<Rc<RustParsedSelectorList>>,
- ) -> Rc<RustParsedSelectorList> {
- if let Some(cached) = self.matching_selectors.borrow().as_ref()
- && Arc::ptr_eq(&source, &cached.source)
- && parent_kind == cached.parent_kind
- && match (&parents, &cached.parents) {
- (Some(parents), Some(cached)) => Rc::ptr_eq(parents, cached),
- (None, None) => true,
- _ => false,
- }
- {
- return cached.selectors.clone();
+ return SelectorListRef::pack(&scope_root_selector_list());
}
- let empty: crate::css::selector::SelectorList = Box::new([]);
- let parent_selectors = parents.as_ref().map_or(&empty, |parents| &parents.selectors);
- let selectors = Rc::new(RustParsedSelectorList {
- selectors: absolutize_selector_list(&source.selectors, parent_kind, parent_selectors)
- .unwrap_or_else(|| source.selectors.clone()),
- });
- *self.matching_selectors.borrow_mut() = Some(MatchingSelectorCache {
- source,
- parent_kind,
- parents,
- selectors: selectors.clone(),
- });
- selectors
+ absolutized(&self.style_rule().selectors().selectors)
}
- fn scope(&self) -> &ScopeSelectors {
+ fn scope(&self) -> Arc<ScopeSelectors> {
match &self.payload {
- RulePayload::Scope(scope) | RulePayload::Import { scope: Some(scope), .. } => scope,
+ RulePayload::Scope(scope) => scope.borrow().clone(),
+ RulePayload::Import { scope: Some(scope), .. } => scope.clone(),
_ => unreachable!(),
}
}
- pub(crate) fn scope_start_selectors(&self) -> Option<Rc<RustParsedSelectorList>> {
- let source = self.scope().start.as_ref()?.clone();
- // Imports start a new sheet. A scope prelude uses its immediate enclosing rule's context.
- let parent = if self.rule_type == NativeRuleType::Scope {
- self.parent.borrow().upgrade()
- } else {
- None
- };
- let parent_kind = parent
- .as_ref()
- .map_or(StyleNestingParent::None, |parent| match parent.rule_type {
- NativeRuleType::Style => StyleNestingParent::Style,
- NativeRuleType::Scope => StyleNestingParent::Scope,
- _ => StyleNestingParent::None,
- });
- let parents = if parent_kind == StyleNestingParent::Style {
- Some(parent.as_ref().unwrap().matching_selectors())
- } else {
- None
- };
- Some(self.cached_matching_selectors(source, parent_kind, parents))
+ /// The `<scope-start>` of a scope rule or scoped import, absolutized as
+ /// [`Self::absolutized_selectors`] are.
+ pub(crate) fn absolutized_scope_start(&self) -> Option<SelectorListRef> {
+ Some(absolutized(&self.scope().start.as_ref()?.selectors))
}
- pub(crate) fn scope_end_selectors(&self) -> Option<Rc<RustParsedSelectorList>> {
- let source = self.scope().end.as_ref()?;
- if let Some(cached) = self.scope_end_selectors.borrow().as_ref() {
- return Some(cached.clone());
- }
- let selectors = Rc::new(RustParsedSelectorList {
- selectors: adapt_scope_end_selector_list(&source.selectors),
- });
- *self.scope_end_selectors.borrow_mut() = Some(selectors.clone());
- Some(selectors)
+ /// The `<scope-end>` of a scope rule or scoped import, relative to its scoping root.
+ pub(crate) fn absolutized_scope_end(&self) -> Option<SelectorListRef> {
+ let scope = self.scope();
+ let end = scope.end.as_ref()?;
+ // NB: The tree names the atoms of the end's arena, which is live while it is packed again.
+ Some(SelectorListRef::pack(&adapt_scope_end_selector_list(
+ &end.selectors.view().to_tree(),
+ )))
}
fn internal_layer_name(&self) -> Option<Cow<'_, [u16]>> {
@@ -403,17 +513,18 @@ impl NativeRule {
identity,
rule_type,
payload,
- children,
- source_position,
- parent: RefCell::new(Weak::new()),
- matching_selectors: RefCell::new(None),
- scope_end_selectors: RefCell::new(None),
+ children: children.map_or_else(OnceCell::new, OnceCell::from),
+ source_position: source_position.map(|(line, column)| {
+ let narrow = |value: usize| u32::try_from(value).expect("style sheet text exceeds u32");
+ (narrow(line), narrow(column))
+ }),
+ parent: Cell::new(Weak::new()),
});
- if let Some(children) = &rule.children {
+ if let Some(children) = rule.children.get() {
*children.owner.borrow_mut() = Rc::downgrade(&rule);
if let Some(materialized) = children.rules.borrow().as_ref() {
for child in materialized {
- *child.parent.borrow_mut() = Rc::downgrade(&rule);
+ child.set_parent(Rc::downgrade(&rule));
}
}
}
@@ -440,7 +551,7 @@ impl NativeRuleList {
let import_media = source.import_media.borrow().clone();
self.clear();
for rule in rules.iter().flatten().chain(exposed.values()) {
- *rule.parent.borrow_mut() = self.owner.borrow().clone();
+ rule.set_parent(self.owner.borrow().clone());
}
self.rules.replace(rules);
self.exposed_rules.replace(exposed);
@@ -465,7 +576,7 @@ impl NativeRuleList {
}
self.materialized_rules_mut().retain(|rule| {
if rule.rule_type == NativeRuleType::Import {
- *rule.parent.borrow_mut() = Weak::new();
+ rule.set_parent(Weak::new());
false
} else {
true
@@ -481,7 +592,12 @@ impl NativeRuleList {
}
pub(crate) fn insert(&self, index: usize, rule: Rc<NativeRule>) {
- *rule.parent.borrow_mut() = self.owner.borrow().clone();
+ rule.set_parent(self.owner.borrow().clone());
+ // NB: A rule parsed for a place inside a style rule or `@scope` names it with `&` once
+ // placed there.
+ if rule.nesting_parent().is_some() {
+ rule.bind_nesting();
+ }
self.materialized_rules_mut().insert(index, rule);
}
@@ -533,7 +649,12 @@ impl NativeRuleList {
pub(crate) fn remove(&self, index: usize) {
let rule = self.materialized_rules_mut().remove(index);
- *rule.parent.borrow_mut() = Weak::new();
+ let was_nested = rule.nesting_parent().is_some();
+ rule.set_parent(Weak::new());
+ // NB: A rule taken out of a style rule or `@scope` names neither with `&` any more.
+ if was_nested {
+ rule.bind_nesting();
+ }
}
pub(crate) fn validate_removal(&self, index: usize) -> RuleRemovalResult {
@@ -557,11 +678,11 @@ impl NativeRuleList {
pub(crate) fn clear(&self) {
if let Some(rules) = self.rules.replace(Some(Vec::new())) {
for rule in rules {
- *rule.parent.borrow_mut() = Weak::new();
+ rule.set_parent(Weak::new());
}
} else {
- for rule in self.exposed_rules.borrow_mut().drain().map(|(_, rule)| rule) {
- *rule.parent.borrow_mut() = Weak::new();
+ for rule in self.exposed_rules.borrow_mut().drain() {
+ rule.set_parent(Weak::new());
}
}
}
@@ -611,7 +732,7 @@ impl NativeRuleList {
.as_ref()
.unwrap()
.materialize_at(index, self);
- *rule.parent.borrow_mut() = self.owner.borrow().clone();
+ rule.set_parent(self.owner.borrow().clone());
if let Some(result) = self.media_results.borrow_mut().remove(&rule.identity) {
match &rule.payload {
RulePayload::Media { list } => {
@@ -702,17 +823,35 @@ impl NativeRuleList {
/// Immutable parsing input that can outlive edits to the document-local rule graph.
pub struct NativeNamespaceContext {
pub(crate) prefixes: Box<[crate::css::css_string::CssString]>,
+ /// The namespace each prefix names, in the order of `prefixes`.
+ pub(crate) uris: Box<[crate::css::css_string::CssString]>,
+}
+
+impl NativeNamespaceContext {
+ /// The declarations, as the selectors of a sheet carry them.
+ pub(crate) fn declarations(&self) -> crate::css::selector_arena::NamespaceDeclarations {
+ crate::css::selector_arena::NamespaceDeclarations::of_texts(
+ self.prefixes
+ .iter()
+ .zip(&self.uris)
+ .map(|(prefix, uri)| (prefix.units(), uri.units())),
+ )
+ }
}
#[unsafe(no_mangle)]
pub extern "C" fn rust_rule_list_namespace_context(list: &NativeRuleList) -> *const NativeNamespaceContext {
- let mut prefixes = Vec::new();
- list.for_each_namespace(|namespace| prefixes.push(namespace.prefix.clone()));
+ let (mut prefixes, mut uris) = (Vec::new(), Vec::new());
+ list.for_each_namespace(|namespace| {
+ prefixes.push(namespace.prefix.clone());
+ uris.push(namespace.uri.clone());
+ });
if prefixes.is_empty() {
return std::ptr::null();
}
Arc::into_raw(Arc::new(NativeNamespaceContext {
prefixes: prefixes.into(),
+ uris: uris.into(),
}))
}
@@ -755,7 +894,7 @@ pub extern "C" fn rust_keyframes_find_rule(rule: &NativeRule, selector: FfiUtf16
};
frame.keys() == selectors
};
- let children = rule.children.as_ref().unwrap();
+ let children = rule.child_rules().unwrap();
if let Some(rules) = children.rules.borrow().as_ref() {
return rules.iter().rposition(|frame| matches(frame)).unwrap_or(usize::MAX);
}
@@ -814,12 +953,12 @@ pub extern "C" fn rust_rule_containing_function(rule: &NativeRule) -> *const Nat
if rule.rule_type == NativeRuleType::Function {
return rule;
}
- let mut parent = rule.parent.borrow().upgrade();
+ let mut parent = rule.parent();
while let Some(rule) = parent {
if rule.rule_type == NativeRuleType::Function {
return Rc::as_ptr(&rule);
}
- parent = rule.parent.borrow().upgrade();
+ parent = rule.parent();
}
std::ptr::null()
}
@@ -848,9 +987,8 @@ pub extern "C" fn rust_rule_selectors(rule: &NativeRule) -> *const c_void {
/// `rust_parsed_selector_list_destroy` on the same thread.
#[unsafe(no_mangle)]
pub extern "C" fn rust_rule_matching_selectors(rule: &NativeRule) -> *mut c_void {
- let selectors = rule.matching_selectors();
Box::into_raw(Box::new(RustParsedSelectorList {
- selectors: selectors.selectors.clone(),
+ selectors: rule.absolutized_selectors(),
}))
.cast()
}
@@ -859,26 +997,17 @@ pub extern "C" fn rust_rule_matching_selectors(rule: &NativeRule) -> *mut c_void
/// `rust_parsed_selector_list_destroy`; null means the start is omitted.
#[unsafe(no_mangle)]
pub extern "C" fn rust_rule_scope_start_selectors(rule: &NativeRule) -> *mut c_void {
- rule.scope_start_selectors()
- .map(|selectors| {
- Box::into_raw(Box::new(RustParsedSelectorList {
- selectors: selectors.selectors.clone(),
- }))
- .cast()
+ rule.absolutized_scope_start()
+ .map_or(std::ptr::null_mut(), |selectors| {
+ Box::into_raw(Box::new(RustParsedSelectorList { selectors })).cast()
})
- .unwrap_or(std::ptr::null_mut())
}
#[unsafe(no_mangle)]
pub extern "C" fn rust_rule_scope_end_selectors(rule: &NativeRule) -> *mut c_void {
- rule.scope_end_selectors()
- .map(|selectors| {
- Box::into_raw(Box::new(RustParsedSelectorList {
- selectors: selectors.selectors.clone(),
- }))
- .cast()
- })
- .unwrap_or(std::ptr::null_mut())
+ rule.absolutized_scope_end().map_or(std::ptr::null_mut(), |selectors| {
+ Box::into_raw(Box::new(RustParsedSelectorList { selectors })).cast()
+ })
}
/// # Safety
@@ -957,12 +1086,12 @@ pub extern "C" fn rust_rule_external_memory_size(rule: &NativeRule) -> usize {
}
RulePayload::Keyframes(name) => {
let mut size = size_of_val(name.borrow().units());
- let _ = rule.children.as_ref().unwrap().visit_rules(&mut |frame| {
+ let _ = rule.child_rules().unwrap().visit_rules(&mut |frame| {
let (keys, declarations) = frame.keyframe();
size = size
.saturating_add(size_of::<crate::css::keyframes::KeyframeData>())
.saturating_add(size_of_val(keys))
- .saturating_add(declarations.external_memory_size());
+ .saturating_add(declarations.heap_bytes());
std::ops::ControlFlow::Continue(())
});
size
@@ -987,8 +1116,8 @@ pub unsafe extern "C" fn rust_rule_payload(rule: &NativeRule) -> FfiRulePayload<
let mut result = FfiRulePayload::default();
if let Some((line, column)) = rule.source_position {
result.has_source_position = true;
- result.start_line = line;
- result.start_column = column;
+ result.start_line = line as usize;
+ result.start_column = column as usize;
}
match &rule.payload {
RulePayload::Style(_) => {}
@@ -1022,7 +1151,7 @@ pub unsafe extern "C" fn rust_rule_payload(rule: &NativeRule) -> FfiRulePayload<
RulePayload::Property(data) => result.property = Arc::as_ptr(data),
RulePayload::Function(data) => result.function_signature = Arc::as_ptr(data),
RulePayload::Container(data) => result.container = Arc::as_ptr(data),
- RulePayload::Scope(data) => result.scope = Arc::as_ptr(data),
+ RulePayload::Scope(data) => result.scope = Arc::as_ptr(&data.borrow()),
}
result
}
@@ -1035,6 +1164,22 @@ pub extern "C" fn rust_rule_set_page_selectors(rule: &NativeRule, selectors: Arc
*current.borrow_mut() = selectors.to_arc();
}
+/// The text the list's sheet was parsed from, when the list holds a parsed sheet, which the parse
+/// shares between the documents it was parsed for.
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_rule_list_source_text(list: &NativeRuleList, has_text: &mut bool) -> usize {
+ let parsed = list.parsed_source.borrow();
+ let Some(sheet) = parsed.as_ref().and_then(|parsed| parsed.root_sheet()) else {
+ *has_text = false;
+ return ak::Utf16String::from_utf16(&[]).into_raw();
+ };
+ *has_text = true;
+ match sheet.source_text().units() {
+ crate::css::css_tokenizer::TokenizerInput::Latin1(bytes) => ak::Utf16String::from_latin1(bytes).into_raw(),
+ crate::css::css_tokenizer::TokenizerInput::Utf16(units) => ak::Utf16String::from_utf16(units).into_raw(),
+ }
+}
+
#[unsafe(no_mangle)]
pub extern "C" fn rust_rule_children(rule: &NativeRule) -> *const NativeRuleList {
rule.child_rules().map_or(std::ptr::null(), Rc::as_ptr)
diff --git a/Libraries/LibWeb/Rust/src/css/rule/compilation.rs b/Libraries/LibWeb/Rust/src/css/rule/compilation.rs
index 5fbfeddcabd..385c84da69a 100644
--- a/Libraries/LibWeb/Rust/src/css/rule/compilation.rs
+++ b/Libraries/LibWeb/Rust/src/css/rule/compilation.rs
@@ -286,7 +286,7 @@ fn find_rule_path(
find_rule_path(imported.rules(), &imported, identity, path)
} else {
rule.children
- .as_ref()
+ .get()
.is_some_and(|children| find_rule_path(children, sheet, identity, path))
};
if found {
@@ -356,6 +356,39 @@ pub unsafe extern "C" fn rust_style_sheet_compile(
publisher.finish();
}
+/// Compile `sheet`, a user agent sheet, into the rules the process keeps, unless the process already did: the documents
+/// of the process read those rather than each recording them.
+///
+/// # Safety
+///
+/// As for rust_style_sheet_compile, which `source`, `environment` and `callbacks` are given to.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_user_agent_style_sheet_publish(
+ sheet: &NativeStyleSheet,
+ source: *const c_void,
+ environment: FfiMediaEnvironment<'_>,
+ callbacks: &NativeCompilationCallbacks,
+) {
+ if crate::render_state::process_style().has_user_agent_sheet(sheet.identity()) {
+ return;
+ }
+ let publisher = Publisher::of_user_agent_sheet();
+ // SAFETY: Guaranteed by the caller.
+ let (host, source) = unsafe { CompilationHost::new(callbacks, source) };
+ // SAFETY: Guaranteed by the caller.
+ let environment = environment.borrow();
+ visit_compilation(
+ sheet,
+ 0,
+ NativeCompilationPurpose::Rules,
+ source,
+ environment,
+ host,
+ Some(&publisher),
+ );
+ crate::css::style::rule_writes::publish_user_agent_sheet(sheet.identity(), publisher.into_rules());
+}
+
/// Update the selectors of a style rule and its native descendants without materializing CSSOM.
///
/// # Safety
@@ -383,7 +416,6 @@ pub unsafe extern "C" fn rust_style_sheet_replace_selectors(
purpose: NativeCompilationPurpose::Selectors,
..Default::default()
};
- let mut target_sheet = sheet;
let mut target_source = source;
for entry in &path {
context = context.within(
@@ -396,7 +428,6 @@ pub unsafe extern "C" fn rust_style_sheet_replace_selectors(
);
if let Some(imported) = &entry.imported {
target_source = host.import_source(target_source, entry.rule.identity, imported);
- target_sheet = imported;
}
}
// Bind each ancestor and descendant once. Traversal inputs keep the new parent binding
@@ -406,7 +437,7 @@ pub unsafe extern "C" fn rust_style_sheet_replace_selectors(
while let Some((rule, context)) = pending.pop() {
let selectors = context.selectors.matching_selectors(RuleRef::Materialized(&rule));
if has_compiled_children(RuleRef::Materialized(&rule))
- && let Some(children) = &rule.children
+ && let Some(children) = rule.children.get()
{
let nested = context.within(
RuleRef::Materialized(&rule),
@@ -434,7 +465,7 @@ pub unsafe extern "C" fn rust_style_sheet_replace_selectors(
let published = publisher.host().published_rules();
for (rule, context, selectors) in affected {
if published.contains(publisher.sheet(), rule.identity) {
- publisher.replace_selectors(RuleRef::Materialized(&rule), target_sheet, &context, selectors);
+ publisher.replace_selectors(RuleRef::Materialized(&rule), &context, selectors);
continue;
}
// A previously empty selector list may become matchable. Publish that newly active
@@ -569,7 +600,7 @@ mod tests {
}
fn materialize(rules: &NativeRuleList) {
for rule in rules.materialized_rules().iter() {
- if let Some(children) = &rule.children {
+ if let Some(children) = rule.children.get() {
materialize(children);
}
}
@@ -630,7 +661,7 @@ mod tests {
fn media_at(sheet: &NativeStyleSheet, path: &[usize]) -> MediaList {
let mut rule = sheet.rules().rule_at(path[0]);
for &index in &path[1..] {
- rule = rule.children.as_ref().unwrap().rule_at(index);
+ rule = rule.child_rules().unwrap().rule_at(index);
}
match &rule.payload {
RulePayload::Media { list, .. } | RulePayload::Import { media: list, .. } => list.clone(),
@@ -687,7 +718,7 @@ mod tests {
fn media_changes_publish_only_affected_subtrees_with_document_local_baselines() {
let source = sheet(".unaffected {} @media (min-width: 100px) { .affected {} }");
let unaffected = source.rules().rule_at(0).identity;
- let affected = source.rules().rule_at(1).children.as_ref().unwrap().rule_at(0).identity;
+ let affected = source.rules().rule_at(1).child_rules().unwrap().rule_at(0).identity;
let mut first = crate::css::style_sheet::NativeMediaEvaluationState::default();
let mut second = crate::css::style_sheet::NativeMediaEvaluationState::default();
with_media_width(150.0, |environment| {
@@ -759,7 +790,7 @@ mod tests {
fn newly_loaded_imports_publish_conditions_on_the_next_media_evaluation() {
let source = sheet("@import 'child.css';");
let child = sheet("@media (min-width: 100px) { .target {} }");
- let target = child.rules().rule_at(0).children.as_ref().unwrap().rule_at(0).identity;
+ let target = child.rules().rule_at(0).child_rules().unwrap().rule_at(0).identity;
let mut state = crate::css::style_sheet::NativeMediaEvaluationState::default();
with_media_width(50.0, |environment| {
assert!(
@@ -922,7 +953,7 @@ mod tests {
assert_eq!(source.rules().materialized_rules().len(), 5);
let imported = source.rules().rule_at(1);
let outer = source.rules().rule_at(3);
- let anonymous = outer.children.as_ref().unwrap().rule_at(1);
+ let anonymous = outer.child_rules().unwrap().rule_at(1);
let name = |rule: &NativeRule| RuleRef::Materialized(rule).internal_layer_name().unwrap().into_owned();
let imported_name = name(&imported);
let anonymous_name = name(&anonymous);
@@ -972,23 +1003,39 @@ mod tests {
}
#[test]
- fn native_binding_caches_follow_selector_mutation_without_rebinding_scope_limits() {
+ fn selector_edits_bind_nested_selectors_without_rebinding_scope_limits() {
+ use crate::css::selector_arena::{Nesting, NestingContext};
let source = sheet(".親 { & > .子 {} @scope (& .根) to (.限) {} }");
let parent = source.rules().rule_at(0);
- let children = parent.children.as_ref().unwrap();
+ let children = parent.child_rules().unwrap();
let child = children.rule_at(0);
let scope = children.rule_at(1);
- let matching = child.matching_selectors();
- let start = scope.scope_start_selectors().unwrap();
- let end = scope.scope_end_selectors().unwrap();
- assert!(Rc::ptr_eq(&matching, &child.matching_selectors()));
- assert!(Rc::ptr_eq(&start, &scope.scope_start_selectors().unwrap()));
- assert!(Rc::ptr_eq(&end, &scope.scope_end_selectors().unwrap()));
+ let parsed_child = child.style_rule().selectors();
+ let parsed_scope = scope.scope();
+ // A parsed sheet's nested selectors name their parent's in the sheet's arena already.
+ let parent_selectors = parent.style_rule().selectors();
+ assert!(
+ parsed_child
+ .selectors
+ .is_nested_in(NestingContext::Rule(&parent_selectors.selectors))
+ );
let units: Vec<_> = ".新".encode_utf16().collect();
assert!(parent.set_selector_text(crate::css::css_tokenizer::TokenizerInput::Utf16(&units), None));
- assert!(!Rc::ptr_eq(&matching, &child.matching_selectors()));
- assert!(!Rc::ptr_eq(&start, &scope.scope_start_selectors().unwrap()));
- assert!(Rc::ptr_eq(&end, &scope.scope_end_selectors().unwrap()));
+ let parent_selectors = parent.style_rule().selectors();
+ let edited = NestingContext::Rule(&parent_selectors.selectors);
+ let child_selectors = child.style_rule().selectors();
+ assert!(!std::sync::Arc::ptr_eq(&parsed_child, &child_selectors));
+ assert!(child_selectors.selectors.is_nested_in(edited));
+ let Some(Nesting::Rule(named)) = child_selectors.selectors.view().nesting() else {
+ panic!("the child's `&` names a style rule");
+ };
+ assert_eq!(named.iter().next().unwrap().specificity().classes, 1);
+ let bound_scope = scope.scope();
+ assert!(bound_scope.start.as_ref().unwrap().selectors.is_nested_in(edited));
+ assert!(std::sync::Arc::ptr_eq(
+ parsed_scope.end.as_ref().unwrap(),
+ bound_scope.end.as_ref().unwrap()
+ ));
}
#[test]
@@ -996,9 +1043,9 @@ mod tests {
use crate::css::rule::rust_rule_list_clear;
fn ancestors(rule: &NativeRule) -> Vec<Rc<NativeRule>> {
let mut result = Vec::new();
- let mut parent = rule.parent.borrow().upgrade();
+ let mut parent = rule.parent();
while let Some(ancestor) = parent {
- parent = ancestor.parent.borrow().upgrade();
+ parent = ancestor.parent();
result.push(ancestor);
}
result
@@ -1007,9 +1054,9 @@ mod tests {
let roots = source.rules();
let leaf = {
let layer = roots.rule_at(0);
- let media = layer.children.as_ref().unwrap().rule_at(0);
- let scope = media.children.as_ref().unwrap().rule_at(0);
- scope.children.as_ref().unwrap().rule_at(0)
+ let media = layer.child_rules().unwrap().rule_at(0);
+ let scope = media.child_rules().unwrap().rule_at(0);
+ scope.child_rules().unwrap().rule_at(0)
};
let destination = roots.rule_at(1);
let retained = ancestors(&leaf);
@@ -1022,7 +1069,7 @@ mod tests {
assert_eq!(ancestors(&leaf).len(), 3);
drop(retained);
assert!(ancestors(&leaf).is_empty());
- let children = destination.children.as_ref().unwrap();
+ let children = destination.child_rules().unwrap();
children.insert(0, leaf.clone());
let reparented = ancestors(&leaf);
assert_eq!(reparented.len(), 1);
@@ -1050,11 +1097,11 @@ mod tests {
let media = list.rule_at(0);
assert_eq!(RULE_OWNER_ALLOCATIONS.get(), before + 1);
- let children = media.children.as_ref().unwrap();
+ let children = media.child_rules().unwrap();
let second = children.rule_at(1);
assert_eq!(RULE_OWNER_ALLOCATIONS.get(), before + 2);
assert!(Rc::ptr_eq(&second, &children.rule_at(1)));
- assert_eq!(second.parent.borrow().upgrade().unwrap().identity, media.identity);
+ assert_eq!(second.parent().unwrap().identity, media.identity);
path.clear();
assert!(list.find_path(second.identity, &mut path));
assert_eq!(path, [0, 1]);
@@ -1062,7 +1109,7 @@ mod tests {
let keyframes = list.rule_at(2);
assert_eq!(RULE_OWNER_ALLOCATIONS.get(), before + 3);
- let frames = keyframes.children.as_ref().unwrap();
+ let frames = keyframes.child_rules().unwrap();
let frame = frames.rule_at(1);
assert_eq!(RULE_OWNER_ALLOCATIONS.get(), before + 4);
assert!(frames.rules.borrow().is_none());
@@ -1072,10 +1119,10 @@ mod tests {
rust_rule_list_clear(list);
assert_eq!(RULE_OWNER_ALLOCATIONS.get(), before + 4);
- assert!(media.parent.borrow().upgrade().is_none());
- assert!(keyframes.parent.borrow().upgrade().is_none());
- assert_eq!(second.parent.borrow().upgrade().unwrap().identity, media.identity);
- assert_eq!(frame.parent.borrow().upgrade().unwrap().identity, keyframes.identity);
+ assert!(media.parent().is_none());
+ assert!(keyframes.parent().is_none());
+ assert_eq!(second.parent().unwrap().identity, media.identity);
+ assert_eq!(frame.parent().unwrap().identity, keyframes.identity);
}
#[test]
@@ -1086,7 +1133,7 @@ mod tests {
let old = sheet("@media all { .old { color: red; } .unread { color: blue; } } .other { width: 1px; }");
let media = old.rules().rule_at(0);
- let child = media.children.as_ref().unwrap().rule_at(0);
+ let child = media.child_rules().unwrap().rule_at(0);
let replacement = sheet("@media all { .new { color: green; } } .last { width: 2px; }");
let expected_identity = rust_rule_list_identity_at(replacement.rules(), 0);
let before = RULE_OWNER_ALLOCATIONS.get();
@@ -1095,12 +1142,12 @@ mod tests {
assert_eq!(RULE_OWNER_ALLOCATIONS.get(), before);
assert!(old.rules().rules.borrow().is_none());
assert!(replacement.rules().rules.borrow().is_none());
- assert!(media.parent.borrow().upgrade().is_none());
- assert_eq!(child.parent.borrow().upgrade().unwrap().identity, media.identity);
+ assert!(media.parent().is_none());
+ assert_eq!(child.parent().unwrap().identity, media.identity);
let new_media = old.rules().rule_at(0);
assert_eq!(new_media.identity, expected_identity);
assert_eq!(RULE_OWNER_ALLOCATIONS.get(), before + 1);
- assert!(new_media.children.as_ref().unwrap().rules.borrow().is_none());
+ assert!(new_media.child_rules().unwrap().rules.borrow().is_none());
}
#[test]
@@ -1264,7 +1311,6 @@ mod tests {
let add_sheet = |host: &crate::render_state::TestHost| {
crate::css::style::rule_writes::style_engine_add_sheet(
host.host(),
- 1,
crate::css::style::bridge::FfiCascadeOrigin::Author,
)
};
@@ -1340,7 +1386,10 @@ mod tests {
.successor(compiled_sheet, &source, import_identity);
// SAFETY: The test reaches the engine only between the host's calls.
let engine = unsafe { host.engine().get() };
- assert_eq!(engine.native_rule_id(next), Some(crate::css::style::program::RuleID(1)));
+ assert_eq!(
+ engine.native_rule_id(next),
+ Some(crate::css::style::pipeline::rule_store::RuleID(1))
+ );
let imported_host = crate::render_state::TestHost::new();
let imported_sheet = add_sheet(&imported_host);
compiled.set(0);
@@ -1378,7 +1427,7 @@ mod tests {
context: *const c_void,
_: *const f64,
count: usize,
- _: *const crate::css::declaration_block::DeclarationBlockData,
+ _: *const crate::css::declaration_block::DeclarationBlockHeader,
) {
assert_eq!(count, 1);
let definitions = unsafe { &*context.cast::<Definitions>() };
@@ -1467,11 +1516,11 @@ mod tests {
// Exposing one nested style rule must not replace the shared compilation path
// with a document-local graph for its siblings or descendants.
let layer = source.rules().rule_at(1);
- let style = layer.children.as_ref().unwrap().rule_at(0);
+ let style = layer.child_rules().unwrap().rule_at(0);
assert_eq!(RULE_OWNER_ALLOCATIONS.get(), rule_owners + 2);
assert!(source.rules().rules.borrow().is_none());
- assert!(layer.children.as_ref().unwrap().rules.borrow().is_none());
- assert!(style.children.as_ref().unwrap().rules.borrow().is_none());
+ assert!(layer.child_rules().unwrap().rules.borrow().is_none());
+ assert!(style.child_rules().unwrap().rules.borrow().is_none());
let exposed_host = crate::render_state::TestHost::new();
let exposed_sheet = add_sheet(&exposed_host);
let exposed_publication = NativeStylePublication {
@@ -1513,21 +1562,23 @@ mod tests {
fn traversal_binds_selectors_without_native_parents_or_caches() {
use crate::css::selector_parser::RustParsedSelectorList;
- fn visit(rule: &NativeRule, inputs: &SelectorInputs, bound: &mut Vec<std::sync::Arc<RustParsedSelectorList>>) {
+ type Bound = (
+ std::sync::Arc<RustParsedSelectorList>,
+ std::sync::Arc<crate::css::style::bridge::BoundScopeChain>,
+ );
+ fn visit(rule: &NativeRule, inputs: &SelectorInputs, bound: &mut Vec<Bound>) {
// The traversal must supply nesting even when no parent owner can be consulted.
- *rule.parent.borrow_mut() = Default::default();
+ rule.set_parent(Default::default());
let selectors = inputs.matching_selectors(RuleRef::Materialized(rule));
if let Some(selectors) = &selectors {
- bound.push(selectors.clone());
+ bound.push((selectors.clone(), inputs.scope()));
}
let nested = inputs.within(RuleRef::Materialized(rule), selectors, u32::MAX);
- if let Some(children) = &rule.children {
+ if let Some(children) = rule.children.get() {
for child in children.materialized_rules().iter() {
visit(child, &nested, bound);
}
}
- assert!(rule.matching_selectors.borrow().is_none());
- assert!(rule.scope_end_selectors.borrow().is_none());
}
let sheet = sheet(
@@ -1543,14 +1594,13 @@ mod tests {
drop(sheet);
let specificities: Vec<_> = bound
.iter()
- .map(|list| list.selectors[0].specificity().classes)
+ .map(|(list, _)| list.selectors.iter().next().unwrap().specificity().classes)
.collect();
assert_eq!(specificities, [1, 1, 0, 0]);
- assert!(bound.iter().all(|list| {
- list.selectors
- .iter()
- .all(|selector| !crate::css::selector_operations::contains_nesting(selector))
- }));
+ // A nested rule keeps its `&` as written, naming its parent's selectors in the sheet's arena.
+ assert!(crate::css::selector_operations::contains_nesting(
+ &bound[1].0.selectors.iter().next().unwrap().to_tree()
+ ));
}
#[test]
@@ -1626,14 +1676,14 @@ mod tests {
use crate::css::rule::{rust_rule_containing_function, rust_rule_list_clear};
let sheet = sheet("@function --f() { @media all { result: 1px; } }");
let function = sheet.rules().materialized_rules()[0].clone();
- let body = function.children.as_ref().unwrap();
+ let body = function.child_rules().unwrap();
let group = body
.materialized_rules()
.iter()
.find(|rule| rule.rule_type == NativeRuleType::Media)
.unwrap()
.clone();
- let declarations = group.children.as_ref().unwrap().materialized_rules()[0].clone();
+ let declarations = group.child_rules().unwrap().materialized_rules()[0].clone();
assert_eq!(rust_rule_containing_function(&function), Rc::as_ptr(&function));
assert_eq!(rust_rule_containing_function(&group), Rc::as_ptr(&function));
assert_eq!(rust_rule_containing_function(&declarations), Rc::as_ptr(&function));
@@ -1747,8 +1797,8 @@ mod tests {
fn selector_replacement_does_not_change_media_match_state() {
let sheet = sheet("@media all { @scope (.root) { .target { color: red; } } }");
let media = sheet.rules().materialized_rules()[0].clone();
- let scope = media.children.as_ref().unwrap().materialized_rules()[0].clone();
- let target = scope.children.as_ref().unwrap().materialized_rules()[0].identity;
+ let scope = media.child_rules().unwrap().materialized_rules()[0].clone();
+ let target = scope.child_rules().unwrap().materialized_rules()[0].identity;
let RulePayload::Media { list, .. } = &media.payload else {
unreachable!()
};
@@ -1766,7 +1816,7 @@ mod tests {
fn selector_traversal_preserves_descendant_media_state() {
let sheet = sheet(".parent { @media all { & .nested { color: red; } } }");
let parent = sheet.rules().materialized_rules()[0].clone();
- let media = parent.children.as_ref().unwrap().materialized_rules()[0].clone();
+ let media = parent.child_rules().unwrap().materialized_rules()[0].clone();
let RulePayload::Media { list, .. } = &media.payload else {
unreachable!()
};
@@ -1785,7 +1835,7 @@ mod tests {
use crate::css::rule::{rust_rule_declarations, rust_rule_list_clear, rust_rule_list_remove};
let sheet = sheet("@keyframes 色 { from { opacity: 0.25; } to { opacity: 0.75; } }");
let rule = sheet.rules().materialized_rules()[0].clone();
- let children = rule.children.as_ref().unwrap();
+ let children = rule.child_rules().unwrap();
let first = children.materialized_rules()[0].clone();
assert_eq!(first.declaration_owner_identity(), Some(rule.identity));
let native = unsafe { Box::from_raw(rust_rule_declarations(&first)) };
@@ -1818,9 +1868,9 @@ mod tests {
let rules = first.rules();
let other = second.rules();
let media = rules.materialized_rules()[1].clone();
- let children = media.children.as_ref().unwrap();
+ let children = media.child_rules().unwrap();
let supports = children.materialized_rules()[1].clone();
- let descendants = supports.children.as_ref().unwrap();
+ let descendants = supports.child_rules().unwrap();
let target = descendants.materialized_rules()[0].clone();
let path = |list: &NativeRuleList, identity| {
let mut path = Vec::new();
diff --git a/Libraries/LibWeb/Rust/src/css/rule/compilation/publication.rs b/Libraries/LibWeb/Rust/src/css/rule/compilation/publication.rs
index 168532e685c..7652c8bfe54 100644
--- a/Libraries/LibWeb/Rust/src/css/rule/compilation/publication.rs
+++ b/Libraries/LibWeb/Rust/src/css/rule/compilation/publication.rs
@@ -6,14 +6,13 @@
use super::{CompilationContext, NativeRuleType, NativeStyleSheet};
use crate::css::rule::read::RuleRef;
-use crate::css::selector_operations::{
- absolutize_selector_list, adapt_scope_end_selector_list, scope_root_selector_list,
-};
-use crate::css::selector_parser::{RustParsedSelectorList, StyleNestingParent};
+use crate::css::selector::SelectorListRef;
+use crate::css::selector_operations::scope_root_selector_list;
+use crate::css::selector_parser::RustParsedSelectorList;
use crate::css::style::bridge::{BoundScopeChain, declares_transitions};
use crate::css::style::engine_calls::document_host;
-use crate::css::style::program::RuleKind;
-use crate::css::style::rule_writes::{BoundSelectors, CompiledRule, CompiledRuleKind, NamespaceTexts, RuleWrite};
+use crate::css::style::pipeline::rule_store::RuleKind;
+use crate::css::style::rule_writes::{BoundSelectors, CompiledRule, CompiledRuleKind, RuleWrite};
use crate::render_state::DocumentHost;
use std::cell::RefCell;
use std::sync::Arc;
@@ -37,56 +36,45 @@ pub struct NativeStylePublication {
pub before: u64,
}
+/// What the rules a traversal reaches are directly inside, as their nested declarations see it.
+#[derive(Clone, Default)]
+enum Enclosing {
+ #[default]
+ None,
+ Scope,
+ /// A style rule, with its selectors.
+ Style(Arc<RustParsedSelectorList>),
+}
+
// Binding belongs to this document-thread traversal, not to the shared rule graph.
-#[derive(Clone)]
+#[derive(Clone, Default)]
pub(super) struct SelectorInputs {
- parent_kind: StyleNestingParent,
- immediate_parent_kind: StyleNestingParent,
- parents: Option<Arc<RustParsedSelectorList>>,
+ enclosing: Enclosing,
+ /// The scopes the rules are inside.
scope: Arc<BoundScopeChain>,
}
-impl Default for SelectorInputs {
- fn default() -> Self {
- Self {
- parent_kind: StyleNestingParent::None,
- immediate_parent_kind: StyleNestingParent::None,
- parents: None,
- scope: Arc::default(),
- }
- }
-}
-
impl SelectorInputs {
- fn bind(&self, source: &RustParsedSelectorList, parent_kind: StyleNestingParent) -> Arc<RustParsedSelectorList> {
- let empty: crate::css::selector::SelectorList = Box::new([]);
- let parents = if parent_kind == StyleNestingParent::Style {
- self.parents.as_ref().map_or(&empty, |parents| &parents.selectors)
- } else {
- &empty
- };
- Arc::new(RustParsedSelectorList {
- selectors: absolutize_selector_list(&source.selectors, parent_kind, parents)
- .unwrap_or_else(|| source.selectors.clone()),
- })
- }
-
+ /// The selectors the engine matches `rule` by, whose `&` names what the sheet's arena says.
pub(super) fn matching_selectors(&self, rule: RuleRef<'_>) -> Option<Arc<RustParsedSelectorList>> {
match rule.rule_type() {
- NativeRuleType::Style => Some(self.bind(&rule.selectors().unwrap(), self.parent_kind)),
- NativeRuleType::NestedDeclarations => {
- if let Some(parents) = &self.parents {
- return Some(parents.clone());
- }
- assert_eq!(self.parent_kind, StyleNestingParent::Scope);
- Some(Arc::new(RustParsedSelectorList {
- selectors: scope_root_selector_list(),
- }))
- }
+ NativeRuleType::Style => rule.selectors(),
+ NativeRuleType::NestedDeclarations => match &self.enclosing {
+ Enclosing::Style(selectors) => Some(selectors.clone()),
+ Enclosing::Scope => Some(Arc::new(RustParsedSelectorList {
+ selectors: SelectorListRef::pack(&scope_root_selector_list()),
+ })),
+ Enclosing::None => unreachable!("nested declarations are inside a style rule or `@scope`"),
+ },
_ => None,
}
}
+ /// The scopes the rules are inside.
+ pub(super) fn scope(&self) -> Arc<BoundScopeChain> {
+ self.scope.clone()
+ }
+
pub(super) fn within(
&self,
rule: RuleRef<'_>,
@@ -94,34 +82,17 @@ impl SelectorInputs {
implicit_root: u32,
) -> Self {
let mut nested = self.clone();
- nested.immediate_parent_kind = StyleNestingParent::None;
- if rule.rule_type() == NativeRuleType::Style {
- nested.parents = matching.or_else(|| self.matching_selectors(rule));
- nested.parent_kind = StyleNestingParent::Style;
- nested.immediate_parent_kind = StyleNestingParent::Style;
+ if rule.rule_type() == NativeRuleType::Style
+ && let Some(selectors) = matching.or_else(|| self.matching_selectors(rule))
+ {
+ nested.enclosing = Enclosing::Style(selectors);
}
if let Some(scope) = rule.scope() {
- let parent_kind = if rule.rule_type() == NativeRuleType::Import {
- StyleNestingParent::None
- } else {
- self.immediate_parent_kind
- };
- let start = scope.start.as_ref().map(|start| self.bind(start, parent_kind));
- let end = scope.end.as_ref().map(|end| RustParsedSelectorList {
- selectors: adapt_scope_end_selector_list(&end.selectors),
- });
- Arc::make_mut(&mut nested.scope).push(start.as_deref(), end.as_ref(), implicit_root);
+ Arc::make_mut(&mut nested.scope).push(scope.start.as_deref(), scope.end.as_deref(), implicit_root);
}
match rule.rule_type() {
- NativeRuleType::Scope => {
- nested.parent_kind = StyleNestingParent::Scope;
- nested.immediate_parent_kind = StyleNestingParent::Scope;
- nested.parents = None;
- }
- NativeRuleType::Import => {
- nested.parent_kind = StyleNestingParent::None;
- nested.parents = None;
- }
+ NativeRuleType::Scope => nested.enclosing = Enclosing::Scope,
+ NativeRuleType::Import => nested.enclosing = Enclosing::None,
_ => {}
}
nested
@@ -131,12 +102,11 @@ impl SelectorInputs {
/// The rules one compilation publishes to a sheet of a document's style engine, ahead of one rule, which it writes
/// as one write as it ends. The host notes each rule it publishes as it compiles it.
pub(super) struct Publisher<'a> {
- host: &'a DocumentHost,
+ /// The document whose engine the rules go to, or none where the process keeps them.
+ host: Option<&'a DocumentHost>,
sheet: u32,
before: u64,
rules: RefCell<Vec<CompiledRule>>,
- /// The native sheet the last rule came from, by identity, and the namespaces it declares.
- namespaces: RefCell<Option<(u64, Option<Arc<NamespaceTexts>>)>>,
}
impl<'a> Publisher<'a> {
@@ -146,16 +116,31 @@ impl<'a> Publisher<'a> {
pub(super) unsafe fn new(publication: &NativeStylePublication) -> Self {
Self {
// SAFETY: Guaranteed by the caller.
- host: unsafe { document_host(publication.host) },
+ host: Some(unsafe { document_host(publication.host) }),
sheet: publication.sheet,
before: publication.before,
rules: RefCell::default(),
- namespaces: RefCell::default(),
}
}
+ /// A publisher of a user agent sheet, whose rules the process keeps, once: no document notes them.
+ pub(super) fn of_user_agent_sheet() -> Self {
+ Self {
+ host: None,
+ sheet: 0,
+ before: 0,
+ rules: RefCell::default(),
+ }
+ }
+
+ /// The rules the compilation published, of a publisher of a user agent sheet.
+ pub(super) fn into_rules(self) -> Vec<CompiledRule> {
+ debug_assert!(self.host.is_none());
+ self.rules.into_inner()
+ }
+
pub(super) fn host(&self) -> &'a DocumentHost {
- self.host
+ self.host.expect("only the rules of a document's sheet are edited")
}
pub(super) fn sheet(&self) -> u32 {
@@ -169,50 +154,35 @@ impl<'a> Publisher<'a> {
sheet: self.sheet,
before,
rules: RefCell::default(),
- namespaces: RefCell::default(),
}
}
/// Writes the rules the compilation published, as one write.
pub(super) fn finish(self) {
+ let host = self.host();
let rules = self.rules.into_inner();
if rules.is_empty() {
return;
}
- self.host.write_rules(RuleWrite::PublishRules {
+ host.write_rules(RuleWrite::PublishRules {
sheet: self.sheet,
before: self.before,
rules,
});
}
- /// The namespaces `source` declares, which the rules that come from it share.
- fn namespaces_of(&self, source: &NativeStyleSheet) -> Option<Arc<NamespaceTexts>> {
- let mut cached = self.namespaces.borrow_mut();
- if let Some((identity, texts)) = &*cached
- && *identity == source.identity()
- {
- return texts.clone();
- }
- let texts = NamespaceTexts::of(source);
- *cached = Some((source.identity(), texts.clone()));
- texts
- }
-
/// Writes the selectors `selectors` for the published style rule `rule`, which keeps its place and declarations.
pub(super) fn replace_selectors(
&self,
rule: RuleRef<'_>,
- source: &NativeStyleSheet,
context: &CompilationContext,
selectors: Arc<RustParsedSelectorList>,
) {
- self.host.write_rules(RuleWrite::ReplaceSelectors {
+ self.host().write_rules(RuleWrite::ReplaceSelectors {
identity: rule.identity(),
selectors: BoundSelectors {
selectors,
- scope: context.selectors.scope.clone(),
- namespaces: self.namespaces_of(source),
+ scope: context.selectors.scope(),
},
});
}
@@ -235,8 +205,7 @@ impl<'a> Publisher<'a> {
CompiledRuleKind::Style {
selectors: BoundSelectors {
selectors: selectors.clone(),
- scope: context.selectors.scope.clone(),
- namespaces: self.namespaces_of(source),
+ scope: context.selectors.scope(),
},
gated_by_container_query: context.gated_by_container_query,
}
@@ -258,13 +227,27 @@ impl<'a> Publisher<'a> {
let declares_transitions = matches!(kind, CompiledRuleKind::Style { .. })
&& declarations
.as_ref()
- .is_some_and(|declarations| declares_transitions(&declarations.properties));
+ .is_some_and(|declarations| declares_transitions(declarations.properties()));
let in_a_layer = context.in_a_layer
&& matches!(
rule.rule_type(),
NativeRuleType::Style | NativeRuleType::NestedDeclarations | NativeRuleType::CounterStyle
);
- self.host.published_rules().insert(self.sheet, rule.identity());
+ if let Some(host) = self.host {
+ host.published_rules().insert(self.sheet, rule.identity());
+ // NB: These rules hand over declarations the rule write does not hold.
+ match rule.rule_type() {
+ NativeRuleType::Function => super::super::function::note_attr_names_read_by_function(host, rule),
+ NativeRuleType::Keyframes => {
+ let _ = rule.visit_children(&mut |keyframe| {
+ let (_, declarations) = keyframe.keyframe();
+ crate::css::style::host_atoms::note_attr_names_read_by_block(host, &declarations);
+ std::ops::ControlFlow::Continue(())
+ });
+ }
+ _ => {}
+ }
+ }
self.rules.borrow_mut().push(CompiledRule {
identity: rule.identity(),
kind,
diff --git a/Libraries/LibWeb/Rust/src/css/rule/function.rs b/Libraries/LibWeb/Rust/src/css/rule/function.rs
index 21fcf7c1d26..0cff554d372 100644
--- a/Libraries/LibWeb/Rust/src/css/rule/function.rs
+++ b/Libraries/LibWeb/Rust/src/css/rule/function.rs
@@ -112,6 +112,25 @@ impl CompiledFunction {
}
}
+/// Notes what the `attr()`s of the `@function` rule `rule`, which the host is handing the engine, can read.
+pub(super) fn note_attr_names_read_by_function(host: &crate::render_state::DocumentHost, rule: RuleRef<'_>) {
+ let function = CompiledFunction::compile(&NativeRuleView { rule, containers: &[] });
+ let defaults = function
+ .parameter_defaults
+ .iter()
+ .flatten()
+ .filter(|_| function.parameter_defaults_read_attributes);
+ let bodies = function
+ .inputs
+ .iter()
+ .filter(|input| input.reads_attributes)
+ .flat_map(|input| &input.declarations)
+ .map(SubstitutionFunctionDeclaration::tokens);
+ for tokens in defaults.map(|tokens| tokens.as_ref()).chain(bodies) {
+ crate::css::style::host_atoms::note_attr_names_read_by_tokens(host, tokens);
+ }
+}
+
#[unsafe(no_mangle)]
pub extern "C" fn rust_rule_view_compile_function(view: &NativeRuleView<'_>) -> *const CompiledFunction {
Arc::into_raw(Arc::new(CompiledFunction::compile(view)))
diff --git a/Libraries/LibWeb/Rust/src/css/rule/mutation.rs b/Libraries/LibWeb/Rust/src/css/rule/mutation.rs
index 983d65e3a26..e3d696bf90c 100644
--- a/Libraries/LibWeb/Rust/src/css/rule/mutation.rs
+++ b/Libraries/LibWeb/Rust/src/css/rule/mutation.rs
@@ -27,7 +27,7 @@ fn visit_rule(
visit_list(imported.rules(), imported, visit)?;
}
} else if rule.rule_type != NativeRuleType::Keyframes
- && let Some(children) = &rule.children
+ && let Some(children) = rule.children.get()
{
visit_list(children, sheet, visit)?;
}
@@ -133,8 +133,8 @@ mod tests {
let sheet = sheet("@media all { .一 {} .二 {} } @layer 空; @supports (display: grid) { .三 {} } .四 {}");
let rules = sheet.rules().materialized_rules();
let first = &rules[0];
- let inside = first.children.as_ref().unwrap().materialized_rules()[0].identity;
- let next = rules[2].children.as_ref().unwrap().materialized_rules()[0].identity;
+ let inside = first.child_rules().unwrap().materialized_rules()[0].identity;
+ let next = rules[2].child_rules().unwrap().materialized_rules()[0].identity;
let last = rules[3].identity;
let published = |identity| [inside, next, last].contains(&identity);
assert_eq!(successor(&sheet, first.identity, published), next);
diff --git a/Libraries/LibWeb/Rust/src/css/rule/read.rs b/Libraries/LibWeb/Rust/src/css/rule/read.rs
index 9531241f05e..01f8970b03c 100644
--- a/Libraries/LibWeb/Rust/src/css/rule/read.rs
+++ b/Libraries/LibWeb/Rust/src/css/rule/read.rs
@@ -7,7 +7,7 @@
use super::{NativeRule, NativeRuleList, NativeRuleType, RulePayload};
use crate::css::container_conditions::ContainerConditionsData;
use crate::css::css_string::CssString;
-use crate::css::declaration_block::DeclarationBlockData;
+use crate::css::declaration_block::SharedDeclarationBlock;
use crate::css::descriptor_block::{DescriptorBlockData, FfiDescriptorBlock};
use crate::css::font_feature_values::FontFeatureValuesData;
use crate::css::function_signature::FunctionSignature;
@@ -219,11 +219,14 @@ pub unsafe extern "C" fn rust_rule_view_name(
/// The declarations of a `@position-try` rule, retained for the caller.
#[unsafe(no_mangle)]
-pub extern "C" fn rust_rule_view_position_try_declarations(view: &NativeRuleView<'_>) -> *const DeclarationBlockData {
+pub extern "C" fn rust_rule_view_position_try_declarations(
+ view: &NativeRuleView<'_>,
+) -> *const crate::css::declaration_block::DeclarationBlockHeader {
assert!(view.rule.rule_type() == NativeRuleType::PositionTry);
- view.rule
- .position_try_declarations()
- .map_or(std::ptr::null(), Arc::into_raw)
+ view.rule.position_try_declarations().map_or(
+ std::ptr::null(),
+ crate::css::declaration_block::SharedDeclarationBlock::into_raw,
+ )
}
/// # Safety
@@ -232,13 +235,18 @@ pub extern "C" fn rust_rule_view_position_try_declarations(view: &NativeRuleView
pub unsafe extern "C" fn rust_rule_view_keyframes(
view: &NativeRuleView<'_>,
context: *const std::ffi::c_void,
- visit: unsafe extern "C" fn(*const std::ffi::c_void, *const f64, usize, *const DeclarationBlockData),
+ visit: unsafe extern "C" fn(
+ *const std::ffi::c_void,
+ *const f64,
+ usize,
+ *const crate::css::declaration_block::DeclarationBlockHeader,
+ ),
) {
assert!(view.rule.rule_type() == NativeRuleType::Keyframes);
let _ = view.rule.visit_children(&mut |frame| {
let (keys, declarations) = frame.keyframe();
unsafe {
- visit(context, keys.as_ptr(), keys.len(), Arc::as_ptr(&declarations));
+ visit(context, keys.as_ptr(), keys.len(), declarations.as_ptr());
}
ControlFlow::Continue(())
});
@@ -296,7 +304,7 @@ impl<'a> RuleRef<'a> {
}
}
- pub(super) fn keyframe(self) -> (&'a [f64], Arc<DeclarationBlockData>) {
+ pub(super) fn keyframe(self) -> (&'a [f64], SharedDeclarationBlock) {
match self {
Self::Materialized(rule) => {
let RulePayload::Keyframe(frame) = &rule.payload else {
@@ -493,14 +501,15 @@ impl<'a> RuleRef<'a> {
pub(crate) fn scope(self) -> Option<Arc<ScopeSelectors>> {
match self {
Self::Materialized(rule) => match &rule.payload {
- RulePayload::Scope(scope) | RulePayload::Import { scope: Some(scope), .. } => Some(scope.clone()),
+ RulePayload::Scope(scope) => Some(scope.borrow().clone()),
+ RulePayload::Import { scope: Some(scope), .. } => Some(scope.clone()),
_ => None,
},
Self::Shared(rule, _) => rule.scope(),
}
}
- pub(crate) fn cascade_declarations(self) -> Option<Arc<DeclarationBlockData>> {
+ pub(crate) fn cascade_declarations(self) -> Option<SharedDeclarationBlock> {
match self {
Self::Materialized(rule) => rule.cascade_declarations(),
Self::Shared(rule, _) => rule.cascade_declarations(),
@@ -508,7 +517,7 @@ impl<'a> RuleRef<'a> {
}
/// The declarations of a `@position-try` rule.
- pub(crate) fn position_try_declarations(self) -> Option<Arc<DeclarationBlockData>> {
+ pub(crate) fn position_try_declarations(self) -> Option<SharedDeclarationBlock> {
match self {
Self::Materialized(rule) => match &rule.payload {
RulePayload::PositionTry { declarations, .. } => Some(declarations.data()),
@@ -520,7 +529,7 @@ impl<'a> RuleRef<'a> {
pub(crate) fn visit_children(self, visit: &mut impl FnMut(RuleRef<'_>) -> ControlFlow<()>) -> ControlFlow<()> {
match self {
- Self::Materialized(rule) => match &rule.children {
+ Self::Materialized(rule) => match rule.children.get() {
Some(children) => children.visit_rules(visit),
None => ControlFlow::Continue(()),
},
diff --git a/Libraries/LibWeb/Rust/src/css/selector.rs b/Libraries/LibWeb/Rust/src/css/selector.rs
index 55f105f0f9d..26faba96677 100644
--- a/Libraries/LibWeb/Rust/src/css/selector.rs
+++ b/Libraries/LibWeb/Rust/src/css/selector.rs
@@ -4,14 +4,12 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-use std::sync::Arc;
-
pub use crate::css::ffi_support::FfiStringView;
-use crate::css::ffi_support::{OwnedBox, ascii_lowercase};
-use crate::css::retained_fly_string::RetainedUtf16FlyString;
+use crate::css::ffi_support::OwnedBox;
+use crate::css::ffi_support::ascii_lowercase;
+use crate::css::style::index::StyleAtomID;
pub type SelectorString = crate::css::css_string::CssString;
-pub type SelectorList = Box<[Arc<CompiledSelector>]>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
@@ -36,48 +34,51 @@ pub enum NamespaceType {
Named,
}
-#[derive(Clone, Debug, PartialEq, Eq)]
+/// A name with its namespace. The names are process style atoms, which the selector holding them
+/// leases; the atom table gives each its text and its ASCII-lowercase form.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct QualifiedName {
pub namespace_type: NamespaceType,
- pub namespace: RetainedUtf16FlyString,
- pub name: RetainedUtf16FlyString,
- pub lowercase_name: RetainedUtf16FlyString,
+ /// The namespace prefix, for a `Named` namespace, and none otherwise.
+ pub namespace: StyleAtomID,
+ pub name: StyleAtomID,
+ /// Whether `name` is its own ASCII-lowercase form, which a match that folds the name compares as written.
+ pub name_is_ascii_lowercase: bool,
}
impl QualifiedName {
#[must_use]
- pub fn interned_name_identity(&self) -> Option<usize> {
- self.name.optional_raw()
- }
-
- /// HTML elements in HTML documents match tag names case-insensitively, so the lowercase form is
- /// the identity a tag atom is keyed by.
- #[must_use]
- pub fn interned_lowercase_name_identity(&self) -> Option<usize> {
- self.lowercase_name.optional_raw()
+ pub fn new(namespace_type: NamespaceType, namespace: StyleAtomID, name: StyleAtomID) -> Self {
+ Self {
+ namespace_type,
+ namespace,
+ name,
+ name_is_ascii_lowercase: is_ascii_lowercase_atom(name),
+ }
}
}
-#[derive(Clone, Debug, PartialEq, Eq)]
+/// The name of an id or class selector, as a process style atom the selector holding it leases.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct NameSelector {
- pub name: RetainedUtf16FlyString,
- /// The ASCII-lowercase name used for quirks-mode id and class matching.
- pub lowercase_name: RetainedUtf16FlyString,
+ pub name: StyleAtomID,
+ /// Whether `name` is its own ASCII-lowercase form, which a match that folds the name compares as written.
+ pub is_ascii_lowercase: bool,
}
impl NameSelector {
- /// The interned identity of this name, for keying an atom table by the same word the DOM side
- /// compares against.
#[must_use]
- pub fn interned_name_identity(&self) -> Option<usize> {
- self.name.optional_raw()
+ pub fn new(name: StyleAtomID) -> Self {
+ Self {
+ name,
+ is_ascii_lowercase: is_ascii_lowercase_atom(name),
+ }
}
+}
- /// The interned identity of this name's ASCII-lowercase folding.
- #[must_use]
- pub fn interned_lowercase_name_identity(&self) -> Option<usize> {
- self.lowercase_name.optional_raw()
- }
+/// Whether the name of `atom` is its own ASCII-lowercase form.
+fn is_ascii_lowercase_atom(atom: StyleAtomID) -> bool {
+ atom.is_none() || crate::css::style::process_atoms().ascii_lowercase(atom) == atom
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -100,15 +101,6 @@ pub enum AttributeCaseType {
Insensitive,
}
-#[derive(Clone, Debug, PartialEq, Eq)]
-pub struct AttributeSelector {
- pub match_type: AttributeMatchType,
- pub qualified_name: QualifiedName,
- pub value: SelectorString,
- pub value_identity: RetainedUtf16FlyString,
- pub case_type: AttributeCaseType,
-}
-
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct AnPlusBPattern {
pub step_size: i32,
@@ -169,95 +161,6 @@ fn equals_ascii_case_insensitive(value: &[u16], expected: &[u8]) -> bool {
include!(concat!(env!("OUT_DIR"), "/selector_pseudo_generated.rs"));
-#[derive(Clone, Debug, PartialEq, Eq)]
-pub struct LanguageRange {
- pub value: SelectorString,
- pub is_string: bool,
-}
-
-#[derive(Clone, Debug, PartialEq, Eq)]
-pub struct PseudoClassSelector {
- pub pseudo_class: PseudoClassType,
- pub an_plus_b_pattern: AnPlusBPattern,
- pub argument_selector_list: SelectorList,
- pub languages: Box<[LanguageRange]>,
- pub direction: Option<Direction>,
- pub identifier: Option<SelectorString>,
- pub identifier_identity: RetainedUtf16FlyString,
- pub identifier_lowercase_identity: RetainedUtf16FlyString,
- pub levels: Box<[i64]>,
- pub is_forgiving: bool,
-}
-
-#[derive(Clone, Debug, PartialEq, Eq)]
-pub enum PseudoElementValue {
- None,
- CompoundSelector(Arc<CompiledSelector>),
- Identifiers(Box<[SelectorString]>),
- TransitionName(Box<TransitionNameAndClassSelector>),
-}
-
-// https://drafts.csswg.org/css-view-transitions-1/#typedef-pt-name-selector
-#[derive(Clone, Debug, PartialEq, Eq)]
-pub enum TransitionNameSelector {
- Universal,
- Name(SelectorString),
-}
-
-// https://drafts.csswg.org/css-view-transitions-2/#typedef-pt-name-and-class-selector
-#[derive(Clone, Debug, PartialEq, Eq)]
-pub struct TransitionNameAndClassSelector {
- pub name: Option<TransitionNameSelector>,
- pub classes: Box<[SelectorString]>,
-}
-
-#[derive(Clone, Debug, PartialEq, Eq)]
-pub struct PseudoElementSelector {
- pub pseudo_element: PseudoElementType,
- pub serialized_name: Option<SelectorString>,
- pub value: PseudoElementValue,
- /// The interned identity of each name in `value`, when it holds identifiers, keyed by the same
- /// word the DOM side compares against.
- pub identifier_identities: Box<[RetainedUtf16FlyString]>,
-}
-
-// Keep the common ID and class selectors inline without reserving space for the larger payloads.
-#[derive(Clone, Debug, PartialEq, Eq)]
-pub enum SimpleSelector {
- Universal(Box<QualifiedName>),
- TagName(Box<QualifiedName>),
- Id(NameSelector),
- Class(NameSelector),
- Attribute(Box<AttributeSelector>),
- PseudoClass(Box<PseudoClassSelector>),
- PseudoElement(Box<PseudoElementSelector>),
- Nesting,
- Invalid(SelectorString),
-}
-
-// Keep names to three words, plus the selector tag.
-const _: () = assert!(size_of::<SimpleSelector>() <= 4 * size_of::<usize>());
-
-#[derive(Clone, Debug, PartialEq, Eq)]
-pub struct CompoundSelector {
- /// The combinator relating this compound to the compound immediately to its left. The
- /// leftmost compound therefore has `Combinator::None`.
- pub combinator: Combinator,
- pub is_implicit_universal_anchor: bool,
- pub simple_selectors: Box<[SimpleSelector]>,
-}
-
-/// The immutable representation used by every matching path.
-///
-/// Compounds retain their parsed left-to-right order. Matching starts at the final compound and
-/// follows each compound's combinator toward the beginning of this slice.
-#[derive(Debug, PartialEq, Eq)]
-pub struct CompiledSelector {
- pub compound_selectors: Box<[CompoundSelector]>,
- /// The pseudo-element required on the initial match target, if this selector ends in one.
- pub target_pseudo_element: Option<PseudoElementType>,
-}
-
/// Selector specificity, compared component by component.
#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Specificity {
@@ -277,7 +180,7 @@ impl Specificity {
}
#[must_use]
- fn packed(self) -> u32 {
+ pub(in crate::css) fn packed(self) -> u32 {
(u32::from(self.ids.min(u16::from(u8::MAX))) << 16)
| (u32::from(self.classes.min(u16::from(u8::MAX))) << 8)
| u32::from(self.types.min(u16::from(u8::MAX)))
@@ -290,172 +193,22 @@ pub enum SearchTextMatchFilter {
NotCurrent,
}
-pub fn search_text_match_filter_of_pseudo_class(pseudo_class: &PseudoClassSelector) -> Option<SearchTextMatchFilter> {
- match pseudo_class.pseudo_class {
- PseudoClassType::Current => Some(SearchTextMatchFilter::Current),
- PseudoClassType::Not => {
- let [argument] = &*pseudo_class.argument_selector_list else {
- return None;
- };
- let [compound] = &*argument.compound_selectors else {
- return None;
- };
- matches!(
- &*compound.simple_selectors,
- [SimpleSelector::PseudoClass(inner)] if inner.pseudo_class == PseudoClassType::Current
- )
- .then_some(SearchTextMatchFilter::NotCurrent)
- }
- _ => None,
- }
-}
-
-pub fn search_text_match_filter(simple: &SimpleSelector) -> Option<SearchTextMatchFilter> {
- match simple {
- SimpleSelector::PseudoClass(pseudo_class) => search_text_match_filter_of_pseudo_class(pseudo_class),
- _ => None,
- }
-}
-
-impl CompiledSelector {
- #[allow(clippy::arc_with_non_send_sync)] // Bound selectors retain document-thread atoms.
- pub(crate) fn new(compound_selectors: Box<[CompoundSelector]>) -> Arc<Self> {
- let target_pseudo_element = compound_selectors
- .last()
- .and_then(|compound| compound.simple_selectors.first())
- .and_then(|simple_selector| match simple_selector {
- SimpleSelector::PseudoElement(selector)
- if !matches!(
- selector.pseudo_element,
- PseudoElementType::Part | PseudoElementType::Slotted
- ) =>
- {
- Some(selector.pseudo_element)
- }
- _ => None,
- })
- .map(|pseudo_element| {
- let names_current_match = pseudo_element == PseudoElementType::SearchText
- && compound_selectors.last().is_some_and(|compound| {
- compound
- .simple_selectors
- .iter()
- .any(|simple| search_text_match_filter(simple) == Some(SearchTextMatchFilter::Current))
- });
- if names_current_match {
- PseudoElementType::SearchTextCurrent
- } else {
- pseudo_element
- }
- });
-
- Arc::new(Self {
- compound_selectors,
- target_pseudo_element,
- })
- }
-
- pub fn styles_every_search_text_match(&self) -> bool {
- self.target_pseudo_element == Some(PseudoElementType::SearchText)
- && self.compound_selectors.last().is_some_and(|compound| {
- compound
- .simple_selectors
- .iter()
- .all(|simple| search_text_match_filter(simple).is_none())
- })
- }
-
- /// https://www.w3.org/TR/selectors-4/#specificity-rules
- #[must_use]
- pub fn specificity(&self) -> Specificity {
- fn greatest_specificity(selectors: &[Arc<CompiledSelector>]) -> Specificity {
- selectors
- .iter()
- .map(|selector| selector.specificity())
- .max()
- .unwrap_or_default()
- }
-
- let mut specificity = Specificity::default();
- for compound in &self.compound_selectors {
- for simple_selector in &compound.simple_selectors {
- let contribution = match simple_selector {
- SimpleSelector::Id(_) => Specificity {
- ids: 1,
- ..Specificity::default()
- },
- SimpleSelector::Class(_) | SimpleSelector::Attribute(_) => Specificity {
- classes: 1,
- ..Specificity::default()
- },
- SimpleSelector::TagName(_) => Specificity {
- types: 1,
- ..Specificity::default()
- },
- SimpleSelector::PseudoClass(pseudo_class) => match pseudo_class.pseudo_class {
- PseudoClassType::Has | PseudoClassType::Is | PseudoClassType::Not => {
- greatest_specificity(&pseudo_class.argument_selector_list)
- }
- PseudoClassType::NthChild | PseudoClassType::NthLastChild => Specificity {
- classes: 1,
- ..Specificity::default()
- }
- .saturating_add(greatest_specificity(&pseudo_class.argument_selector_list)),
- PseudoClassType::Where => Specificity::default(),
- PseudoClassType::Host => Specificity {
- classes: 1,
- ..Specificity::default()
- }
- .saturating_add(greatest_specificity(&pseudo_class.argument_selector_list)),
- _ => Specificity {
- classes: 1,
- ..Specificity::default()
- },
- },
- SimpleSelector::PseudoElement(pseudo_element) => {
- // https://drafts.csswg.org/css-view-transitions-2/#pseudo-element-class-additions
- // The specificity of a named view transition pseudo-element selector with a * argument and with
- // an empty <pt-class-selector> is zero.
- if let PseudoElementValue::TransitionName(argument) = &pseudo_element.value
- && argument.name == Some(TransitionNameSelector::Universal)
- && argument.classes.is_empty()
- {
- Specificity::default()
- } else {
- let pseudo_specificity = Specificity {
- types: 1,
- ..Specificity::default()
- };
- match &pseudo_element.value {
- PseudoElementValue::CompoundSelector(argument)
- if pseudo_element.pseudo_element == PseudoElementType::Slotted =>
- {
- pseudo_specificity.saturating_add(argument.specificity())
- }
- _ => pseudo_specificity,
- }
- }
- }
- SimpleSelector::Universal(_) | SimpleSelector::Nesting | SimpleSelector::Invalid(_) => {
- Specificity::default()
- }
- };
- specificity = specificity.saturating_add(contribution);
- }
- }
- specificity
- }
-}
+pub use crate::css::selector_arena::{
+ AttributeSelector, CompoundRef, PseudoClassSelector, PseudoElementSelector, PseudoElementValue, Selector,
+ SelectorListRef, SelectorListView, SelectorRef, SimpleSelector, TransitionNameSelector,
+ search_text_match_filter_of_pseudo_class,
+};
+/// A parsed selector, as C++ holds one.
pub struct RustSelector {
- pub(crate) selector: Arc<CompiledSelector>,
+ pub(crate) selector: SelectorRef,
}
impl RustSelector {
- /// The compiled selector, for consumers that translate it rather than match with it.
+ /// The selector, for consumers that translate it rather than match with it.
#[must_use]
- pub fn compiled(&self) -> &CompiledSelector {
- &self.selector
+ pub fn compiled(&self) -> Selector<'_> {
+ self.selector.view()
}
}
@@ -585,8 +338,7 @@ pub fn language_range_matches_tag<T: Copy + Into<u16>>(language_range: &[u16], l
// https://html.spec.whatwg.org/multipage/semantics-other.html#case-sensitivity-of-selectors
// Attribute selectors on an HTML element in an HTML document must treat the values of attributes
// with the following names as ASCII case-insensitive:
-pub fn is_ascii_case_insensitive_html_attribute(name: &RetainedUtf16FlyString) -> bool {
- let name = super::css_tokenizer::TokenizerInput::from(name);
+pub fn is_ascii_case_insensitive_html_attribute(name: &[u16]) -> bool {
const NAMES: &[&[u8]] = &[
b"accept",
b"accept-charset",
@@ -636,11 +388,7 @@ pub fn is_ascii_case_insensitive_html_attribute(name: &RetainedUtf16FlyString) -
b"vlink",
];
NAMES.iter().any(|candidate| {
- name.len() == candidate.len()
- && candidate
- .iter()
- .enumerate()
- .all(|(index, &byte)| name.code_unit_at(index) == u16::from(byte))
+ name.len() == candidate.len() && candidate.iter().zip(name).all(|(&byte, &unit)| unit == u16::from(byte))
})
}
@@ -657,5 +405,5 @@ pub extern "C" fn rust_selector_destroy(selector: OwnedBox<RustSelector>) {
pub unsafe extern "C" fn rust_selector_specificity(selector: *const RustSelector) -> u32 {
assert!(!selector.is_null());
// SAFETY: The caller guarantees that the selector handle remains valid for this call.
- unsafe { &(*selector).selector }.specificity().packed()
+ unsafe { &(*selector).selector }.view().specificity().packed()
}
diff --git a/Libraries/LibWeb/Rust/src/css/selector_arena.rs b/Libraries/LibWeb/Rust/src/css/selector_arena.rs
new file mode 100644
index 00000000000..702dd37e9cf
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/selector_arena.rs
@@ -0,0 +1,2533 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Parsed selectors, as 8-byte components in one immutable arena per parsed list.
+//!
+//! Every selector of a list, nested argument lists included, is a run of [`Component`]s in
+//! matching order: the subject compound first, and inside a compound the simple selectors in the
+//! order they were written. The last component of each compound carries the [`Relation`] to the
+//! compound left of it. A nested list is stored before the selector that names it, so runs never
+//! interleave. Payloads that do not fit a component's 32-bit data go in typed side pools.
+//!
+//! Names are process style atoms, which the arena leases once each. The arena is `Send` and
+//! `Sync`: it holds atoms, indices and text only.
+//!
+//! Readers see the components through borrowed views ([`Selector`], [`CompoundRef`],
+//! [`SimpleSelector`]) that decode them on the fly.
+
+use smallvec::SmallVec;
+use std::sync::Arc;
+
+use crate::css::selector::{
+ AnPlusBPattern, AttributeCaseType, AttributeMatchType, Combinator, Direction, NameSelector, NamespaceType,
+ PseudoClassParameterType, PseudoClassType, PseudoElementType, QualifiedName, SearchTextMatchFilter, Specificity,
+ pseudo_class_from_ffi,
+};
+use crate::css::selector_tree as tree;
+use crate::css::style::AtomLeases;
+use crate::css::style::index::StyleAtomID;
+
+/// The number a selector arena takes as it is frozen, which no other arena of the process ever
+/// takes: what a cache keyed by a selector names its arena by, where an address could be reused
+/// by the arena of a later parse.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub(crate) struct SelectorArenaSerial(u64);
+
+impl SelectorArenaSerial {
+ /// The next serial of the process, from `next`, the counter of its process style.
+ pub(crate) fn next(next: &std::sync::atomic::AtomicU64) -> Self {
+ Self(next.fetch_add(1, std::sync::atomic::Ordering::Relaxed))
+ }
+}
+
+/// Where a selector list starts in its arena.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub(crate) struct ListStart(u32);
+
+/// A component's position in its arena.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub(crate) struct ComponentOffset(u32);
+
+impl ComponentOffset {
+ /// Where the page of `1 << page_bits` components the component is in starts, and where it is
+ /// in that page.
+ #[must_use]
+ pub(crate) fn in_page(self, page_bits: u32) -> (Self, u32) {
+ let mask = (1 << page_bits) - 1;
+ (Self(self.0 & !mask), self.0 & mask)
+ }
+
+ /// The component `offset` components into the page starting at `self`.
+ #[must_use]
+ pub(crate) fn into_page(self, offset: u32) -> Self {
+ Self(self.0 + offset)
+ }
+}
+
+/// A style rule's place among the style rules whose selectors an arena holds: the rule a `&`
+/// names, through the arena's rule lists.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub(crate) struct RuleOrdinal(u32);
+
+/// What a `&` names.
+///
+/// https://drafts.csswg.org/css-nesting/#nest-selector
+/// The nesting selector represents the elements matched by the parent rule. When the parent rule
+/// is a style rule, it represents the elements matched by that rule's selector list; inside a
+/// scoped rule it represents the scoping root, and anywhere else the root of the tree.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum Nesting<Rule> {
+ /// The root of the tree, or the scoping root where a scope is bound.
+ #[default]
+ Root,
+ /// The scoping root of the `@scope` the rule is directly in.
+ Scope,
+ /// The selectors of the style rule the rule is nested in, in the same arena.
+ Rule(Rule),
+ /// A style rule the parse did not see, as when the CSSOM parses a nested rule's selectors
+ /// before it places the rule. Placing it binds the `&` to its parent.
+ Unbound,
+}
+
+/// What a `&` names, as the parse that wrote it knew.
+pub(crate) type NestingTarget = Nesting<RuleOrdinal>;
+
+/// What a `&` in an arena names, decoded: the selectors of the parent style rule are `:is()` of them.
+pub type NestingOfArena<'a> = Nesting<SelectorListView<'a>>;
+
+const NESTING_ROOT: u8 = 0;
+const NESTING_SCOPE: u8 = 1;
+const NESTING_RULE: u8 = 2;
+const NESTING_UNBOUND: u8 = 3;
+
+impl NestingTarget {
+ fn kind(self) -> u8 {
+ match self {
+ Self::Root => NESTING_ROOT,
+ Self::Scope => NESTING_SCOPE,
+ Self::Rule(_) => NESTING_RULE,
+ Self::Unbound => NESTING_UNBOUND,
+ }
+ }
+}
+
+/// A run of entries in one of an arena's pools.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct PoolRange {
+ start: u32,
+ length: u32,
+}
+
+impl PoolRange {
+ fn of<T>(pool: &[T], range: PoolRange) -> &[T] {
+ &pool[range.start as usize..(range.start + range.length) as usize]
+ }
+}
+
+fn index_u32(index: usize) -> u32 {
+ u32::try_from(index).expect("a selector list holds fewer than 2^32 parts")
+}
+
+/// What a component is.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+enum ComponentKind {
+ Universal,
+ Tag,
+ Id,
+ Class,
+ Attribute,
+ PseudoClass,
+ PseudoElement,
+ Nesting,
+ Invalid,
+ /// The implicit leftmost compound of a selector that starts with a combinator.
+ RelativeAnchor,
+}
+
+/// How the compound a component ends relates to the compound left of it, or `SubSelector` for a
+/// component that does not end its compound.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub(crate) enum Relation {
+ SubSelector,
+ Descendant,
+ Child,
+ NextSibling,
+ SubsequentSibling,
+ Column,
+ PseudoElement,
+ /// The component ends the leftmost compound, and so the complex selector.
+ Leftmost,
+}
+
+impl Relation {
+ fn of(combinator: Combinator) -> Self {
+ match combinator {
+ Combinator::None => Self::Leftmost,
+ Combinator::Descendant => Self::Descendant,
+ Combinator::ImmediateChild => Self::Child,
+ Combinator::NextSibling => Self::NextSibling,
+ Combinator::SubsequentSibling => Self::SubsequentSibling,
+ Combinator::Column => Self::Column,
+ Combinator::PseudoElement => Self::PseudoElement,
+ }
+ }
+
+ fn combinator(self) -> Combinator {
+ match self {
+ Self::Descendant => Combinator::Descendant,
+ Self::Child => Combinator::ImmediateChild,
+ Self::NextSibling => Combinator::NextSibling,
+ Self::SubsequentSibling => Combinator::SubsequentSibling,
+ Self::Column => Combinator::Column,
+ Self::PseudoElement => Combinator::PseudoElement,
+ Self::SubSelector | Self::Leftmost => Combinator::None,
+ }
+ }
+}
+
+const KIND_BITS: u32 = 0x0000_000f;
+const RELATION_SHIFT: u32 = 4;
+const RELATION_BITS: u32 = 0x0000_00f0;
+const PSEUDO_SHIFT: u32 = 8;
+const PSEUDO_BITS: u32 = 0x0000_ff00;
+const LAST_IN_LIST: u32 = 1 << 16;
+const IMPLICIT: u32 = 1 << 17;
+const NAMESPACE_SHIFT: u32 = 18;
+const NAMESPACE_BITS: u32 = 0b11 << NAMESPACE_SHIFT;
+/// On a `:not()` component: its argument is `:current` alone, which picks the kind of search text match an entry
+/// styles rather than constraining any element.
+const SEARCH_TEXT_FILTER: u32 = 1 << 20;
+/// On the first component of a selector: its subject compound holds no pseudo-element, `::part()` or `::slotted()`,
+/// so that it describes the element it is matched against from its subject on.
+const DESCRIBES_ITS_SUBJECT: u32 = 1 << 21;
+const INLINE: u32 = 1 << 22;
+const FORGIVING: u32 = 1 << 23;
+/// The name of a type, id, class or attribute selector is its own ASCII-lowercase form.
+const ASCII_LOWERCASE: u32 = 1 << 24;
+/// An attribute selector names one of the attributes whose values HTML compares ASCII case-insensitively.
+const LEGACY_CASE_INSENSITIVE: u32 = 1 << 25;
+/// On the first component of a selector: the selector names the scoping root, with `:scope` or a `&` directly inside
+/// `@scope`, anywhere in it.
+const NAMES_THE_SCOPE: u32 = 1 << 26;
+/// On the first component of a selector: the selector names an element in another tree, with `::slotted()` or
+/// `::part()`, where the sheet's default namespace does not follow it.
+const ESCAPES_ITS_NAMESPACE: u32 = 1 << 27;
+/// On the first component of a compound: how many components the compound has, where it has fewer than 16, so that a
+/// walk steps from a compound to the next one without reading the components between; zero for a longer compound,
+/// which a walk reads to its end.
+const COMPOUND_LENGTH_SHIFT: u32 = 28;
+const COMPOUND_LENGTH_BITS: u32 = 0xf << COMPOUND_LENGTH_SHIFT;
+
+/// The kind, relation and flags of a component, in 32 bits.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+#[repr(transparent)]
+struct ComponentBits(u32);
+
+impl ComponentBits {
+ fn new(kind: ComponentKind) -> Self {
+ Self(kind as u32)
+ }
+
+ fn kind(self) -> ComponentKind {
+ const KINDS: [ComponentKind; 10] = [
+ ComponentKind::Universal,
+ ComponentKind::Tag,
+ ComponentKind::Id,
+ ComponentKind::Class,
+ ComponentKind::Attribute,
+ ComponentKind::PseudoClass,
+ ComponentKind::PseudoElement,
+ ComponentKind::Nesting,
+ ComponentKind::Invalid,
+ ComponentKind::RelativeAnchor,
+ ];
+ KINDS[(self.0 & KIND_BITS) as usize]
+ }
+
+ fn relation(self) -> Relation {
+ const RELATIONS: [Relation; 8] = [
+ Relation::SubSelector,
+ Relation::Descendant,
+ Relation::Child,
+ Relation::NextSibling,
+ Relation::SubsequentSibling,
+ Relation::Column,
+ Relation::PseudoElement,
+ Relation::Leftmost,
+ ];
+ RELATIONS[((self.0 & RELATION_BITS) >> RELATION_SHIFT) as usize]
+ }
+
+ fn with_relation(self, relation: Relation) -> Self {
+ Self((self.0 & !RELATION_BITS) | ((relation as u32) << RELATION_SHIFT))
+ }
+
+ fn pseudo(self) -> u8 {
+ ((self.0 & PSEUDO_BITS) >> PSEUDO_SHIFT) as u8
+ }
+
+ fn with_pseudo(self, pseudo: u8) -> Self {
+ Self((self.0 & !PSEUDO_BITS) | (u32::from(pseudo) << PSEUDO_SHIFT))
+ }
+
+ fn namespace(self) -> NamespaceType {
+ const TYPES: [NamespaceType; 4] = [
+ NamespaceType::Default,
+ NamespaceType::None,
+ NamespaceType::Any,
+ NamespaceType::Named,
+ ];
+ TYPES[((self.0 & NAMESPACE_BITS) >> NAMESPACE_SHIFT) as usize]
+ }
+
+ fn with_namespace(self, namespace: NamespaceType) -> Self {
+ Self((self.0 & !NAMESPACE_BITS) | ((namespace as u32) << NAMESPACE_SHIFT))
+ }
+
+ fn with(self, flag: u32, set: bool) -> Self {
+ Self(if set { self.0 | flag } else { self.0 & !flag })
+ }
+
+ fn has(self, flag: u32) -> bool {
+ self.0 & flag != 0
+ }
+}
+
+/// One simple selector of a complex selector. The last component of each compound carries the
+/// relation to the compound left of it.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+#[repr(C)]
+struct Component {
+ bits: ComponentBits,
+ /// What `bits` says it is: an atom, a list start, an inline `an+b`, or an index in a pool.
+ data: u32,
+}
+const _: () = assert!(size_of::<Component>() == 8);
+
+/// No list, no payload.
+const NONE: u32 = u32::MAX;
+
+/// A name written with an explicit namespace prefix.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+struct QualifiedRare {
+ prefix: StyleAtomID,
+ local: StyleAtomID,
+}
+
+/// `[x op v]`. The operator and case live in the component's pseudo bits, the namespace in its
+/// namespace bits.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+struct AttributeRare {
+ name: QualifiedRare,
+ value: StyleAtomID,
+ text: PoolRange,
+}
+
+/// `:nth-*()` outside the inline range, or with `of S`.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+struct NthRare {
+ a: i32,
+ b: i32,
+ of: u32,
+}
+
+/// The arguments of a pseudo-class that takes something other than selectors.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum ArgumentRare {
+ /// `:dir()`, `:state()` and the other pseudo-classes taking one identifier.
+ Ident {
+ text: PoolRange,
+ atom: StyleAtomID,
+ direction: Option<Direction>,
+ },
+ /// `:lang()`: ranges into the arena's text ranges; a range with its top length bit set was written as a string.
+ Languages { ranges: PoolRange },
+ /// `:heading()`: levels into the arena's numbers.
+ Levels { levels: PoolRange },
+}
+
+const STRING_BIT: u32 = 1 << 31;
+
+/// What a pseudo-element names beside its kind.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+struct PseudoElementRare {
+ serialized_name: Option<PoolRange>,
+ value: PseudoElementRareValue,
+ identifier_identities: PoolRange,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum PseudoElementRareValue {
+ None,
+ CompoundSelector(ListStart),
+ /// Ranges into the arena's text ranges.
+ Identifiers(PoolRange),
+ TransitionName {
+ /// None for no name, `Some(None)` for `*`.
+ name: Option<Option<PoolRange>>,
+ /// Ranges into the arena's text ranges.
+ classes: PoolRange,
+ },
+}
+
+/// The `@namespace` declarations of the sheet an arena's selectors are of, as process atoms.
+///
+/// A prefix means whatever its sheet says it means, and an unprefixed type or universal selector
+/// means the sheet's default namespace where one is declared.
+#[derive(Clone, Copy, Debug, Default)]
+pub struct SheetNamespaces<'a> {
+ /// The sheet's default namespace, or `None` when it declared none - in which case an
+ /// unprefixed name constrains no namespace at all.
+ pub default: Option<StyleAtomID>,
+ /// Each declared prefix followed by the namespace it names.
+ prefixes: &'a [StyleAtomID],
+}
+
+impl<'a> SheetNamespaces<'a> {
+ /// The declarations of a default namespace, where `default` is one, and of the prefixes
+ /// `prefixes` holds, each followed by the namespace it names.
+ #[must_use]
+ pub fn new(default: Option<StyleAtomID>, prefixes: &'a [StyleAtomID]) -> Self {
+ debug_assert!(
+ prefixes.len().is_multiple_of(2),
+ "a prefix is followed by its namespace"
+ );
+ Self { default, prefixes }
+ }
+
+ /// The namespace `prefix` names, where the sheet declares it.
+ #[must_use]
+ pub fn namespace_of(self, prefix: StyleAtomID) -> Option<StyleAtomID> {
+ self.prefixes
+ .as_chunks::<2>()
+ .0
+ .iter()
+ .find(|declared| declared[0] == prefix)
+ .map(|declared| declared[1])
+ }
+}
+
+/// The `@namespace` declarations of a sheet, with the leases keeping the names they intern live
+/// until an arena leases them.
+#[derive(Default)]
+pub(crate) struct NamespaceDeclarations {
+ default: Option<StyleAtomID>,
+ /// Each declared prefix followed by the namespace it names.
+ prefixes: Vec<StyleAtomID>,
+ names: Vec<crate::css::style::AtomLease>,
+}
+
+impl NamespaceDeclarations {
+ /// The namespaces `declared` declares as prefix and namespace texts, an empty prefix declaring
+ /// the default namespace, and a later declaration of a prefix replacing an earlier one.
+ pub(crate) fn of_texts<'a>(declared: impl IntoIterator<Item = (&'a [u16], &'a [u16])>) -> Self {
+ let mut declarations = Self::default();
+ for (prefix, uri) in declared {
+ declarations.declare(prefix, uri);
+ }
+ declarations
+ }
+
+ fn intern(&mut self, text: &[u16]) -> StyleAtomID {
+ let lease = crate::css::style::process_atoms().intern(text);
+ let atom = lease.atom();
+ self.names.push(lease);
+ atom
+ }
+
+ /// Declare `prefix` to name `uri`, an empty prefix declaring the default namespace.
+ fn declare(&mut self, prefix: &[u16], uri: &[u16]) {
+ let uri = match uri.is_empty() {
+ true => StyleAtomID::NONE,
+ false => self.intern(uri),
+ };
+ if prefix.is_empty() {
+ self.default = Some(uri);
+ return;
+ }
+ let prefix = self.intern(prefix);
+ match self
+ .prefixes
+ .as_chunks_mut::<2>()
+ .0
+ .iter_mut()
+ .find(|declared| declared[0] == prefix)
+ {
+ Some(declared) => declared[1] = uri,
+ None => self.prefixes.extend([prefix, uri]),
+ }
+ }
+}
+
+/// The selectors of one parsed list and the lists nested in it. Immutable once built, and shared
+/// by every document and thread that reaches the list.
+#[derive(Debug)]
+pub(crate) struct SelectorArena {
+ components: Box<[Component]>,
+ qualified: Box<[QualifiedRare]>,
+ attributes: Box<[AttributeRare]>,
+ nths: Box<[NthRare]>,
+ arguments: Box<[ArgumentRare]>,
+ pseudo_elements: Box<[PseudoElementRare]>,
+ atoms: Box<[StyleAtomID]>,
+ numbers: Box<[i64]>,
+ text_ranges: Box<[PoolRange]>,
+ text: Box<[u16]>,
+ /// Where the selectors of each style rule the arena holds start, by the rule's ordinal: what a
+ /// `&` naming the rule reads.
+ rule_lists: Box<[ListStart]>,
+ /// The `@namespace` declarations of the sheet the selectors are of: the default namespace, and
+ /// the prefixes, each followed by the namespace it names, in `atoms`.
+ default_namespace: Option<StyleAtomID>,
+ namespace_prefixes: PoolRange,
+ serial: SelectorArenaSerial,
+ /// What matching asks of each compound as a whole, by where the compound starts, in the order of the
+ /// components.
+ compounds: Box<[CompoundFacts]>,
+ /// Which components start a compound, a bit each, which [`Self::compounds`] is numbered by.
+ compound_starts: Box<[u64]>,
+ /// How many compounds start before each word of `compound_starts`, so that a compound's facts
+ /// are found from where it starts without a search.
+ compound_ranks: Box<[u32]>,
+ _leases: AtomLeases,
+}
+
+const _: fn() = || {
+ fn assert_send_sync<T: Send + Sync>() {}
+ assert_send_sync::<SelectorArena>();
+};
+
+impl SelectorArena {
+ fn text(&self, range: PoolRange) -> &[u16] {
+ PoolRange::of(&self.text, range)
+ }
+
+ fn selectors_of(&self, start: Option<ListStart>) -> SelectorsOf<'_> {
+ SelectorsOf {
+ arena: self,
+ at: start.map_or(usize::MAX, |start| start.0 as usize),
+ }
+ }
+
+ fn decode(&self, at: usize) -> SimpleSelector<'_> {
+ let Component { bits, data } = self.components[at];
+ let qualified = |namespace: NamespaceType| -> QualifiedName {
+ match namespace {
+ NamespaceType::Named => {
+ let rare = self.qualified[data as usize];
+ QualifiedName {
+ namespace_type: namespace,
+ namespace: rare.prefix,
+ name: rare.local,
+ name_is_ascii_lowercase: bits.has(ASCII_LOWERCASE),
+ }
+ }
+ _ => QualifiedName {
+ namespace_type: namespace,
+ namespace: StyleAtomID::NONE,
+ name: StyleAtomID(data),
+ name_is_ascii_lowercase: bits.has(ASCII_LOWERCASE),
+ },
+ }
+ };
+ match bits.kind() {
+ ComponentKind::Universal => SimpleSelector::Universal(qualified(bits.namespace())),
+ ComponentKind::Tag => SimpleSelector::TagName(qualified(bits.namespace())),
+ ComponentKind::Id => SimpleSelector::Id(NameSelector {
+ name: StyleAtomID(data),
+ is_ascii_lowercase: bits.has(ASCII_LOWERCASE),
+ }),
+ ComponentKind::Class => SimpleSelector::Class(NameSelector {
+ name: StyleAtomID(data),
+ is_ascii_lowercase: bits.has(ASCII_LOWERCASE),
+ }),
+ ComponentKind::Attribute => {
+ let rare = &self.attributes[data as usize];
+ let namespace_type = bits.namespace();
+ SimpleSelector::Attribute(AttributeSelector {
+ match_type: attribute_operator(bits.pseudo() & 0b111),
+ qualified_name: QualifiedName {
+ namespace_type,
+ namespace: rare.name.prefix,
+ name: rare.name.local,
+ name_is_ascii_lowercase: bits.has(ASCII_LOWERCASE),
+ },
+ value: self.text(rare.text),
+ value_identity: rare.value,
+ case_type: attribute_case(bits.pseudo() >> 3),
+ names_a_legacy_case_insensitive_attribute: bits.has(LEGACY_CASE_INSENSITIVE),
+ })
+ }
+ ComponentKind::PseudoClass => self.decode_pseudo_class(bits, data),
+ ComponentKind::PseudoElement => self.decode_pseudo_element(bits, data),
+ ComponentKind::Nesting => SimpleSelector::Nesting(match bits.pseudo() {
+ NESTING_ROOT => Nesting::Root,
+ NESTING_SCOPE => Nesting::Scope,
+ NESTING_RULE => Nesting::Rule(SelectorListView {
+ arena: self,
+ start: Some(self.rule_lists[data as usize]),
+ }),
+ _ => Nesting::Unbound,
+ }),
+ ComponentKind::Invalid => SimpleSelector::Invalid(self.text(self.text_ranges[data as usize])),
+ ComponentKind::RelativeAnchor => unreachable!("a relative anchor is not among a compound's selectors"),
+ }
+ }
+
+ /// The list a component names by where it starts, or none by `NONE`.
+ fn list_at(&self, data: u32) -> SelectorListView<'_> {
+ SelectorListView {
+ arena: self,
+ start: (data != NONE).then_some(ListStart(data)),
+ }
+ }
+
+ fn decode_pseudo_class(&self, bits: ComponentBits, data: u32) -> SimpleSelector<'_> {
+ let pseudo_class = pseudo_class_from_ffi(bits.pseudo());
+ let mut selector = PseudoClassSelector {
+ pseudo_class,
+ an_plus_b_pattern: AnPlusBPattern::default(),
+ argument_selector_list: self.list_at(NONE),
+ languages: Languages {
+ arena: self,
+ ranges: &[],
+ },
+ direction: None,
+ identifier: None,
+ identifier_identity: StyleAtomID::NONE,
+ levels: &[],
+ is_forgiving: bits.has(FORGIVING),
+ };
+ match pseudo_class.metadata().parameter_type {
+ PseudoClassParameterType::AnPlusB | PseudoClassParameterType::AnPlusBOf => {
+ if data != NONE {
+ let (a, b, of) = match bits.has(INLINE) {
+ true => (
+ i32::from((data >> 16) as u16 as i16),
+ i32::from(data as u16 as i16),
+ NONE,
+ ),
+ false => {
+ let nth = self.nths[data as usize];
+ (nth.a, nth.b, nth.of)
+ }
+ };
+ selector.an_plus_b_pattern = AnPlusBPattern {
+ step_size: a,
+ offset: b,
+ };
+ selector.argument_selector_list = self.list_at(of);
+ }
+ }
+ PseudoClassParameterType::Ident
+ | PseudoClassParameterType::LanguageRanges
+ | PseudoClassParameterType::LevelList => {
+ if data != NONE {
+ match self.arguments[data as usize] {
+ ArgumentRare::Ident { text, atom, direction } => {
+ selector.identifier = Some(self.text(text));
+ selector.identifier_identity = atom;
+ selector.direction = direction;
+ }
+ ArgumentRare::Languages { ranges } => {
+ selector.languages.ranges = PoolRange::of(&self.text_ranges, ranges);
+ }
+ ArgumentRare::Levels { levels } => {
+ selector.levels = PoolRange::of(&self.numbers, levels);
+ }
+ }
+ }
+ }
+ PseudoClassParameterType::None => {}
+ PseudoClassParameterType::CompoundSelector
+ | PseudoClassParameterType::ForgivingSelectorList
+ | PseudoClassParameterType::RelativeSelectorList
+ | PseudoClassParameterType::SelectorList => selector.argument_selector_list = self.list_at(data),
+ }
+ SimpleSelector::PseudoClass(selector)
+ }
+
+ fn decode_pseudo_element(&self, bits: ComponentBits, data: u32) -> SimpleSelector<'_> {
+ let pseudo_element = crate::css::selector::pseudo_element_from_ffi(bits.pseudo());
+ let Some(rare) = (data != NONE).then(|| self.pseudo_elements[data as usize]) else {
+ return SimpleSelector::PseudoElement(PseudoElementSelector {
+ pseudo_element,
+ serialized_name: None,
+ value: PseudoElementValue::None,
+ identifier_identities: &[],
+ });
+ };
+ let texts = |range: PoolRange| TextList {
+ arena: self,
+ ranges: PoolRange::of(&self.text_ranges, range),
+ };
+ SimpleSelector::PseudoElement(PseudoElementSelector {
+ pseudo_element,
+ serialized_name: rare.serialized_name.map(|range| self.text(range)),
+ value: match rare.value {
+ PseudoElementRareValue::None => PseudoElementValue::None,
+ PseudoElementRareValue::CompoundSelector(start) => PseudoElementValue::CompoundSelector(
+ self.selectors_of(Some(start)).next().expect("a list holds a selector"),
+ ),
+ PseudoElementRareValue::Identifiers(range) => PseudoElementValue::Identifiers(texts(range)),
+ PseudoElementRareValue::TransitionName { name, classes } => {
+ PseudoElementValue::TransitionName(TransitionNameAndClassSelector {
+ name: name.map(|name| match name {
+ None => TransitionNameSelector::Universal,
+ Some(range) => TransitionNameSelector::Name(self.text(range)),
+ }),
+ classes: texts(classes),
+ })
+ }
+ },
+ identifier_identities: PoolRange::of(&self.atoms, rare.identifier_identities),
+ })
+ }
+}
+
+impl SelectorArena {
+ /// Where the compound starting at `start` ends, past its last component.
+ #[inline]
+ fn compound_end(&self, start: usize) -> usize {
+ // NB: A compound shorter than 16 components says its length on its first component.
+ let length = ((self.components[start].bits.0 & COMPOUND_LENGTH_BITS) >> COMPOUND_LENGTH_SHIFT) as usize;
+ if length != 0 {
+ return start + length;
+ }
+ let mut end = start;
+ while self.components[end].bits.relation() == Relation::SubSelector {
+ end += 1;
+ }
+ end + 1
+ }
+}
+
+fn attribute_operator(value: u8) -> AttributeMatchType {
+ const OPERATORS: [AttributeMatchType; 7] = [
+ AttributeMatchType::HasAttribute,
+ AttributeMatchType::ExactValue,
+ AttributeMatchType::ContainsWord,
+ AttributeMatchType::ContainsString,
+ AttributeMatchType::StartsWithSegment,
+ AttributeMatchType::StartsWithString,
+ AttributeMatchType::EndsWithString,
+ ];
+ OPERATORS[value as usize]
+}
+
+fn attribute_case(value: u8) -> AttributeCaseType {
+ const CASES: [AttributeCaseType; 3] = [
+ AttributeCaseType::Default,
+ AttributeCaseType::Sensitive,
+ AttributeCaseType::Insensitive,
+ ];
+ CASES[value as usize]
+}
+
+/// A selector's identity in the process, from one of its compounds leftwards.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub(crate) struct SelectorKey {
+ pub(crate) arena: SelectorArenaSerial,
+ pub(crate) at: ComponentOffset,
+}
+
+/// One complex selector, by the offset of its subject component in its arena.
+#[derive(Clone, Copy, Debug)]
+pub struct Selector<'a> {
+ arena: &'a SelectorArena,
+ at: ComponentOffset,
+}
+
+impl PartialEq for Selector<'_> {
+ fn eq(&self, other: &Self) -> bool {
+ std::ptr::eq(self.arena, other.arena) && self.at == other.at
+ }
+}
+
+impl Eq for Selector<'_> {}
+
+/// One compound of a complex selector, as a range of its components, which it decodes one by one
+/// as they are read.
+#[derive(Clone, Copy, Debug)]
+pub struct CompoundRef<'a> {
+ /// The combinator relating this compound to the compound immediately to its left. The
+ /// leftmost compound therefore has `Combinator::None`, unless the selector is relative.
+ pub combinator: Combinator,
+ pub is_implicit_universal_anchor: bool,
+ pub simple_selectors: SimpleSelectors<'a>,
+}
+
+/// The simple selectors of a compound, decoded from their components as they are read.
+#[derive(Clone, Copy, Debug)]
+pub struct SimpleSelectors<'a> {
+ arena: &'a SelectorArena,
+ start: u32,
+ end: u32,
+}
+
+impl<'a> SimpleSelectors<'a> {
+ fn new(arena: &'a SelectorArena, start: usize, end: usize) -> Self {
+ Self {
+ arena,
+ start: index_u32(start),
+ end: index_u32(end),
+ }
+ }
+
+ #[must_use]
+ pub fn len(self) -> usize {
+ (self.end - self.start) as usize
+ }
+
+ #[must_use]
+ pub fn is_empty(self) -> bool {
+ self.start == self.end
+ }
+
+ #[must_use]
+ pub fn get(self, index: usize) -> Option<SimpleSelector<'a>> {
+ (index < self.len()).then(|| self.arena.decode(self.start as usize + index))
+ }
+
+ #[must_use]
+ pub fn first(self) -> Option<SimpleSelector<'a>> {
+ self.get(0)
+ }
+
+ /// The simple selectors after the first.
+ #[must_use]
+ pub fn after_first(self) -> Self {
+ Self {
+ start: (self.start + 1).min(self.end),
+ ..self
+ }
+ }
+
+ pub fn iter(self) -> impl DoubleEndedIterator<Item = SimpleSelector<'a>> + ExactSizeIterator + 'a {
+ let arena = self.arena;
+ (self.start as usize..self.end as usize).map(move |index| arena.decode(index))
+ }
+
+ /// The simple selectors as their components say them: an id or a class by its name alone, read where it lies,
+ /// and any other to be decoded where it is asked for.
+ pub(crate) fn views(self) -> impl Iterator<Item = SimpleView<'a>> + 'a {
+ let arena = self.arena;
+ (self.start as usize..self.end as usize).map(move |index| {
+ let Component { bits, data } = arena.components[index];
+ let name = || NameSelector {
+ name: StyleAtomID(data),
+ is_ascii_lowercase: bits.has(ASCII_LOWERCASE),
+ };
+ match bits.kind() {
+ ComponentKind::Id => SimpleView::Id(name()),
+ ComponentKind::Class => SimpleView::Class(name()),
+ ComponentKind::Tag if bits.namespace() != NamespaceType::Named => SimpleView::TagName(QualifiedName {
+ namespace_type: bits.namespace(),
+ namespace: StyleAtomID::NONE,
+ name: StyleAtomID(data),
+ name_is_ascii_lowercase: bits.has(ASCII_LOWERCASE),
+ }),
+ ComponentKind::PseudoClass => SimpleView::PseudoClass {
+ kind: pseudo_class_from_ffi(bits.pseudo()),
+ is_search_text_filter: bits.has(SEARCH_TEXT_FILTER),
+ component: ComponentRef { arena, index },
+ },
+ _ => SimpleView::Other(ComponentRef { arena, index }),
+ }
+ })
+ }
+}
+
+/// A simple selector as its component says it, which matching reads without decoding the common kinds.
+#[derive(Clone, Copy, Debug)]
+pub(crate) enum SimpleView<'a> {
+ Id(NameSelector),
+ Class(NameSelector),
+ /// A type selector naming no namespace prefix.
+ TagName(QualifiedName),
+ /// A pseudo-class, by its kind as the component says it, which needs no decode to tell a state or a structural
+ /// test taking no argument, with the component to decode for the rest.
+ PseudoClass {
+ kind: PseudoClassType,
+ /// Whether a `:not()` only picks the kind of search text match its entry styles.
+ is_search_text_filter: bool,
+ component: ComponentRef<'a>,
+ },
+ /// Any other simple selector.
+ Other(ComponentRef<'a>),
+}
+
+/// A name of a compound its id and class selectors test.
+#[derive(Clone, Copy, Debug)]
+pub(crate) enum IdOrClass {
+ Id(NameSelector),
+ Class(NameSelector),
+}
+
+/// A component of an arena, to be decoded where it is asked for.
+#[derive(Clone, Copy, Debug)]
+pub(crate) struct ComponentRef<'a> {
+ arena: &'a SelectorArena,
+ index: usize,
+}
+
+impl<'a> SimpleSelector<'a> {
+ /// The selectors nested in the simple selector: what a pseudo-class takes, what a `::slotted()` takes, and the
+ /// selectors of the style rule a `&` names.
+ pub(crate) fn nested(&self) -> impl Iterator<Item = Selector<'a>> + 'a {
+ let (list, argument) = match self {
+ Self::PseudoClass(pseudo_class) => (Some(pseudo_class.argument_selector_list), None),
+ Self::PseudoElement(PseudoElementSelector {
+ value: PseudoElementValue::CompoundSelector(argument),
+ ..
+ }) => (None, Some(*argument)),
+ Self::Nesting(Nesting::Rule(parent)) => (Some(*parent), None),
+ _ => (None, None),
+ };
+ list.into_iter().flatten().chain(argument)
+ }
+}
+
+impl<'a> SimpleView<'a> {
+ /// The simple selector, decoded.
+ #[must_use]
+ pub(crate) fn decode(self) -> SimpleSelector<'a> {
+ match self {
+ Self::Id(name) => SimpleSelector::Id(name),
+ Self::Class(name) => SimpleSelector::Class(name),
+ Self::TagName(name) => SimpleSelector::TagName(name),
+ Self::Other(other) | Self::PseudoClass { component: other, .. } => other.arena.decode(other.index),
+ }
+ }
+}
+
+impl<'a> Selector<'a> {
+ /// Where the selector starts in its arena.
+ #[must_use]
+ pub(crate) fn offset(self) -> ComponentOffset {
+ self.at
+ }
+
+ /// Whether the selector, which starts here, names the scoping root: `:scope`, or a `&` directly inside `@scope`,
+ /// anywhere in it.
+ #[must_use]
+ pub(crate) fn names_the_scope(self) -> bool {
+ self.arena.components[self.at.0 as usize].bits.has(NAMES_THE_SCOPE)
+ }
+
+ /// Whether the selector, which starts here, holds no pseudo-element, `::part()` or `::slotted()` in its subject
+ /// compound, as the arena noted as it froze.
+ #[must_use]
+ pub(crate) fn describes_its_subject(self) -> bool {
+ self.arena.components[self.at.0 as usize]
+ .bits
+ .has(DESCRIBES_ITS_SUBJECT)
+ }
+
+ /// Whether the selector, which starts here, names an element in another tree, with `::slotted()` or `::part()`.
+ #[must_use]
+ pub(crate) fn escapes_its_namespace(self) -> bool {
+ self.arena.components[self.at.0 as usize]
+ .bits
+ .has(ESCAPES_ITS_NAMESPACE)
+ }
+
+ /// The selector's identity in the process: its arena's serial, and where it starts there.
+ #[must_use]
+ pub(crate) fn key(self) -> SelectorKey {
+ SelectorKey {
+ arena: self.arena.serial,
+ at: self.at,
+ }
+ }
+
+ /// The compounds of the selector in matching order, each as the range of its components and
+ /// its relation to the compound left of it.
+ fn compound_ranges(self) -> SmallVec<[(usize, usize, Relation); 8]> {
+ let mut compounds = SmallVec::new();
+ let mut start = self.at.0 as usize;
+ let mut index = start;
+ loop {
+ let relation = self.arena.components[index].bits.relation();
+ index += 1;
+ if relation == Relation::SubSelector {
+ continue;
+ }
+ compounds.push((start, index, relation));
+ if relation == Relation::Leftmost {
+ return compounds;
+ }
+ start = index;
+ }
+ }
+
+ /// The selector of the same arena from `at`, the start of one of its compounds, leftwards: what
+ /// is left to match of a selector once a walk along it reached that compound.
+ #[must_use]
+ pub(crate) fn at_compound(self, at: ComponentOffset) -> Self {
+ Self { arena: self.arena, at }
+ }
+
+ /// The `@namespace` declarations of the sheet the selector is of.
+ #[must_use]
+ pub(crate) fn namespaces(self) -> SheetNamespaces<'a> {
+ SheetNamespaces::new(
+ self.arena.default_namespace,
+ PoolRange::of(&self.arena.atoms, self.arena.namespace_prefixes),
+ )
+ }
+
+ /// Where the first compound ends, past its last component, with that component's relation.
+ #[inline]
+ fn first_compound_end(self) -> (usize, Relation) {
+ let end = self.arena.compound_end(self.at.0 as usize);
+ (end, self.arena.components[end - 1].bits.relation())
+ }
+
+ /// The first compound, the subject's, as the matcher reads it.
+ #[must_use]
+ pub(crate) fn first_compound(self) -> CompoundRef<'a> {
+ let start = self.at.0 as usize;
+ let (end, relation) = self.first_compound_end();
+ let first = self.arena.components[start];
+ CompoundRef {
+ combinator: relation.combinator(),
+ is_implicit_universal_anchor: first.bits.kind() == ComponentKind::Universal && first.bits.has(IMPLICIT),
+ simple_selectors: match first.bits.kind() {
+ ComponentKind::RelativeAnchor => SimpleSelectors::new(self.arena, start, start),
+ _ => SimpleSelectors::new(self.arena, start, end),
+ },
+ }
+ }
+
+ /// What the arena noted of the first compound as it froze.
+ #[inline]
+ fn compound_facts(self) -> Option<&'a CompoundFacts> {
+ let at = self.at.0 as usize;
+ let (word, bit) = (at / 64, at % 64);
+ let starts = *self.arena.compound_starts.get(word)?;
+ if starts & (1 << bit) == 0 {
+ return None;
+ }
+ let index = self.arena.compound_ranks[word] + (starts & ((1 << bit) - 1)).count_ones();
+ self.arena.compounds.get(index as usize)
+ }
+
+ /// The dispatch bloom bits of the ids, classes, lowercase types and states the first compound tests, as the arena
+ /// noted them as it froze.
+ #[must_use]
+ pub(crate) fn required_dispatch_bloom(self) -> u64 {
+ self.compound_facts().map_or(0, |facts| facts.bloom)
+ }
+
+ /// What tells the tests of the first compound from those of other compounds, alike for compounds of the arena
+ /// testing the same facts alike, whatever selector they are of: what an answer of the compound's own tests can be
+ /// shared by. None for a compound whose tests read the selector they are of or the tree its rule decides in, as
+ /// `:scope`, `&`, `:host` and pseudo-elements do.
+ #[must_use]
+ pub(crate) fn own_tests(self) -> Option<(SelectorArenaSerial, u32)> {
+ self.compound_facts()
+ .filter(|facts| facts.shape != CompoundFacts::NO_SHAPE)
+ .map(|facts| (self.arena.serial, facts.shape))
+ }
+
+ /// The ids, as `false`, and the classes, as `true`, the first compound tests, read from its components.
+ pub(crate) fn ids_and_classes(self) -> impl Iterator<Item = IdOrClass> + 'a {
+ let (end, _) = self.first_compound_end();
+ let components = &self.arena.components[self.at.0 as usize..end];
+ components.iter().filter_map(|component| {
+ let name = NameSelector {
+ name: StyleAtomID(component.data),
+ is_ascii_lowercase: component.bits.has(ASCII_LOWERCASE),
+ };
+ match component.bits.kind() {
+ ComponentKind::Id => Some(IdOrClass::Id(name)),
+ ComponentKind::Class => Some(IdOrClass::Class(name)),
+ _ => None,
+ }
+ })
+ }
+
+ /// Whether the first compound is the implicit anchor a relative selector ends in.
+ #[must_use]
+ pub(crate) fn is_relative_anchor(self) -> bool {
+ self.arena.components[self.at.0 as usize].bits.kind() == ComponentKind::RelativeAnchor
+ }
+
+ /// The combinator left of the first compound, with the selector from the compound left of it,
+ /// or none where the first compound is the leftmost.
+ #[must_use]
+ pub(crate) fn left(self) -> Option<(Combinator, Self)> {
+ let (end, relation) = self.first_compound_end();
+ (relation != Relation::Leftmost)
+ .then(|| (relation.combinator(), self.at_compound(ComponentOffset(index_u32(end)))))
+ }
+
+ /// The selector from the compound right of the first one, in the complex selector the first
+ /// compound is of, or none where the first compound is that selector's subject.
+ #[must_use]
+ pub(crate) fn right(self) -> Option<Self> {
+ let at = self.at.0 as usize;
+ // NB: Every list ends its last selector with a leftmost compound, and nested lists stand
+ // before the selectors holding them, so what stands right before a subject ends
+ // another selector.
+ if at == 0 || self.arena.components[at - 1].bits.relation() == Relation::Leftmost {
+ return None;
+ }
+ let mut start = at - 1;
+ while start > 0 && self.arena.components[start - 1].bits.relation() == Relation::SubSelector {
+ start -= 1;
+ }
+ Some(self.at_compound(ComponentOffset(index_u32(start))))
+ }
+
+ /// The selector from the compound of this selector, or of one nested in it, holding the
+ /// pseudo-class, pseudo-element or `&` whose list holds `nested`, or none where none does.
+ #[must_use]
+ pub(crate) fn compound_owning(self, nested: Self) -> Option<Self> {
+ for (start, end, _) in self.compound_ranges() {
+ for index in start..end {
+ if self.arena.components[index].bits.kind() == ComponentKind::RelativeAnchor {
+ continue;
+ }
+ for selector in self.arena.decode(index).nested() {
+ if selector.at == nested.at {
+ return Some(self.at_compound(ComponentOffset(index_u32(start))));
+ }
+ if let Some(found) = selector.compound_owning(nested) {
+ return Some(found);
+ }
+ }
+ }
+ }
+ None
+ }
+
+ /// The compounds of the selector, left to right.
+ #[must_use]
+ pub fn compound_selectors(self) -> SmallVec<[CompoundRef<'a>; 4]> {
+ let ranges = self.compound_ranges();
+ let mut compounds = SmallVec::with_capacity(ranges.len());
+ // NB: Each compound holds its relation to the compound left of it, the next in matching
+ // order, and a relative selector's leftmost compound is an implicit anchor, so the
+ // first compound written holds the leading combinator.
+ for &(start, end, relation) in ranges.iter().rev() {
+ let first = self.arena.components[start];
+ if first.bits.kind() == ComponentKind::RelativeAnchor {
+ continue;
+ }
+ compounds.push(CompoundRef {
+ combinator: relation.combinator(),
+ is_implicit_universal_anchor: first.bits.kind() == ComponentKind::Universal && first.bits.has(IMPLICIT),
+ simple_selectors: SimpleSelectors::new(self.arena, start, end),
+ });
+ }
+ compounds
+ }
+
+ /// The compounds of the selector in matching order, from the subject leftwards, without the
+ /// implicit anchor a relative selector ends in. Each is read where it lies in the arena.
+ pub(crate) fn compounds(self) -> impl Iterator<Item = CompoundRef<'a>> + 'a {
+ self.chain().map(Selector::first_compound)
+ }
+
+ /// The selector from each of its compounds leftwards, from this one on, without the implicit
+ /// anchor a relative selector ends in.
+ pub(crate) fn chain(self) -> impl Iterator<Item = Self> + 'a {
+ std::iter::successors(Some(self), |current| current.left().map(|(_, left)| left))
+ .filter(|current| !current.is_relative_anchor())
+ }
+
+ /// The leftmost compound of the selector that is not a relative selector's implicit anchor:
+ /// the one that holds a relative selector's leading combinator.
+ #[must_use]
+ pub(crate) fn leftmost_compound(self) -> CompoundRef<'a> {
+ self.chain().last().unwrap_or(self).first_compound()
+ }
+
+ /// The pseudo-element required on the initial match target, if this selector ends in one.
+ #[must_use]
+ pub fn target_pseudo_element(self) -> Option<PseudoElementType> {
+ // NB: The compound a selector ends in is its first in matching order, the subject's.
+ let first = self.arena.components[self.at.0 as usize];
+ if first.bits.kind() != ComponentKind::PseudoElement {
+ return None;
+ }
+ let last = self.first_compound();
+ let pseudo_element = match last.simple_selectors.first()? {
+ SimpleSelector::PseudoElement(selector)
+ if !matches!(
+ selector.pseudo_element,
+ PseudoElementType::Part | PseudoElementType::Slotted
+ ) =>
+ {
+ selector.pseudo_element
+ }
+ _ => return None,
+ };
+ let names_current_match = pseudo_element == PseudoElementType::SearchText
+ && last
+ .simple_selectors
+ .iter()
+ .any(|simple| search_text_match_filter(&simple) == Some(SearchTextMatchFilter::Current));
+ Some(if names_current_match {
+ PseudoElementType::SearchTextCurrent
+ } else {
+ pseudo_element
+ })
+ }
+
+ #[must_use]
+ pub fn styles_every_search_text_match(self) -> bool {
+ self.target_pseudo_element() == Some(PseudoElementType::SearchText)
+ && self
+ .first_compound()
+ .simple_selectors
+ .iter()
+ .all(|simple| search_text_match_filter(&simple).is_none())
+ }
+
+ /// https://www.w3.org/TR/selectors-4/#specificity-rules
+ ///
+ /// NB: A `&` naming a style rule adds what `:is()` of that rule's selectors would, and any
+ /// other `&` adds nothing. https://drafts.csswg.org/css-nesting/#nest-selector
+ #[must_use]
+ pub fn specificity(self) -> Specificity {
+ let greatest = |selectors: SelectorListView<'_>| -> Specificity {
+ selectors.iter().map(Selector::specificity).max().unwrap_or_default()
+ };
+ let class = Specificity {
+ classes: 1,
+ ..Specificity::default()
+ };
+ let mut specificity = Specificity::default();
+ for compound in self.compound_selectors() {
+ for simple in compound.simple_selectors.iter() {
+ let simple = &simple;
+ let contribution = match simple {
+ SimpleSelector::Id(_) => Specificity {
+ ids: 1,
+ ..Specificity::default()
+ },
+ SimpleSelector::Class(_) | SimpleSelector::Attribute(_) => class,
+ SimpleSelector::TagName(_) => Specificity {
+ types: 1,
+ ..Specificity::default()
+ },
+ SimpleSelector::PseudoClass(pseudo_class) => match pseudo_class.pseudo_class {
+ PseudoClassType::Has | PseudoClassType::Is | PseudoClassType::Not => {
+ greatest(pseudo_class.argument_selector_list)
+ }
+ PseudoClassType::NthChild | PseudoClassType::NthLastChild | PseudoClassType::Host => {
+ class.saturating_add(greatest(pseudo_class.argument_selector_list))
+ }
+ PseudoClassType::Where => Specificity::default(),
+ _ => class,
+ },
+ SimpleSelector::PseudoElement(pseudo_element) => {
+ // https://drafts.csswg.org/css-view-transitions-2/#pseudo-element-class-additions
+ // The specificity of a named view transition pseudo-element selector with a * argument and with
+ // an empty <pt-class-selector> is zero.
+ if let PseudoElementValue::TransitionName(argument) = &pseudo_element.value
+ && argument.name == Some(TransitionNameSelector::Universal)
+ && argument.classes.is_empty()
+ {
+ Specificity::default()
+ } else {
+ let pseudo_specificity = Specificity {
+ types: 1,
+ ..Specificity::default()
+ };
+ match &pseudo_element.value {
+ PseudoElementValue::CompoundSelector(argument)
+ if pseudo_element.pseudo_element == PseudoElementType::Slotted =>
+ {
+ pseudo_specificity.saturating_add(argument.specificity())
+ }
+ _ => pseudo_specificity,
+ }
+ }
+ }
+ SimpleSelector::Nesting(Nesting::Rule(parent)) => greatest(*parent),
+ SimpleSelector::Nesting(_) => Specificity::default(),
+ SimpleSelector::Universal(_) | SimpleSelector::Invalid(_) => Specificity::default(),
+ };
+ specificity = specificity.saturating_add(contribution);
+ }
+ }
+ specificity
+ }
+}
+
+/// A selector list in its arena, or an empty one.
+#[derive(Clone, Copy, Debug)]
+pub struct SelectorListView<'a> {
+ arena: &'a SelectorArena,
+ start: Option<ListStart>,
+}
+
+impl<'a> SelectorListView<'a> {
+ /// What identifies the list within the process, for as long as the process lives, or none for
+ /// an empty list.
+ #[must_use]
+ pub(crate) fn identity(self) -> Option<(SelectorArenaSerial, ListStart)> {
+ self.start.map(|start| (self.arena.serial, start))
+ }
+
+ pub fn iter(self) -> impl Iterator<Item = Selector<'a>> + 'a {
+ self.arena.selectors_of(self.start)
+ }
+
+ #[must_use]
+ pub fn is_empty(self) -> bool {
+ self.start.is_none()
+ }
+
+ #[must_use]
+ pub fn len(self) -> usize {
+ self.iter().count()
+ }
+
+ /// What each `&` in the list names, nested lists included, or none where it has none. All of
+ /// them name the same: the parse wrote them for one rule.
+ #[must_use]
+ pub fn nesting(self) -> Option<NestingOfArena<'a>> {
+ fn in_selector(selector: Selector<'_>) -> Option<NestingOfArena<'_>> {
+ selector
+ .compound_selectors()
+ .iter()
+ .find_map(|compound| compound.simple_selectors.iter().find_map(|simple| in_simple(&simple)))
+ }
+ fn in_simple<'a>(simple: &SimpleSelector<'a>) -> Option<NestingOfArena<'a>> {
+ match simple {
+ SimpleSelector::Nesting(nesting) => Some(*nesting),
+ _ => simple.nested().find_map(in_selector),
+ }
+ }
+ self.iter().find_map(in_selector)
+ }
+
+ /// The list's one selector, where it holds exactly one.
+ #[must_use]
+ pub fn single(self) -> Option<Selector<'a>> {
+ let mut selectors = self.iter();
+ let first = selectors.next()?;
+ selectors.next().is_none().then_some(first)
+ }
+}
+
+/// A list of literals in an arena, as `:lang()` ranges or `::part()` names.
+#[derive(Clone, Copy, Debug)]
+pub struct TextList<'a> {
+ arena: &'a SelectorArena,
+ ranges: &'a [PoolRange],
+}
+
+impl<'a> TextList<'a> {
+ pub fn iter(self) -> impl Iterator<Item = &'a [u16]> + 'a {
+ self.ranges.iter().map(move |&range| self.arena.text(range))
+ }
+
+ #[must_use]
+ pub fn is_empty(self) -> bool {
+ self.ranges.is_empty()
+ }
+
+ #[must_use]
+ pub fn len(self) -> usize {
+ self.ranges.len()
+ }
+}
+
+/// The language ranges of `:lang()`.
+#[derive(Clone, Copy, Debug)]
+pub struct Languages<'a> {
+ arena: &'a SelectorArena,
+ ranges: &'a [PoolRange],
+}
+
+/// One range of `:lang()`, as written.
+#[derive(Clone, Copy, Debug)]
+pub struct LanguageRange<'a> {
+ pub value: &'a [u16],
+ pub is_string: bool,
+}
+
+impl<'a> Languages<'a> {
+ pub fn iter(self) -> impl Iterator<Item = LanguageRange<'a>> + 'a {
+ self.ranges.iter().map(move |&range| LanguageRange {
+ value: self.arena.text(PoolRange {
+ start: range.start,
+ length: range.length & !STRING_BIT,
+ }),
+ is_string: range.length & STRING_BIT != 0,
+ })
+ }
+
+ #[must_use]
+ pub fn is_empty(self) -> bool {
+ self.ranges.is_empty()
+ }
+}
+
+/// A simple selector, decoded from its component.
+#[derive(Clone, Copy, Debug)]
+pub enum SimpleSelector<'a> {
+ Universal(QualifiedName),
+ TagName(QualifiedName),
+ Id(NameSelector),
+ Class(NameSelector),
+ Attribute(AttributeSelector<'a>),
+ PseudoClass(PseudoClassSelector<'a>),
+ PseudoElement(PseudoElementSelector<'a>),
+ Nesting(NestingOfArena<'a>),
+ Invalid(&'a [u16]),
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct AttributeSelector<'a> {
+ pub match_type: AttributeMatchType,
+ pub qualified_name: QualifiedName,
+ pub value: &'a [u16],
+ /// The value as a process style atom, or none for a presence test.
+ pub value_identity: StyleAtomID,
+ pub case_type: AttributeCaseType,
+ /// Whether the name is one of the attributes whose values HTML compares ASCII case-insensitively, written with
+ /// no namespace.
+ pub names_a_legacy_case_insensitive_attribute: bool,
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct PseudoClassSelector<'a> {
+ pub pseudo_class: PseudoClassType,
+ pub an_plus_b_pattern: AnPlusBPattern,
+ pub argument_selector_list: SelectorListView<'a>,
+ pub languages: Languages<'a>,
+ pub direction: Option<Direction>,
+ pub identifier: Option<&'a [u16]>,
+ /// The identifier as a process style atom, where the pseudo-class names a state by it.
+ pub identifier_identity: StyleAtomID,
+ pub levels: &'a [i64],
+ pub is_forgiving: bool,
+}
+
+#[derive(Clone, Copy, Debug)]
+pub enum PseudoElementValue<'a> {
+ None,
+ CompoundSelector(Selector<'a>),
+ Identifiers(TextList<'a>),
+ TransitionName(TransitionNameAndClassSelector<'a>),
+}
+
+// https://drafts.csswg.org/css-view-transitions-1/#typedef-pt-name-selector
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum TransitionNameSelector<'a> {
+ Universal,
+ Name(&'a [u16]),
+}
+
+// https://drafts.csswg.org/css-view-transitions-2/#typedef-pt-name-and-class-selector
+#[derive(Clone, Copy, Debug)]
+pub struct TransitionNameAndClassSelector<'a> {
+ pub name: Option<TransitionNameSelector<'a>>,
+ pub classes: TextList<'a>,
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct PseudoElementSelector<'a> {
+ pub pseudo_element: PseudoElementType,
+ pub serialized_name: Option<&'a [u16]>,
+ pub value: PseudoElementValue<'a>,
+ /// The process style atom of each name in `value`, when it holds identifiers.
+ pub identifier_identities: &'a [StyleAtomID],
+}
+
+pub fn search_text_match_filter_of_pseudo_class(
+ pseudo_class: &PseudoClassSelector<'_>,
+) -> Option<SearchTextMatchFilter> {
+ match pseudo_class.pseudo_class {
+ PseudoClassType::Current => Some(SearchTextMatchFilter::Current),
+ PseudoClassType::Not => {
+ let argument = pseudo_class.argument_selector_list.single()?;
+ let compounds = argument.compound_selectors();
+ let [compound] = &*compounds else {
+ return None;
+ };
+ (compound.simple_selectors.len() == 1
+ && matches!(
+ compound.simple_selectors.first(),
+ Some(SimpleSelector::PseudoClass(inner)) if inner.pseudo_class == PseudoClassType::Current
+ ))
+ .then_some(SearchTextMatchFilter::NotCurrent)
+ }
+ _ => None,
+ }
+}
+
+pub fn search_text_match_filter(simple: &SimpleSelector<'_>) -> Option<SearchTextMatchFilter> {
+ match simple {
+ SimpleSelector::PseudoClass(pseudo_class) => search_text_match_filter_of_pseudo_class(pseudo_class),
+ _ => None,
+ }
+}
+
+/// The arena a sheet's selectors go into as its parse finishes them, which every handle to them
+/// holds from the start and reads once the parse froze it.
+type SharedArena = Arc<std::sync::OnceLock<SelectorArena>>;
+
+fn frozen(arena: &SharedArena) -> &SelectorArena {
+ arena
+ .get()
+ .expect("a sheet's selectors are read once its parse has finished them")
+}
+
+/// Packs the selector lists of one parse, a whole sheet's or one list's, into one arena, which it
+/// freezes as it drops: every handle it gave out then reads the arena.
+#[derive(Default)]
+pub(crate) struct SheetSelectorsBuilder {
+ builder: Builder,
+ /// The names the parse interned, which stay live until the arena leases them.
+ names: Vec<crate::css::style::AtomLease>,
+ /// The lists copied in, whose arenas keep their names live until this one leases them.
+ copied: Vec<SelectorListRef>,
+ arena: SharedArena,
+}
+
+impl SheetSelectorsBuilder {
+ /// Packs `list`, whose names `names` keeps live and whose `&` names `nesting`, and answers its
+ /// handle.
+ pub(crate) fn push(
+ &mut self,
+ list: &[Arc<tree::CompiledSelector>],
+ names: Vec<crate::css::style::AtomLease>,
+ nesting: NestingTarget,
+ ) -> SelectorListRef {
+ let start = self.builder.push_list(list, nesting);
+ self.names.extend(names);
+ SelectorListRef {
+ arena: Arc::clone(&self.arena),
+ start,
+ }
+ }
+
+ /// Packs a copy of `list` from another arena, whose `&` names `nesting` here.
+ pub(crate) fn push_copy(&mut self, list: &SelectorListRef, nesting: NestingTarget) -> SelectorListRef {
+ let copy = self.push(&list.view().to_tree(), Vec::new(), nesting);
+ self.copied.push(list.clone());
+ copy
+ }
+
+ /// Have the selectors of the arena be of a sheet declaring `declarations`.
+ pub(crate) fn declare_namespaces(&mut self, declarations: NamespaceDeclarations) {
+ self.builder.default_namespace = declarations.default;
+ self.builder.namespace_prefixes = declarations.prefixes;
+ self.names.extend(declarations.names);
+ }
+
+ /// Have the selectors pushed from here on be of a sheet declaring `prefix` to name `uri` as
+ /// well, an empty prefix declaring the default namespace.
+ pub(crate) fn declare_namespace(&mut self, prefix: &[u16], uri: &[u16]) {
+ let mut declarations = NamespaceDeclarations {
+ default: self.builder.default_namespace,
+ prefixes: std::mem::take(&mut self.builder.namespace_prefixes),
+ names: Vec::new(),
+ };
+ declarations.declare(prefix, uri);
+ self.declare_namespaces(declarations);
+ }
+
+ /// Packs the selectors of a style rule as [`Self::push`] does, and answers too the ordinal a
+ /// `&` in a rule nested in it names it by, which an empty list has none of.
+ pub(crate) fn push_rule(
+ &mut self,
+ list: &[Arc<tree::CompiledSelector>],
+ names: Vec<crate::css::style::AtomLease>,
+ nesting: NestingTarget,
+ ) -> (SelectorListRef, Option<RuleOrdinal>) {
+ let selectors = self.push(list, names, nesting);
+ let rule = selectors.start.map(|start| self.builder.push_rule(start));
+ (selectors, rule)
+ }
+}
+
+/// What a `&` in the selectors of a rule placed somewhere names: what the CSSOM knows of the place.
+#[derive(Clone, Copy)]
+pub(crate) enum NestingContext<'a> {
+ Root,
+ Scope,
+ Rule(&'a SelectorListRef),
+}
+
+impl Drop for SheetSelectorsBuilder {
+ fn drop(&mut self) {
+ let arena = std::mem::take(&mut self.builder).finish();
+ assert!(self.arena.set(arena).is_ok(), "a sheet's selectors are frozen once");
+ }
+}
+
+/// A parsed selector list, holding its arena.
+#[derive(Clone, Debug)]
+pub struct SelectorListRef {
+ arena: SharedArena,
+ start: Option<ListStart>,
+}
+
+impl SelectorListRef {
+ /// Packs the parsed list `list`, which names no style rule with a `&`, into an arena of its own.
+ pub(crate) fn pack(list: &[Arc<tree::CompiledSelector>]) -> Self {
+ SheetSelectorsBuilder::default().push(list, Vec::new(), NestingTarget::Root)
+ }
+
+ /// Whether each `&` in the list names what `context` says it does: the same selectors, or a
+ /// copy of them naming what they name.
+ #[must_use]
+ pub(crate) fn is_nested_in(&self, context: NestingContext<'_>) -> bool {
+ fn same(a: SelectorListView<'_>, b: SelectorListView<'_>) -> bool {
+ if std::ptr::eq(a.arena, b.arena) && a.start == b.start {
+ return true;
+ }
+ // NB: The trees name the atoms of live arenas.
+ a.to_tree() == b.to_tree()
+ && match (a.nesting(), b.nesting()) {
+ (Some(Nesting::Rule(a)), Some(Nesting::Rule(b))) => same(a, b),
+ (None, None)
+ | (Some(Nesting::Root), Some(Nesting::Root))
+ | (Some(Nesting::Scope), Some(Nesting::Scope))
+ | (Some(Nesting::Unbound), Some(Nesting::Unbound)) => true,
+ _ => false,
+ }
+ }
+ match (self.view().nesting(), context) {
+ (None, _) | (Some(Nesting::Root), NestingContext::Root) | (Some(Nesting::Scope), NestingContext::Scope) => {
+ true
+ }
+ (Some(Nesting::Rule(parent)), NestingContext::Rule(rule)) => same(parent, rule.view()),
+ _ => false,
+ }
+ }
+
+ /// The list with each `&` in it naming what `context` says, which is the list itself where it
+ /// already does. Otherwise it goes into an arena of its own after the selectors its `&` names,
+ /// which name what they did.
+ #[must_use]
+ pub(crate) fn nested_in(&self, context: NestingContext<'_>) -> Self {
+ if self.is_nested_in(context) {
+ return self.clone();
+ }
+ let mut builder = SheetSelectorsBuilder::default();
+ let nesting = match context {
+ NestingContext::Root => NestingTarget::Root,
+ NestingContext::Scope => NestingTarget::Scope,
+ NestingContext::Rule(rule) => builder
+ .builder
+ .copy_rule(rule.view())
+ .map_or(NestingTarget::Root, NestingTarget::Rule),
+ };
+ // NB: The tree names the atoms of this list's arena, which is live while it is packed again.
+ builder.push(&self.view().to_tree(), Vec::new(), nesting)
+ }
+
+ /// The atoms the list's arena names, which it leases.
+ pub(crate) fn leased_atoms(&self) -> &[StyleAtomID] {
+ frozen(&self.arena)._leases.atoms()
+ }
+
+ /// The serial of the list's arena, which no other arena of the process takes.
+ #[must_use]
+ pub(crate) fn serial(&self) -> SelectorArenaSerial {
+ frozen(&self.arena).serial
+ }
+
+ /// Where the list starts in its arena, or none for an empty list.
+ #[must_use]
+ pub(crate) fn start_offset(&self) -> Option<u32> {
+ self.start.map(|start| start.0)
+ }
+
+ /// How many components the list's arena holds.
+ #[must_use]
+ pub(crate) fn arena_len(&self) -> u32 {
+ index_u32(frozen(&self.arena).components.len())
+ }
+
+ /// The list of the same arena starting at `offset`, where one of its lists starts.
+ #[must_use]
+ pub(crate) fn list_at_offset(&self, offset: u32) -> Self {
+ assert!(offset < self.arena_len(), "a list starts inside its arena");
+ Self {
+ arena: Arc::clone(&self.arena),
+ start: Some(ListStart(offset)),
+ }
+ }
+
+ #[must_use]
+ pub fn view(&self) -> SelectorListView<'_> {
+ SelectorListView {
+ arena: frozen(&self.arena),
+ start: self.start,
+ }
+ }
+
+ pub fn iter(&self) -> impl Iterator<Item = Selector<'_>> + '_ {
+ self.view().iter()
+ }
+
+ /// The selector of the list starting at `offset`, holding its arena.
+ #[must_use]
+ pub(crate) fn selector_ref_at(&self, offset: ComponentOffset) -> SelectorRef {
+ SelectorRef {
+ arena: self.arena.clone(),
+ at: offset,
+ }
+ }
+
+ /// The selector of the list starting at `offset`, which one of the list's selectors names.
+ #[must_use]
+ pub(crate) fn selector_at(&self, offset: ComponentOffset) -> Selector<'_> {
+ Selector {
+ arena: frozen(&self.arena),
+ at: offset,
+ }
+ }
+
+ #[must_use]
+ pub fn is_empty(&self) -> bool {
+ self.start.is_none()
+ }
+
+ #[must_use]
+ pub fn len(&self) -> usize {
+ self.view().len()
+ }
+
+ /// Each selector of the list, holding the arena.
+ pub fn owned(&self) -> impl Iterator<Item = SelectorRef> + '_ {
+ self.iter().map(|selector| SelectorRef {
+ arena: Arc::clone(&self.arena),
+ at: selector.at,
+ })
+ }
+}
+
+/// One parsed selector, holding its arena.
+#[derive(Clone, Debug)]
+pub struct SelectorRef {
+ arena: SharedArena,
+ at: ComponentOffset,
+}
+
+impl SelectorRef {
+ #[must_use]
+ pub fn view(&self) -> Selector<'_> {
+ Selector {
+ arena: frozen(&self.arena),
+ at: self.at,
+ }
+ }
+
+ /// The selector from the compound at `at` leftwards, in the same arena.
+ #[must_use]
+ pub(crate) fn at_compound(&self, at: ComponentOffset) -> Self {
+ Self {
+ arena: self.arena.clone(),
+ at,
+ }
+ }
+}
+
+/// What matching asks of a compound as a whole, which the arena notes as it freezes.
+#[derive(Debug)]
+struct CompoundFacts {
+ /// The compound's own tests, alike for compounds of the arena testing the same facts alike, or
+ /// [`Self::NO_SHAPE`].
+ shape: u32,
+ /// The dispatch bloom bits of the ids, classes, types and attributes written in ASCII lowercase and states the
+ /// compound tests: what an element has to carry to match it, which a walk up across a descendant combinator rejects ancestors on
+ /// and a bucket's candidates are rejected on.
+ bloom: u64,
+}
+
+const _: () = assert!(size_of::<CompoundFacts>() == 16);
+
+impl CompoundFacts {
+ const NO_SHAPE: u32 = u32::MAX;
+}
+
+/// Packs parsed trees into an arena.
+#[derive(Default)]
+struct Builder {
+ components: Vec<Component>,
+ qualified: Vec<QualifiedRare>,
+ attributes: Vec<AttributeRare>,
+ nths: Vec<NthRare>,
+ arguments: Vec<ArgumentRare>,
+ pseudo_elements: Vec<PseudoElementRare>,
+ atoms: Vec<StyleAtomID>,
+ numbers: Vec<i64>,
+ text_ranges: Vec<PoolRange>,
+ text: Vec<u16>,
+ rule_lists: Vec<ListStart>,
+ default_namespace: Option<StyleAtomID>,
+ /// Each declared prefix followed by the namespace it names.
+ namespace_prefixes: Vec<StyleAtomID>,
+ /// What a `&` in the list being pushed names.
+ nesting: NestingTarget,
+ leased: Vec<StyleAtomID>,
+}
+
+fn pool_push<T>(pool: &mut Vec<T>, value: T) -> u32 {
+ pool.push(value);
+ index_u32(pool.len() - 1)
+}
+
+impl Builder {
+ fn push_text(&mut self, text: &[u16]) -> PoolRange {
+ let start = index_u32(self.text.len());
+ self.text.extend_from_slice(text);
+ PoolRange {
+ start,
+ length: index_u32(text.len()),
+ }
+ }
+
+ fn push_text_list<'t>(&mut self, texts: impl IntoIterator<Item = (&'t [u16], bool)>) -> PoolRange {
+ let ranges: Vec<_> = texts
+ .into_iter()
+ .map(|(text, is_string)| {
+ let mut range = self.push_text(text);
+ if is_string {
+ range.length |= STRING_BIT;
+ }
+ range
+ })
+ .collect();
+ let start = index_u32(self.text_ranges.len());
+ self.text_ranges.extend_from_slice(&ranges);
+ PoolRange {
+ start,
+ length: index_u32(ranges.len()),
+ }
+ }
+
+ fn lease(&mut self, atom: StyleAtomID) {
+ if !atom.is_none() {
+ self.leased.push(atom);
+ }
+ }
+
+ /// Pushes `list`, nested lists first, and answers where it starts, or none for an empty list.
+ fn push_list(&mut self, list: &[Arc<tree::CompiledSelector>], nesting: NestingTarget) -> Option<ListStart> {
+ if list.is_empty() {
+ return None;
+ }
+ self.nesting = nesting;
+ // NB: The parser finished every nested list before the list naming it; they go first.
+ let selectors: Vec<Vec<(Combinator, bool, Vec<Component>)>> = list
+ .iter()
+ .map(|selector| {
+ selector
+ .compound_selectors()
+ .iter()
+ .map(|compound| {
+ let components = compound
+ .simple_selectors
+ .iter()
+ .map(|simple| self.component(simple))
+ .collect::<Vec<_>>();
+ (compound.combinator, compound.is_implicit_universal_anchor, components)
+ })
+ .collect()
+ })
+ .collect();
+ let start = ListStart(index_u32(self.components.len()));
+ let count = selectors.len();
+ for (index, compounds) in selectors.into_iter().enumerate() {
+ let leading = compounds.first().map_or(Combinator::None, |compound| compound.0);
+ let compound_count = compounds.len();
+ for (position, (combinator, implicit_anchor, mut components)) in compounds.into_iter().rev().enumerate() {
+ assert!(!components.is_empty(), "a compound holds a simple selector");
+ if implicit_anchor {
+ components[0].bits = components[0].bits.with(IMPLICIT, true);
+ }
+ let leftmost = position + 1 == compound_count;
+ let relation = match leftmost {
+ true if leading != Combinator::None => Relation::of(leading),
+ true => Relation::Leftmost,
+ false => {
+ assert_ne!(
+ combinator,
+ Combinator::None,
+ "only the leftmost compound has no combinator"
+ );
+ Relation::of(combinator)
+ }
+ };
+ let last = components.len() - 1;
+ components[last].bits = components[last].bits.with_relation(relation);
+ if relation == Relation::Leftmost && index + 1 == count {
+ components[last].bits = components[last].bits.with(LAST_IN_LIST, true);
+ }
+ self.components.extend(components);
+ }
+ if leading != Combinator::None {
+ let bits = ComponentBits::new(ComponentKind::RelativeAnchor)
+ .with(IMPLICIT, true)
+ .with_relation(Relation::Leftmost)
+ .with(LAST_IN_LIST, index + 1 == count);
+ self.components.push(Component { bits, data: 0 });
+ }
+ }
+ Some(start)
+ }
+
+ fn push_rule(&mut self, start: ListStart) -> RuleOrdinal {
+ self.rule_lists.push(start);
+ RuleOrdinal(index_u32(self.rule_lists.len() - 1))
+ }
+
+ /// Pushes the selectors of a style rule from another arena, after the selectors their `&` names,
+ /// and answers the rule's ordinal here, or none for an empty list.
+ fn copy_rule(&mut self, list: SelectorListView<'_>) -> Option<RuleOrdinal> {
+ let nesting = match list.nesting() {
+ None | Some(Nesting::Root) => NestingTarget::Root,
+ Some(Nesting::Scope) => NestingTarget::Scope,
+ Some(Nesting::Unbound) => NestingTarget::Unbound,
+ Some(Nesting::Rule(parent)) => self.copy_rule(parent).map_or(NestingTarget::Root, NestingTarget::Rule),
+ };
+ let start = self.push_list(&list.to_tree(), nesting)?;
+ Some(self.push_rule(start))
+ }
+
+ fn qualified_data(&mut self, name: &QualifiedName) -> u32 {
+ self.lease(name.name);
+ match name.namespace_type {
+ NamespaceType::Named => {
+ self.lease(name.namespace);
+ pool_push(
+ &mut self.qualified,
+ QualifiedRare {
+ prefix: name.namespace,
+ local: name.name,
+ },
+ )
+ }
+ _ => name.name.0,
+ }
+ }
+
+ /// The component of `simple`, whose nested lists it pushes first.
+ fn pseudo_class_component(&mut self, pseudo_class: &tree::PseudoClassSelector) -> (ComponentBits, u32) {
+ let bits = ComponentBits::new(ComponentKind::PseudoClass)
+ .with_pseudo(pseudo_class.pseudo_class as u8)
+ .with(FORGIVING, pseudo_class.is_forgiving);
+ let list = |builder: &mut Self| {
+ builder
+ .push_list(&pseudo_class.argument_selector_list, builder.nesting)
+ .map_or(NONE, |start| start.0)
+ };
+ match pseudo_class.pseudo_class.metadata().parameter_type {
+ PseudoClassParameterType::None => (bits, NONE),
+ PseudoClassParameterType::AnPlusB | PseudoClassParameterType::AnPlusBOf => {
+ let of = list(self);
+ let AnPlusBPattern {
+ step_size: a,
+ offset: b,
+ } = pseudo_class.an_plus_b_pattern;
+ match (i16::try_from(a), i16::try_from(b), of) {
+ (Ok(a), Ok(b), NONE) if (u32::from(a as u16) << 16 | u32::from(b as u16)) != NONE => (
+ bits.with(INLINE, true),
+ (u32::from(a as u16) << 16) | u32::from(b as u16),
+ ),
+ _ => (bits, pool_push(&mut self.nths, NthRare { a, b, of })),
+ }
+ }
+ PseudoClassParameterType::Ident => match &pseudo_class.identifier {
+ None => (bits, NONE),
+ Some(identifier) => {
+ // NB: `:dir()` compares its keyword ASCII case-insensitively, as a match
+ // would otherwise fold it through the atom table each time.
+ let atom = match pseudo_class.pseudo_class {
+ PseudoClassType::Dir => {
+ crate::css::style::process_atoms().ascii_lowercase(pseudo_class.identifier_identity)
+ }
+ _ => pseudo_class.identifier_identity,
+ };
+ self.lease(atom);
+ let text = self.push_text(identifier);
+ let rare = ArgumentRare::Ident {
+ text,
+ atom,
+ direction: pseudo_class.direction,
+ };
+ (bits, pool_push(&mut self.arguments, rare))
+ }
+ },
+ PseudoClassParameterType::LanguageRanges => {
+ let ranges = self.push_text_list(
+ pseudo_class
+ .languages
+ .iter()
+ .map(|range| (range.value.units(), range.is_string)),
+ );
+ (bits, pool_push(&mut self.arguments, ArgumentRare::Languages { ranges }))
+ }
+ PseudoClassParameterType::LevelList => {
+ let start = index_u32(self.numbers.len());
+ self.numbers.extend_from_slice(&pseudo_class.levels);
+ let levels = PoolRange {
+ start,
+ length: index_u32(pseudo_class.levels.len()),
+ };
+ (bits, pool_push(&mut self.arguments, ArgumentRare::Levels { levels }))
+ }
+ PseudoClassParameterType::CompoundSelector
+ | PseudoClassParameterType::ForgivingSelectorList
+ | PseudoClassParameterType::RelativeSelectorList
+ | PseudoClassParameterType::SelectorList => (bits, list(self)),
+ }
+ }
+
+ fn pseudo_element_component(&mut self, pseudo_element: &tree::PseudoElementSelector) -> (ComponentBits, u32) {
+ let bits = ComponentBits::new(ComponentKind::PseudoElement).with_pseudo(pseudo_element.pseudo_element as u8);
+ let serialized_name = pseudo_element.serialized_name.as_ref().map(|name| self.push_text(name));
+ let value = match &pseudo_element.value {
+ tree::PseudoElementValue::None => PseudoElementRareValue::None,
+ tree::PseudoElementValue::CompoundSelector(selector) => PseudoElementRareValue::CompoundSelector(
+ self.push_list(std::slice::from_ref(selector), self.nesting)
+ .expect("a one-selector list is not empty"),
+ ),
+ tree::PseudoElementValue::Identifiers(identifiers) => PseudoElementRareValue::Identifiers(
+ self.push_text_list(identifiers.iter().map(|identifier| (identifier.units(), false))),
+ ),
+ tree::PseudoElementValue::TransitionName(argument) => {
+ let name = argument.name.as_ref().map(|name| match name {
+ tree::TransitionNameSelector::Universal => None,
+ tree::TransitionNameSelector::Name(name) => Some(self.push_text(name)),
+ });
+ let classes = self.push_text_list(argument.classes.iter().map(|class| (class.units(), false)));
+ PseudoElementRareValue::TransitionName { name, classes }
+ }
+ };
+ let identities_start = index_u32(self.atoms.len());
+ for &atom in &pseudo_element.identifier_identities {
+ self.lease(atom);
+ self.atoms.push(atom);
+ }
+ let identifier_identities = PoolRange {
+ start: identities_start,
+ length: index_u32(pseudo_element.identifier_identities.len()),
+ };
+ if serialized_name.is_none() && value == PseudoElementRareValue::None && identifier_identities.length == 0 {
+ (bits, NONE)
+ } else {
+ let rare = PseudoElementRare {
+ serialized_name,
+ value,
+ identifier_identities,
+ };
+ (bits, pool_push(&mut self.pseudo_elements, rare))
+ }
+ }
+
+ fn component(&mut self, simple: &tree::SimpleSelector) -> Component {
+ let (bits, data) = match simple {
+ tree::SimpleSelector::Universal(name) => (
+ ComponentBits::new(ComponentKind::Universal)
+ .with_namespace(name.namespace_type)
+ .with(ASCII_LOWERCASE, name.name_is_ascii_lowercase),
+ self.qualified_data(name),
+ ),
+ tree::SimpleSelector::TagName(name) => (
+ ComponentBits::new(ComponentKind::Tag)
+ .with_namespace(name.namespace_type)
+ .with(ASCII_LOWERCASE, name.name_is_ascii_lowercase),
+ self.qualified_data(name),
+ ),
+ tree::SimpleSelector::Id(name) => {
+ self.lease(name.name);
+ (
+ ComponentBits::new(ComponentKind::Id).with(ASCII_LOWERCASE, name.is_ascii_lowercase),
+ name.name.0,
+ )
+ }
+ tree::SimpleSelector::Class(name) => {
+ self.lease(name.name);
+ (
+ ComponentBits::new(ComponentKind::Class).with(ASCII_LOWERCASE, name.is_ascii_lowercase),
+ name.name.0,
+ )
+ }
+ tree::SimpleSelector::Attribute(attribute) => {
+ let name = &attribute.qualified_name;
+ self.lease(name.name);
+ self.lease(name.namespace);
+ self.lease(attribute.value_identity);
+ let text = self.push_text(&attribute.value);
+ let rare = AttributeRare {
+ name: QualifiedRare {
+ prefix: name.namespace,
+ local: name.name,
+ },
+ value: attribute.value_identity,
+ text,
+ };
+ // https://html.spec.whatwg.org/multipage/semantics-other.html#case-sensitivity-of-selectors
+ let legacy_case_insensitive =
+ matches!(name.namespace_type, NamespaceType::Default | NamespaceType::None)
+ && crate::css::style::process_atoms().text(name.name).is_some_and(|text| {
+ crate::css::selector::is_ascii_case_insensitive_html_attribute(&text.to_utf16())
+ });
+ (
+ ComponentBits::new(ComponentKind::Attribute)
+ .with_namespace(name.namespace_type)
+ .with_pseudo(attribute.match_type as u8 | ((attribute.case_type as u8) << 3))
+ .with(ASCII_LOWERCASE, name.name_is_ascii_lowercase)
+ .with(LEGACY_CASE_INSENSITIVE, legacy_case_insensitive),
+ pool_push(&mut self.attributes, rare),
+ )
+ }
+ tree::SimpleSelector::PseudoClass(pseudo_class) => self.pseudo_class_component(pseudo_class),
+ tree::SimpleSelector::PseudoElement(pseudo_element) => self.pseudo_element_component(pseudo_element),
+ tree::SimpleSelector::Nesting => (
+ ComponentBits::new(ComponentKind::Nesting).with_pseudo(self.nesting.kind()),
+ match self.nesting {
+ NestingTarget::Rule(rule) => rule.0,
+ NestingTarget::Root | NestingTarget::Scope | NestingTarget::Unbound => NONE,
+ },
+ ),
+ tree::SimpleSelector::Invalid(text) => {
+ let range = self.push_text(text);
+ (
+ ComponentBits::new(ComponentKind::Invalid),
+ pool_push(&mut self.text_ranges, range),
+ )
+ }
+ tree::SimpleSelector::Compound { .. } => unreachable!("a compound start is not among its simple selectors"),
+ };
+ Component { bits, data }
+ }
+
+ fn finish(mut self) -> SelectorArena {
+ let namespace_prefixes = PoolRange {
+ start: index_u32(self.atoms.len()),
+ length: index_u32(self.namespace_prefixes.len()),
+ };
+ // NB: `[*|x]` and `[ns|x]` test names qualified by a namespace, which what reads the arena,
+ // as the host deciding which attributes to publish, looks up by their qualified atoms.
+ let atoms = crate::css::style::process_atoms();
+ let mut qualified_names = Vec::new();
+ for component in &self.components {
+ if component.bits.kind() != ComponentKind::Attribute {
+ continue;
+ }
+ let qualifier = match component.bits.namespace() {
+ NamespaceType::Any => Some(StyleAtomID::NONE),
+ NamespaceType::Named => {
+ let prefix = self.attributes[component.data as usize].name.prefix;
+ self.namespace_prefixes
+ .as_chunks::<2>()
+ .0
+ .iter()
+ .find(|declared| declared[0] == prefix)
+ .map(|declared| declared[1])
+ }
+ _ => None,
+ };
+ let Some(namespace) = qualifier else {
+ continue;
+ };
+ let local = self.attributes[component.data as usize].name.local;
+ for name in [local, atoms.ascii_lowercase(local)] {
+ qualified_names.push(crate::css::style::AtomLease::acquire_qualified(atoms, namespace, name));
+ }
+ }
+ self.atoms.extend_from_slice(&self.namespace_prefixes);
+ let namespace_atoms = self
+ .default_namespace
+ .into_iter()
+ .chain(self.namespace_prefixes)
+ .chain(qualified_names.iter().map(crate::css::style::AtomLease::atom));
+ let mut arena = SelectorArena {
+ components: self.components.into_boxed_slice(),
+ qualified: self.qualified.into_boxed_slice(),
+ attributes: self.attributes.into_boxed_slice(),
+ nths: self.nths.into_boxed_slice(),
+ arguments: self.arguments.into_boxed_slice(),
+ pseudo_elements: self.pseudo_elements.into_boxed_slice(),
+ atoms: self.atoms.into_boxed_slice(),
+ numbers: self.numbers.into_boxed_slice(),
+ text_ranges: self.text_ranges.into_boxed_slice(),
+ text: self.text.into_boxed_slice(),
+ rule_lists: self.rule_lists.into_boxed_slice(),
+ _leases: crate::css::style::process_atoms().lease(self.leased.into_iter().chain(namespace_atoms)),
+ default_namespace: self.default_namespace,
+ namespace_prefixes,
+ serial: crate::render_state::process_style().next_selector_arena_serial(),
+ compounds: Box::default(),
+ compound_starts: Box::default(),
+ compound_ranks: Box::default(),
+ };
+ arena.mark_selector_facts();
+ arena
+ }
+}
+
+impl SelectorArena {
+ /// Write what matching asks of each selector as a whole on its first component, once, as the arena freezes.
+ fn mark_selector_facts(&mut self) {
+ fn names_the_scope(selector: Selector<'_>) -> bool {
+ fn simple(simple: &SimpleSelector<'_>) -> bool {
+ match simple {
+ SimpleSelector::PseudoClass(pseudo_class) => {
+ pseudo_class.pseudo_class == PseudoClassType::Scope
+ || pseudo_class.argument_selector_list.iter().any(names_the_scope)
+ }
+ SimpleSelector::Nesting(Nesting::Scope) => true,
+ SimpleSelector::Nesting(Nesting::Rule(parent)) => parent.iter().any(names_the_scope),
+ _ => false,
+ }
+ }
+ selector
+ .compounds()
+ .any(|compound| compound.simple_selectors.iter().any(|candidate| simple(&candidate)))
+ }
+ let escapes_its_namespace = |selector: Selector<'_>| {
+ selector.compounds().any(|compound| {
+ compound.simple_selectors.iter().any(|simple| {
+ matches!(simple, SimpleSelector::PseudoElement(pseudo_element)
+ if matches!(pseudo_element.pseudo_element, PseudoElementType::Slotted | PseudoElementType::Part))
+ })
+ })
+ };
+ let search_text_filters: Vec<usize> = (0..self.components.len())
+ .filter(|&at| {
+ self.components[at].bits.kind() == ComponentKind::PseudoClass
+ && matches!(self.decode(at), SimpleSelector::PseudoClass(pseudo_class)
+ if search_text_match_filter_of_pseudo_class(&pseudo_class) == Some(SearchTextMatchFilter::NotCurrent))
+ })
+ .collect();
+ for at in search_text_filters {
+ self.components[at].bits.0 |= SEARCH_TEXT_FILTER;
+ }
+ // NB: Every component is of one selector, which its last component, the one ending the leftmost compound,
+ // ends.
+ let mut facts = Vec::new();
+ let mut start = 0;
+ for index in 0..self.components.len() {
+ if self.components[index].bits.relation() != Relation::Leftmost {
+ continue;
+ }
+ let selector = Selector {
+ arena: self,
+ at: ComponentOffset(index_u32(start)),
+ };
+ let subject_end = (start..=index)
+ .find(|&at| self.components[at].bits.relation() != Relation::SubSelector)
+ .unwrap_or(index);
+ let describes_its_subject =
+ !(start..=subject_end).any(|at| self.components[at].bits.kind() == ComponentKind::PseudoElement);
+ let flags = (u32::from(names_the_scope(selector)) * NAMES_THE_SCOPE)
+ | (u32::from(escapes_its_namespace(selector)) * ESCAPES_ITS_NAMESPACE)
+ | (u32::from(describes_its_subject) * DESCRIBES_ITS_SUBJECT);
+ if flags != 0 {
+ facts.push((start, flags));
+ }
+ start = index + 1;
+ }
+ for (start, flags) in facts {
+ self.components[start].bits.0 |= flags;
+ }
+ self.mark_compound_lengths();
+ self.note_compound_facts();
+ }
+
+ /// Write the length of each compound shorter than 16 components on its first component.
+ fn mark_compound_lengths(&mut self) {
+ let mut start = 0;
+ for index in 0..self.components.len() {
+ if self.components[index].bits.relation() == Relation::SubSelector {
+ continue;
+ }
+ let length = index + 1 - start;
+ if length < 16 {
+ debug_assert_eq!(self.components[start].bits.0 & COMPOUND_LENGTH_BITS, 0);
+ self.components[start].bits.0 |= (length as u32) << COMPOUND_LENGTH_SHIFT;
+ }
+ start = index + 1;
+ }
+ }
+
+ /// Note what matching asks of each compound as a whole, and where each compound starts.
+ fn note_compound_facts(&mut self) {
+ let mut compounds = Vec::new();
+ let mut shapes: crate::css::style::fast_hash::FastMap<Vec<(u32, u32)>, u32> = Default::default();
+ let words = self.components.len().div_ceil(64);
+ let mut starts = vec![0u64; words];
+ let mut start = 0;
+ while start < self.components.len() {
+ let end = self.compound_end(start);
+ starts[start / 64] |= 1 << (start % 64);
+ compounds.push(CompoundFacts {
+ shape: self.compound_shape(start..end, &mut shapes),
+ bloom: self.compound_bloom(start..end),
+ });
+ start = end;
+ }
+ let mut ranks = Vec::with_capacity(words);
+ let mut before = 0;
+ for &word in &starts {
+ ranks.push(before);
+ before += word.count_ones();
+ }
+ self.compounds = compounds.into_boxed_slice();
+ self.compound_starts = starts.into_boxed_slice();
+ self.compound_ranks = ranks.into_boxed_slice();
+ }
+
+ /// The dispatch bloom bits of what the compound of `components` tests, as [`CompoundFacts::bloom`] says.
+ fn compound_bloom(&self, components: std::ops::Range<usize>) -> u64 {
+ use crate::css::style::index::{DispatchKey, dispatch_bloom_bit};
+ self.components[components]
+ .iter()
+ .fold(0, |bloom, component| match component.bits.kind() {
+ ComponentKind::Id => bloom | dispatch_bloom_bit(DispatchKey::Id(StyleAtomID(component.data))),
+ ComponentKind::Class => bloom | dispatch_bloom_bit(DispatchKey::Class(StyleAtomID(component.data))),
+ // NB: A type written in ASCII lowercase is carried as written by every element matching it. A
+ // type qualified by a prefix holds its name in the rare table.
+ ComponentKind::Tag
+ if component.bits.has(ASCII_LOWERCASE) && component.bits.namespace() != NamespaceType::Named =>
+ {
+ bloom | dispatch_bloom_bit(DispatchKey::TagName(StyleAtomID(component.data)))
+ }
+ // NB: An attribute written in ASCII lowercase in no namespace is carried under that name by every
+ // element matching it, as one of the name forms of the attribute it holds.
+ ComponentKind::Attribute
+ if component.bits.has(ASCII_LOWERCASE)
+ && matches!(component.bits.namespace(), NamespaceType::Default | NamespaceType::None) =>
+ {
+ let name = self.attributes[component.data as usize].name.local;
+ bloom | dispatch_bloom_bit(DispatchKey::AttributeName(name))
+ }
+ ComponentKind::PseudoClass => {
+ match crate::css::style::component_matching::state_tested_by(pseudo_class_from_ffi(
+ component.bits.pseudo(),
+ )) {
+ Some(fact) => bloom | dispatch_bloom_bit(DispatchKey::State(fact)),
+ None => bloom,
+ }
+ }
+ _ => bloom,
+ })
+ }
+
+ /// The number of the compound's own tests among those of the arena, as [`CompoundFacts::shape`] says.
+ fn compound_shape(
+ &self,
+ components: std::ops::Range<usize>,
+ shapes: &mut crate::css::style::fast_hash::FastMap<Vec<(u32, u32)>, u32>,
+ ) -> u32 {
+ // NB: Only what a compound's own tests read counts toward its shape: not the combinator its last component
+ // carries, nor the facts the arena notes of a selector or a compound.
+ const SHAPE_BITS: u32 = !(RELATION_BITS
+ | LAST_IN_LIST
+ | NAMES_THE_SCOPE
+ | ESCAPES_ITS_NAMESPACE
+ | DESCRIBES_ITS_SUBJECT
+ | COMPOUND_LENGTH_BITS);
+ let reads_its_selector = components.clone().any(|at| match self.components[at].bits.kind() {
+ ComponentKind::Nesting
+ | ComponentKind::Invalid
+ | ComponentKind::RelativeAnchor
+ | ComponentKind::PseudoElement => true,
+ // NB: What `:host` matches depends on the tree of the sheet the selector's rule decides in.
+ ComponentKind::PseudoClass => matches!(
+ self.decode(at),
+ SimpleSelector::PseudoClass(pseudo_class)
+ if matches!(pseudo_class.pseudo_class, PseudoClassType::Scope | PseudoClassType::Host)
+ ),
+ _ => false,
+ });
+ if reads_its_selector {
+ return CompoundFacts::NO_SHAPE;
+ }
+ let key: Vec<(u32, u32)> = self.components[components]
+ .iter()
+ .map(|component| (component.bits.0 & SHAPE_BITS, component.data))
+ .collect();
+ let next = index_u32(shapes.len());
+ *shapes.entry(key).or_insert(next)
+ }
+}
+
+impl Selector<'_> {
+ /// The selector as a parse tree again, for a transformation that builds another selector from
+ /// it. The tree names the arena's atoms, which the arena keeps live while it is packed again.
+ pub(crate) fn to_tree(self) -> Arc<tree::CompiledSelector> {
+ let compounds: Box<[tree::CompoundSelector]> = self
+ .compound_selectors()
+ .iter()
+ .map(|compound| tree::CompoundSelector {
+ combinator: compound.combinator,
+ is_implicit_universal_anchor: compound.is_implicit_universal_anchor,
+ simple_selectors: compound
+ .simple_selectors
+ .iter()
+ .map(|simple| simple_to_tree(&simple))
+ .collect(),
+ })
+ .collect();
+ tree::CompiledSelector::new(compounds)
+ }
+}
+
+impl SelectorListView<'_> {
+ pub(crate) fn to_tree(self) -> tree::SelectorList {
+ self.iter().map(Selector::to_tree).collect()
+ }
+}
+
+fn simple_to_tree(simple: &SimpleSelector<'_>) -> tree::SimpleSelector {
+ use crate::css::selector::SelectorString;
+ match *simple {
+ SimpleSelector::Universal(name) => tree::SimpleSelector::Universal(Box::new(name)),
+ SimpleSelector::TagName(name) => tree::SimpleSelector::TagName(Box::new(name)),
+ SimpleSelector::Id(name) => tree::SimpleSelector::Id(name),
+ SimpleSelector::Class(name) => tree::SimpleSelector::Class(name),
+ SimpleSelector::Attribute(attribute) => tree::SimpleSelector::Attribute(Box::new(tree::AttributeSelector {
+ match_type: attribute.match_type,
+ qualified_name: attribute.qualified_name,
+ value: attribute.value.into(),
+ value_identity: attribute.value_identity,
+ case_type: attribute.case_type,
+ })),
+ SimpleSelector::PseudoClass(pseudo_class) => {
+ tree::SimpleSelector::PseudoClass(Box::new(tree::PseudoClassSelector {
+ pseudo_class: pseudo_class.pseudo_class,
+ an_plus_b_pattern: pseudo_class.an_plus_b_pattern,
+ argument_selector_list: pseudo_class.argument_selector_list.to_tree(),
+ languages: pseudo_class
+ .languages
+ .iter()
+ .map(|range| tree::LanguageRange {
+ value: range.value.into(),
+ is_string: range.is_string,
+ })
+ .collect(),
+ direction: pseudo_class.direction,
+ identifier: pseudo_class.identifier.map(SelectorString::from),
+ identifier_identity: pseudo_class.identifier_identity,
+ levels: pseudo_class.levels.into(),
+ is_forgiving: pseudo_class.is_forgiving,
+ }))
+ }
+ SimpleSelector::PseudoElement(pseudo_element) => {
+ tree::SimpleSelector::PseudoElement(Box::new(tree::PseudoElementSelector {
+ pseudo_element: pseudo_element.pseudo_element,
+ serialized_name: pseudo_element.serialized_name.map(SelectorString::from),
+ value: match pseudo_element.value {
+ PseudoElementValue::None => tree::PseudoElementValue::None,
+ PseudoElementValue::CompoundSelector(selector) => {
+ tree::PseudoElementValue::CompoundSelector(selector.to_tree())
+ }
+ PseudoElementValue::Identifiers(identifiers) => {
+ tree::PseudoElementValue::Identifiers(identifiers.iter().map(SelectorString::from).collect())
+ }
+ PseudoElementValue::TransitionName(argument) => {
+ tree::PseudoElementValue::TransitionName(Box::new(tree::TransitionNameAndClassSelector {
+ name: argument.name.map(|name| match name {
+ TransitionNameSelector::Universal => tree::TransitionNameSelector::Universal,
+ TransitionNameSelector::Name(name) => tree::TransitionNameSelector::Name(name.into()),
+ }),
+ classes: argument.classes.iter().map(SelectorString::from).collect(),
+ }))
+ }
+ },
+ identifier_identities: pseudo_element.identifier_identities.into(),
+ }))
+ }
+ SimpleSelector::Nesting(_) => tree::SimpleSelector::Nesting,
+ SimpleSelector::Invalid(text) => tree::SimpleSelector::Invalid(text.into()),
+ }
+}
+
+/// The selectors of a list, each found past the last by the lengths of its compounds.
+pub struct SelectorsOf<'a> {
+ arena: &'a SelectorArena,
+ /// Where the next selector starts, or `usize::MAX` past the last.
+ at: usize,
+}
+
+impl<'a> Iterator for SelectorsOf<'a> {
+ type Item = Selector<'a>;
+
+ #[inline]
+ fn next(&mut self) -> Option<Selector<'a>> {
+ if self.at == usize::MAX {
+ return None;
+ }
+ let components = &self.arena.components;
+ let first = self.at;
+ let mut at = first;
+ loop {
+ let end = self.arena.compound_end(at);
+ let bits = components[end - 1].bits;
+ at = end;
+ if bits.relation() == Relation::Leftmost {
+ self.at = match bits.has(LAST_IN_LIST) {
+ true => usize::MAX,
+ false => at,
+ };
+ return Some(Selector {
+ arena: self.arena,
+ at: ComponentOffset(index_u32(first)),
+ });
+ }
+ }
+ }
+}
+
+impl<'a> IntoIterator for SelectorListView<'a> {
+ type Item = Selector<'a>;
+ type IntoIter = SelectorsOf<'a>;
+
+ fn into_iter(self) -> Self::IntoIter {
+ self.arena.selectors_of(self.start)
+ }
+}
+
+impl<'a> IntoIterator for &SelectorListView<'a> {
+ type Item = Selector<'a>;
+ type IntoIter = SelectorsOf<'a>;
+
+ fn into_iter(self) -> Self::IntoIter {
+ (*self).into_iter()
+ }
+}
+
+impl PartialEq for SelectorArena {
+ fn eq(&self, other: &Self) -> bool {
+ self.components == other.components
+ && self.qualified == other.qualified
+ && self.attributes == other.attributes
+ && self.nths == other.nths
+ && self.arguments == other.arguments
+ && self.pseudo_elements == other.pseudo_elements
+ && self.atoms == other.atoms
+ && self.numbers == other.numbers
+ && self.text_ranges == other.text_ranges
+ && self.text == other.text
+ && self.rule_lists == other.rule_lists
+ }
+}
+
+impl PartialEq for SelectorListRef {
+ fn eq(&self, other: &Self) -> bool {
+ self.start == other.start
+ && (Arc::ptr_eq(&self.arena, &other.arena) || frozen(&self.arena) == frozen(&other.arena))
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/selector_operations.rs b/Libraries/LibWeb/Rust/src/css/selector_operations.rs
index 881075e9d75..fad9f63d8bb 100644
--- a/Libraries/LibWeb/Rust/src/css/selector_operations.rs
+++ b/Libraries/LibWeb/Rust/src/css/selector_operations.rs
@@ -9,12 +9,11 @@
use std::sync::Arc;
use super::css_tokenizer::{ParserTokenKind, tokenize_for_parser};
-use super::retained_fly_string::RetainedUtf16FlyString;
-use super::selector::{
- Combinator, CompiledSelector, CompoundSelector, PseudoClassSelector, PseudoClassType, PseudoElementType,
- PseudoElementValue, RustSelector, SelectorList, SimpleSelector, pseudo_class_from_ffi,
-};
+use super::selector::{Combinator, PseudoClassType, PseudoElementType, RustSelector, pseudo_class_from_ffi};
use super::selector_parser::StyleNestingParent;
+use super::selector_tree::{
+ CompiledSelector, CompoundSelector, PseudoClassSelector, PseudoElementValue, SelectorList, SimpleSelector,
+};
fn pseudo_class(pseudo_class: PseudoClassType, arguments: SelectorList) -> SimpleSelector {
SimpleSelector::PseudoClass(Box::new(PseudoClassSelector {
@@ -24,8 +23,7 @@ fn pseudo_class(pseudo_class: PseudoClassType, arguments: SelectorList) -> Simpl
languages: Box::new([]),
direction: None,
identifier: None,
- identifier_identity: RetainedUtf16FlyString::none(),
- identifier_lowercase_identity: RetainedUtf16FlyString::none(),
+ identifier_identity: crate::css::style::index::StyleAtomID::NONE,
levels: Box::new([]),
is_forgiving: false,
}))
@@ -39,16 +37,21 @@ fn scope_selector() -> Arc<CompiledSelector> {
}]))
}
+/// `:where(:scope)`, which matches the scoping root and adds no specificity.
+pub(crate) fn scope_root_anchor() -> SimpleSelector {
+ pseudo_class(PseudoClassType::Where, Box::new([scope_selector()]))
+}
+
pub(crate) fn scope_root_selector_list() -> SelectorList {
Box::new([CompiledSelector::new(Box::new([CompoundSelector {
combinator: Combinator::None,
is_implicit_universal_anchor: false,
- simple_selectors: Box::new([pseudo_class(PseudoClassType::Where, Box::new([scope_selector()]))]),
+ simple_selectors: Box::new([scope_root_anchor()]),
}]))])
}
pub(crate) fn contains_nesting(selector: &CompiledSelector) -> bool {
- selector.compound_selectors.iter().any(|compound| {
+ selector.compound_selectors().iter().any(|compound| {
compound.simple_selectors.iter().any(|simple| match simple {
SimpleSelector::Nesting => true,
SimpleSelector::PseudoClass(pseudo_class) => pseudo_class
@@ -63,8 +66,8 @@ pub(crate) fn contains_nesting(selector: &CompiledSelector) -> bool {
})
}
-fn contains_pseudo_class(selector: &CompiledSelector, expected: PseudoClassType) -> bool {
- selector.compound_selectors.iter().any(|compound| {
+pub(crate) fn contains_pseudo_class(selector: &CompiledSelector, expected: PseudoClassType) -> bool {
+ selector.compound_selectors().iter().any(|compound| {
compound.simple_selectors.iter().any(|simple| {
let SimpleSelector::PseudoClass(pseudo_class) = simple else {
return false;
@@ -80,7 +83,7 @@ fn contains_pseudo_class(selector: &CompiledSelector, expected: PseudoClassType)
fn any_simple(selector: &CompiledSelector, predicate: &impl Fn(&SimpleSelector) -> bool) -> bool {
selector
- .compound_selectors
+ .compound_selectors()
.iter()
.any(|compound| compound.simple_selectors.iter().any(predicate))
}
@@ -129,7 +132,7 @@ fn contains_named_namespace(selector: &CompiledSelector) -> bool {
})
}
-fn invalid_for_has(selector: &CompiledSelector) -> bool {
+pub(crate) fn invalid_for_has(selector: &CompiledSelector) -> bool {
any_simple(selector, &|simple| match simple {
SimpleSelector::PseudoElement(_) => true,
SimpleSelector::PseudoClass(pseudo_class) => {
@@ -145,9 +148,9 @@ fn invalid_for_has(selector: &CompiledSelector) -> bool {
fn absolutize(selector: &CompiledSelector, replacement: &SimpleSelector) -> Option<Arc<CompiledSelector>> {
if !contains_nesting(selector) {
- return Some(CompiledSelector::new(selector.compound_selectors.clone()));
+ return Some(CompiledSelector::new(selector.to_compounds()));
}
- let mut compounds = selector.compound_selectors.clone();
+ let mut compounds = selector.to_compounds();
for compound in &mut compounds {
let mut simples = Vec::with_capacity(compound.simple_selectors.len());
for simple in &compound.simple_selectors {
@@ -183,13 +186,18 @@ fn absolutize(selector: &CompiledSelector, replacement: &SimpleSelector) -> Opti
}
pub(crate) fn relative_to(selector: &CompiledSelector, parent: SimpleSelector) -> Arc<CompiledSelector> {
- let mut compounds = Vec::with_capacity(selector.compound_selectors.len() + 1);
+ let mut compounds = Vec::with_capacity(selector.compound_selectors().len() + 1);
compounds.push(CompoundSelector {
combinator: Combinator::None,
is_implicit_universal_anchor: false,
simple_selectors: Box::new([parent]),
});
- compounds.extend(selector.compound_selectors.iter().cloned());
+ compounds.extend(
+ selector
+ .compound_selectors()
+ .iter()
+ .map(|compound| compound.to_compound()),
+ );
if let Some(second) = compounds.get_mut(1)
&& second.combinator == Combinator::None
{
@@ -201,10 +209,11 @@ pub(crate) fn relative_to(selector: &CompiledSelector, parent: SimpleSelector) -
/// Whether a selector is a lone universal selector, which every element matches. A query API has
/// no default namespace, so `*` and `*|*` name the same elements there.
fn matches_every_element(selector: &CompiledSelector) -> bool {
- let [compound] = selector.compound_selectors.as_ref() else {
+ let compounds = selector.compound_selectors();
+ let [compound] = compounds.as_slice() else {
return false;
};
- let [SimpleSelector::Universal(name)] = compound.simple_selectors.as_ref() else {
+ let [SimpleSelector::Universal(name)] = compound.simple_selectors else {
return false;
};
matches!(
@@ -222,7 +231,7 @@ fn matches_every_element(selector: &CompiledSelector) -> bool {
pub unsafe extern "C" fn rust_selector_matches_every_element(selector: *const RustSelector) -> bool {
unsafe {
assert!(!selector.is_null());
- matches_every_element((*selector).compiled())
+ matches_every_element(&(*selector).compiled().to_tree())
}
}
@@ -232,7 +241,7 @@ pub unsafe extern "C" fn rust_selector_matches_every_element(selector: *const Ru
pub unsafe extern "C" fn rust_selector_contains_nesting(selector: *const RustSelector) -> bool {
unsafe {
assert!(!selector.is_null());
- contains_nesting((*selector).compiled())
+ contains_nesting(&(*selector).compiled().to_tree())
}
}
@@ -242,7 +251,7 @@ pub unsafe extern "C" fn rust_selector_contains_nesting(selector: *const RustSel
pub unsafe extern "C" fn rust_selector_contains_pseudo_class(selector: *const RustSelector, value: u8) -> bool {
unsafe {
assert!(!selector.is_null());
- contains_pseudo_class((*selector).compiled(), pseudo_class_from_ffi(value))
+ contains_pseudo_class(&(*selector).compiled().to_tree(), pseudo_class_from_ffi(value))
}
}
@@ -252,7 +261,7 @@ pub unsafe extern "C" fn rust_selector_contains_pseudo_class(selector: *const Ru
pub unsafe extern "C" fn rust_selector_contains_named_namespace(selector: *const RustSelector) -> bool {
unsafe {
assert!(!selector.is_null());
- contains_named_namespace((*selector).compiled())
+ contains_named_namespace(&(*selector).compiled().to_tree())
}
}
@@ -266,7 +275,7 @@ pub(crate) fn absolutize_selector_list(
|| (parent == StyleNestingParent::Scope
&& !matches!(
selector
- .compound_selectors
+ .compound_selectors()
.first()
.map_or(Combinator::None, |compound| compound.combinator),
Combinator::None | Combinator::Descendant
@@ -284,7 +293,7 @@ pub(crate) fn absolutize_selector_list(
.iter()
.filter_map(|selector| {
let first = selector
- .compound_selectors
+ .compound_selectors()
.first()
.map_or(Combinator::None, |compound| compound.combinator);
if contains_nesting(selector) {
@@ -306,7 +315,7 @@ pub(crate) fn adapt_scope_end_selector_list(selectors: &SelectorList) -> Selecto
.iter()
.map(|selector| {
let first = selector
- .compound_selectors
+ .compound_selectors()
.first()
.map_or(Combinator::None, |compound| compound.combinator);
if !matches!(first, Combinator::None | Combinator::Descendant)
@@ -317,7 +326,7 @@ pub(crate) fn adapt_scope_end_selector_list(selectors: &SelectorList) -> Selecto
pseudo_class(PseudoClassType::Where, Box::new([scope_selector()])),
)
} else if first == Combinator::Descendant {
- let mut compounds = selector.compound_selectors.clone();
+ let mut compounds = selector.to_compounds();
compounds[0].combinator = Combinator::None;
CompiledSelector::new(compounds)
} else {
@@ -331,8 +340,8 @@ pub(crate) fn adapt_scope_end_selector_list(selectors: &SelectorList) -> Selecto
mod tests {
use super::super::css_tokenizer::{TokenizerInput, tokenize_for_parser};
use super::super::parser::component_value::consume_a_list_of_component_values;
- use super::super::selector::SelectorList;
use super::super::selector_parser::{SelectorType, parse_selector_list_from_component_values};
+ use super::super::selector_tree::SelectorList;
use super::contains_named_namespace;
#[test]
@@ -341,18 +350,25 @@ mod tests {
use crate::css::selector_parser::StyleNestingParent;
use crate::css::selector_serialization::serialize_selector_without_namespaces;
- fn parse(source: &str, kind: SelectorType) -> super::SelectorList {
+ // NB: The parsed trees keep their names live, which the results packed from them lease.
+ let trees = std::cell::RefCell::new(Vec::new());
+ let parse = |source: &str, kind: SelectorType| -> super::SelectorList {
let units: Vec<_> = source.encode_utf16().collect();
let values = consume_a_list_of_component_values(tokenize_for_parser(units.as_slice())).unwrap();
let parsed = parse_selector_list_from_component_values(&values, &[], kind).unwrap();
- parsed.selectors
- }
+ let selectors = parsed.selectors.clone();
+ trees.borrow_mut().push(parsed);
+ selectors
+ };
fn text(selectors: super::SelectorList) -> Vec<Vec<u16>> {
selectors
.into_vec()
.into_iter()
.map(|selector| {
- let selector = super::RustSelector { selector };
+ let list = crate::css::selector::SelectorListRef::pack(&[selector]);
+ let selector = super::RustSelector {
+ selector: list.owned().next().unwrap(),
+ };
serialize_selector_without_namespaces(&selector)
})
.collect()
@@ -403,8 +419,7 @@ mod tests {
let values = consume_a_list_of_component_values(tokenize_for_parser(source.as_bytes())).unwrap();
parse_selector_list_from_component_values(&values, &[TokenizerInput::Latin1(b"foo")], SelectorType::Standalone)
.unwrap()
- .selectors()
- .clone()
+ .selectors
}
#[test]
diff --git a/Libraries/LibWeb/Rust/src/css/selector_parser.rs b/Libraries/LibWeb/Rust/src/css/selector_parser.rs
index 0f99a16a0a9..02bf280db9e 100644
--- a/Libraries/LibWeb/Rust/src/css/selector_parser.rs
+++ b/Libraries/LibWeb/Rust/src/css/selector_parser.rs
@@ -14,19 +14,20 @@ use super::ffi_support::FfiUtf16View;
use super::ffi_support::ascii_lowercase;
use super::parser::component_value::{ComponentKind, ComponentValue, consume_a_list_of_component_values};
use super::parser::token_stream::TokenStream as Stream;
-use super::retained_fly_string::RetainedUtf16FlyString;
#[cfg(test)]
use super::selector::FfiStringView;
use super::selector::{
- AnPlusBPattern, AttributeCaseType, AttributeMatchType, Combinator, Direction, LanguageRange, NamespaceType,
+ AnPlusBPattern, AttributeCaseType, AttributeMatchType, Combinator, Direction, NamespaceType,
PseudoClassParameterType, PseudoClassType, PseudoElementParameterType, PseudoElementType, SelectorString,
};
-use super::selector::{
- AttributeSelector, CompiledSelector, CompoundSelector, NameSelector, PseudoClassSelector, PseudoElementSelector,
- PseudoElementValue, QualifiedName, SelectorList, SimpleSelector, TransitionNameAndClassSelector,
- TransitionNameSelector,
+use super::selector::{NameSelector, QualifiedName, RustSelector, SelectorListRef, SelectorRef};
+use super::selector_tree::{
+ AttributeSelector, CompiledSelector, CompoundSelector, LanguageRange, PseudoClassSelector, PseudoElementSelector,
+ PseudoElementValue, SelectorList, SimpleSelector, TransitionNameAndClassSelector, TransitionNameSelector,
+ search_text_match_filter,
};
-use super::selector::{RustSelector, search_text_match_filter};
+use crate::css::style::AtomLease;
+use crate::css::style::index::StyleAtomID;
const MAXIMUM_SELECTOR_NESTING_DEPTH: usize = 128;
@@ -37,6 +38,7 @@ pub(crate) enum SelectorType {
}
pub use super::ffi_support::StyleNestingParent;
+use super::selector_arena::{NestingTarget, RuleOrdinal};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum SelectorParsingMode {
@@ -64,16 +66,6 @@ fn lowercase(value: &[u16]) -> SelectorString {
.into()
}
-fn selector_name(value: &[u16]) -> NameSelector {
- let name = RetainedUtf16FlyString::from_utf16(value);
- let lowercase_name = if value.iter().all(|&unit| ascii_lowercase(unit) == unit) {
- name.clone()
- } else {
- RetainedUtf16FlyString::from_utf16(&value.iter().map(|&unit| ascii_lowercase(unit)).collect::<Vec<_>>())
- };
- NameSelector { name, lowercase_name }
-}
-
fn pseudo_class_selector(pseudo_class: PseudoClassType) -> PseudoClassSelector {
PseudoClassSelector {
pseudo_class,
@@ -82,8 +74,7 @@ fn pseudo_class_selector(pseudo_class: PseudoClassType) -> PseudoClassSelector {
languages: Box::new([]),
direction: None,
identifier: None,
- identifier_identity: RetainedUtf16FlyString::none(),
- identifier_lowercase_identity: RetainedUtf16FlyString::none(),
+ identifier_identity: StyleAtomID::NONE,
levels: Box::new([]),
is_forgiving: false,
}
@@ -317,6 +308,9 @@ struct SelectorParser<'a> {
nesting_limit_exceeded: bool,
compound_pseudo_element: Option<PseudoElementType>,
bare_current_allowed: bool,
+ /// A reference to each name the parse interned, which keeps its atom live until the selector
+ /// naming it leases it.
+ names: std::cell::RefCell<Vec<AtomLease>>,
}
impl<'a> SelectorParser<'a> {
@@ -327,6 +321,23 @@ impl<'a> SelectorParser<'a> {
nesting_limit_exceeded: false,
compound_pseudo_element: None,
bare_current_allowed: false,
+ names: std::cell::RefCell::default(),
+ }
+ }
+
+ /// The process style atom of the name `value` spells.
+ fn name(&self, value: &[u16]) -> StyleAtomID {
+ let lease = crate::css::style::process_atoms().intern(value);
+ let atom = lease.atom();
+ self.names.borrow_mut().push(lease);
+ atom
+ }
+
+ /// The process style atom of a name a qualified name holds, none for `*`, which names any.
+ fn qualified_name_part(&self, value: &[u16]) -> StyleAtomID {
+ match value == [b'*' as u16] {
+ true => StyleAtomID::NONE,
+ false => self.name(value),
}
}
@@ -533,13 +544,11 @@ impl<'a> SelectorParser<'a> {
stream.position = original;
return None;
}
- let NameSelector { name, lowercase_name } = selector_name(parsed_name);
- return Some(QualifiedName {
- namespace_type: NamespaceType::None,
- namespace: RetainedUtf16FlyString::none(),
- lowercase_name,
- name,
- });
+ return Some(QualifiedName::new(
+ NamespaceType::None,
+ StyleAtomID::NONE,
+ self.qualified_name_part(parsed_name),
+ ));
}
let Some(first_name) = name(first) else {
@@ -572,29 +581,25 @@ impl<'a> SelectorParser<'a> {
stream.position = original;
return None;
}
- let NameSelector { name, lowercase_name } = selector_name(parsed_name);
- return Some(QualifiedName {
+ return Some(QualifiedName::new(
namespace_type,
- namespace: if namespace_type == NamespaceType::Named {
- RetainedUtf16FlyString::from_utf16(first_name)
+ if namespace_type == NamespaceType::Named {
+ self.name(first_name)
} else {
- RetainedUtf16FlyString::none()
+ StyleAtomID::NONE
},
- lowercase_name,
- name,
- });
+ self.qualified_name_part(parsed_name),
+ ));
}
if !allow_wildcard && first_name == [b'*' as u16] {
stream.position = original;
return None;
}
- let NameSelector { name, lowercase_name } = selector_name(first_name);
- Some(QualifiedName {
- namespace_type: NamespaceType::Default,
- namespace: RetainedUtf16FlyString::none(),
- lowercase_name,
- name,
- })
+ Some(QualifiedName::new(
+ NamespaceType::Default,
+ StyleAtomID::NONE,
+ self.qualified_name_part(first_name),
+ ))
}
fn next_is_pseudo_element(&self, stream: &Stream<'_>) -> bool {
@@ -628,13 +633,11 @@ impl<'a> SelectorParser<'a> {
let original = stream.position;
if let Some(qualified_name) = self.parse_qualified_name(stream, true) {
- return Ok(Some(
- if qualified_name.name == RetainedUtf16FlyString::from_utf16(&[b'*' as u16]) {
- SimpleSelector::Universal(Box::new(qualified_name))
- } else {
- SimpleSelector::TagName(Box::new(qualified_name))
- },
- ));
+ return Ok(Some(if qualified_name.name.is_none() {
+ SimpleSelector::Universal(Box::new(qualified_name))
+ } else {
+ SimpleSelector::TagName(Box::new(qualified_name))
+ }));
}
stream.position = original;
@@ -656,10 +659,10 @@ impl<'a> SelectorParser<'a> {
}
if first.is_delim(b'.') {
let class_name = stream.next().and_then(ComponentValue::ident).ok_or(())?;
- return Ok(Some(SimpleSelector::Class(selector_name(class_name))));
+ return Ok(Some(SimpleSelector::Class(NameSelector::new(self.name(class_name)))));
}
if let ComponentKind::Token(ParserTokenKind::Hash { value, is_id: true }) = &first.kind {
- return Ok(Some(SimpleSelector::Id(selector_name(value))));
+ return Ok(Some(SimpleSelector::Id(NameSelector::new(self.name(value)))));
}
if let Some(values) = first.square_block() {
return self.parse_attribute(values).map(Some);
@@ -677,7 +680,7 @@ impl<'a> SelectorParser<'a> {
match_type: AttributeMatchType::HasAttribute,
qualified_name,
value: SelectorString::default(),
- value_identity: RetainedUtf16FlyString::from_utf16(&[]),
+ value_identity: StyleAtomID::NONE,
case_type: AttributeCaseType::Default,
})));
}
@@ -724,7 +727,7 @@ impl<'a> SelectorParser<'a> {
Ok(SimpleSelector::Attribute(Box::new(AttributeSelector {
match_type,
qualified_name,
- value_identity: value.to_fly_string(),
+ value_identity: self.name(value.units()),
value,
case_type,
})))
@@ -840,8 +843,7 @@ impl<'a> SelectorParser<'a> {
} else {
Direction::Other
});
- selector.identifier_identity = RetainedUtf16FlyString::from_utf16(ident);
- selector.identifier_lowercase_identity = lowercase(ident).to_fly_string();
+ selector.identifier_identity = self.name(ident);
selector.identifier = Some(ident.into());
}
PseudoClassParameterType::LanguageRanges => {
@@ -981,9 +983,10 @@ impl<'a> SelectorParser<'a> {
pseudo_element,
serialized_name: alias.map(|alias| alias.encode_utf16().collect::<Vec<_>>().into()),
identifier_identities: match &value {
- PseudoElementValue::Identifiers(identifiers) => {
- identifiers.iter().map(SelectorString::to_fly_string).collect()
- }
+ PseudoElementValue::Identifiers(identifiers) => identifiers
+ .iter()
+ .map(|identifier| self.name(identifier.units()))
+ .collect(),
_ => Box::new([]),
},
value,
@@ -1150,7 +1153,7 @@ impl<'a> SelectorParser<'a> {
}
fn contains_pseudo_element(selector: &CompiledSelector) -> bool {
- selector.compound_selectors.iter().any(|compound| {
+ selector.compound_selectors().iter().any(|compound| {
compound
.simple_selectors
.iter()
@@ -1178,12 +1181,11 @@ fn normalize_pseudo_element_transitions(compounds: Vec<CompoundSelector>) -> Vec
normalized.push(CompoundSelector {
combinator,
is_implicit_universal_anchor: true,
- simple_selectors: vec![SimpleSelector::Universal(Box::new(QualifiedName {
- namespace_type: NamespaceType::Any,
- namespace: RetainedUtf16FlyString::none(),
- name: RetainedUtf16FlyString::from_utf16(&[u16::from(b'*')]),
- lowercase_name: RetainedUtf16FlyString::from_utf16(&[u16::from(b'*')]),
- }))]
+ simple_selectors: vec![SimpleSelector::Universal(Box::new(QualifiedName::new(
+ NamespaceType::Any,
+ StyleAtomID::NONE,
+ StyleAtomID::NONE,
+ )))]
.into_boxed_slice(),
});
} else {
@@ -1213,33 +1215,127 @@ pub(crate) fn parse_selector_list<'a>(
declared_namespaces: &[TokenizerInput<'_>],
selector_type: SelectorType,
parsing_mode: SelectorParsingMode,
-) -> Result<SelectorList, ()> {
+) -> Result<ParsedSelectorTree, ()> {
let tokens = tokenize_for_parser(input);
let values = consume_a_list_of_component_values(tokens.as_slice())?;
- SelectorParser::new(Some(declared_namespaces)).parse_selector_list(&values, selector_type, parsing_mode)
+ parse_selector_list_with_mode(&values, declared_namespaces, selector_type, parsing_mode)
+}
+
+fn parse_selector_list_with_mode(
+ values: &[ComponentValue],
+ declared_namespaces: &[TokenizerInput<'_>],
+ selector_type: SelectorType,
+ parsing_mode: SelectorParsingMode,
+) -> Result<ParsedSelectorTree, ()> {
+ let mut parser = SelectorParser::new(Some(declared_namespaces));
+ let selectors = parser.parse_selector_list(values, selector_type, parsing_mode)?;
+ Ok(ParsedSelectorTree {
+ selectors,
+ _names: parser.names.into_inner(),
+ })
}
pub(crate) fn parse_selector_list_from_component_values(
values: &[ComponentValue],
declared_namespaces: &[TokenizerInput<'_>],
selector_type: SelectorType,
-) -> Result<RustParsedSelectorList, ()> {
- let selectors = SelectorParser::new(Some(declared_namespaces)).parse_selector_list(
+) -> Result<ParsedSelectorTree, ()> {
+ parse_selector_list_with_mode(
values,
+ declared_namespaces,
selector_type,
SelectorParsingMode::Standard,
- )?;
- Ok(RustParsedSelectorList::new(selectors))
+ )
+}
+
+/// A selector list as the parser built it, with the names it interned, before it is packed into
+/// the arena a parsed list keeps.
+pub(crate) struct ParsedSelectorTree {
+ pub(crate) selectors: SelectorList,
+ /// A reference to each name the tree names, until the arena leases them.
+ _names: Vec<AtomLease>,
+}
+
+impl ParsedSelectorTree {
+ pub(crate) fn adapt_for_nesting(mut self, parent: StyleNestingParent) -> Self {
+ if parent == StyleNestingParent::None {
+ return self;
+ }
+ for selector in &mut self.selectors {
+ let first = selector
+ .compound_selectors()
+ .first()
+ .map_or(Combinator::None, |compound| compound.combinator);
+ let insert_nesting = parent == StyleNestingParent::Style
+ && (!matches!(first, Combinator::None | Combinator::Descendant)
+ || !super::selector_operations::contains_nesting(selector));
+ if insert_nesting {
+ *selector = super::selector_operations::relative_to(selector, SimpleSelector::Nesting);
+ } else if first == Combinator::Descendant {
+ let mut compounds = selector.to_compounds();
+ compounds[0].combinator = Combinator::None;
+ *selector = CompiledSelector::new(compounds);
+ }
+ }
+ self
+ }
+
+ pub(crate) fn contains_pseudo_element(&self) -> bool {
+ self.selectors
+ .iter()
+ .any(|selector| super::selector_tree::target_pseudo_element(selector).is_some())
+ }
+
+ pub(crate) fn is_empty(&self) -> bool {
+ self.selectors.is_empty()
+ }
+
+ /// The list, packed into an arena of its own, for a rule nested in `nesting_parent`. A `&`
+ /// naming a style rule is bound to it as the rule is placed.
+ pub(crate) fn into_list(self, nesting_parent: StyleNestingParent) -> RustParsedSelectorList {
+ self.into_list_declaring(nesting_parent, super::selector_arena::NamespaceDeclarations::default())
+ }
+
+ /// As [`Self::into_list`], for the selectors of a style rule of a sheet declaring `declarations`.
+ pub(crate) fn into_list_declaring(
+ self,
+ nesting_parent: StyleNestingParent,
+ declarations: super::selector_arena::NamespaceDeclarations,
+ ) -> RustParsedSelectorList {
+ let nesting = match nesting_parent {
+ StyleNestingParent::None => NestingTarget::Root,
+ StyleNestingParent::Scope => NestingTarget::Scope,
+ StyleNestingParent::Style => NestingTarget::Unbound,
+ };
+ let mut builder = super::selector_arena::SheetSelectorsBuilder::default();
+ builder.declare_namespaces(declarations);
+ RustParsedSelectorList {
+ selectors: builder.push(&self.selectors, self._names, nesting),
+ }
+ }
+
+ /// The selectors of a style rule, packed into the arena `selectors` builds, which it reads once
+ /// that is frozen, with the ordinal a `&` names the rule by there.
+ pub(crate) fn into_rule_list_in(
+ self,
+ selectors: &mut super::selector_arena::SheetSelectorsBuilder,
+ nesting: NestingTarget,
+ ) -> (RustParsedSelectorList, Option<RuleOrdinal>) {
+ let (selectors, ordinal) = selectors.push_rule(&self.selectors, self._names, nesting);
+ (RustParsedSelectorList { selectors }, ordinal)
+ }
}
fn parse_pseudo_element_selector(
input: TokenizerInput<'_>,
for_computed_style: bool,
-) -> Result<(Arc<CompiledSelector>, PseudoElementType), ()> {
+) -> Result<(SelectorRef, PseudoElementType), ()> {
let tokens = tokenize_for_parser(input);
let values = consume_a_list_of_component_values(tokens.as_slice())?;
let mut stream = Stream::new(&values);
- let simple = SelectorParser::new(Some(&[])).parse_pseudo_element(&mut stream)?;
+ // NB: The parser holds the names it interned until the selector built below leases them.
+ let mut parser = SelectorParser::new(Some(&[]));
+ let simple = parser.parse_pseudo_element(&mut stream)?;
if !stream.is_empty() {
return Err(());
}
@@ -1256,22 +1352,23 @@ fn parse_pseudo_element_selector(
return Err(());
}
let pseudo_element_type = pseudo_element.pseudo_element;
- Ok((
- CompiledSelector::new(
- normalize_pseudo_element_transitions(vec![CompoundSelector {
- combinator: Combinator::None,
- is_implicit_universal_anchor: false,
- simple_selectors: Box::new([simple]),
- }])
- .into_boxed_slice(),
- ),
- pseudo_element_type,
- ))
+ let selector = CompiledSelector::new(
+ normalize_pseudo_element_transitions(vec![CompoundSelector {
+ combinator: Combinator::None,
+ is_implicit_universal_anchor: false,
+ simple_selectors: Box::new([simple]),
+ }])
+ .into_boxed_slice(),
+ );
+ let list = SelectorListRef::pack(&[selector]);
+ let selector = list.owned().next().expect("the list holds the selector");
+ Ok((selector, pseudo_element_type))
}
+/// A parsed selector list, in the arena it is packed into.
#[derive(Clone, Debug, PartialEq)]
pub struct RustParsedSelectorList {
- pub(crate) selectors: SelectorList,
+ pub(crate) selectors: SelectorListRef,
}
// Parsed selectors and their interned names can be shared across threads.
@@ -1281,47 +1378,10 @@ const _: fn() = || {
};
impl RustParsedSelectorList {
- pub(crate) fn adapt_for_nesting(mut self, parent: StyleNestingParent) -> Self {
- if parent == StyleNestingParent::None {
- return self;
- }
- for selector in &mut self.selectors {
- let first = selector
- .compound_selectors
- .first()
- .map_or(Combinator::None, |compound| compound.combinator);
- let insert_nesting = parent == StyleNestingParent::Style
- && (!matches!(first, Combinator::None | Combinator::Descendant)
- || !super::selector_operations::contains_nesting(selector));
- if insert_nesting {
- *selector = super::selector_operations::relative_to(selector, SimpleSelector::Nesting);
- } else if first == Combinator::Descendant {
- let mut compounds = selector.compound_selectors.clone();
- compounds[0].combinator = Combinator::None;
- *selector = CompiledSelector::new(compounds);
- }
- }
- self
- }
-
- pub(crate) fn new(selectors: SelectorList) -> Self {
- Self { selectors }
- }
-
#[cfg(test)]
- pub(crate) fn selectors(&self) -> &SelectorList {
+ pub(crate) fn selectors(&self) -> &SelectorListRef {
&self.selectors
}
-
- pub(crate) fn contains_pseudo_element(&self) -> bool {
- self.selectors
- .iter()
- .any(|selector| selector.target_pseudo_element.is_some())
- }
-
- pub(crate) fn is_empty(&self) -> bool {
- self.selectors.is_empty()
- }
}
/// # Safety
@@ -1358,6 +1418,7 @@ pub extern "C" fn rust_selector_parse_with_namespace_context(
let Some(input) = input.units() else {
return std::ptr::null_mut();
};
+ let declarations = namespaces.map(crate::css::rule::NativeNamespaceContext::declarations);
let namespaces: Vec<_> = namespaces
.into_iter()
.flat_map(|namespaces| namespaces.prefixes.iter())
@@ -1378,7 +1439,9 @@ pub extern "C" fn rust_selector_parse_with_namespace_context(
},
)
.map_or(std::ptr::null_mut(), |selectors| {
- Box::into_raw(Box::new(RustParsedSelectorList::new(selectors)))
+ Box::into_raw(Box::new(
+ selectors.into_list_declaring(StyleNestingParent::None, declarations.unwrap_or_default()),
+ ))
})
}
@@ -1426,7 +1489,7 @@ pub(crate) unsafe fn parse_selector_list_from_ffi(
) else {
return None;
};
- Some(RustParsedSelectorList::new(selectors).adapt_for_nesting(nesting_parent))
+ Some(selectors.adapt_for_nesting(nesting_parent).into_list(nesting_parent))
}
}
@@ -1474,7 +1537,7 @@ pub extern "C" fn rust_parsed_selector_list_length(list: &RustParsedSelectorList
#[unsafe(no_mangle)]
pub extern "C" fn rust_parsed_selector_list_selector(list: &RustParsedSelectorList, index: usize) -> *mut RustSelector {
Box::into_raw(Box::new(RustSelector {
- selector: list.selectors[index].clone(),
+ selector: list.selectors.owned().nth(index).expect("the index is in bounds"),
}))
}
@@ -1503,7 +1566,7 @@ mod tests {
}
}
- fn serialize(selector: &Arc<CompiledSelector>) -> Vec<u16> {
+ fn serialize(selector: &SelectorRef) -> Vec<u16> {
crate::css::selector_serialization::serialize_selector_without_namespaces(&RustSelector {
selector: selector.clone(),
})
@@ -1521,13 +1584,18 @@ mod tests {
let parsed = std::thread::spawn(move || parse(source)).join().unwrap();
let first = parsed.clone();
let second = parsed.clone();
- assert!(Arc::ptr_eq(&first.selectors[0], &second.selectors[0]));
+ let first_selector = first.selectors.owned().next().unwrap();
+ let second_selector = second.selectors.owned().next().unwrap();
+ assert_eq!(first_selector.view(), second_selector.view());
drop(parsed);
- let expected = serialize(&first.selectors[0]);
- assert_eq!(serialize(&second.selectors[0]), expected);
- assert_eq!(first.selectors[0].specificity(), second.selectors[0].specificity());
- drop(first);
- assert_eq!(serialize(&second.selectors[0]), expected);
+ let expected = serialize(&first_selector);
+ assert_eq!(serialize(&second_selector), expected);
+ assert_eq!(
+ first_selector.view().specificity(),
+ second_selector.view().specificity()
+ );
+ drop((first, first_selector));
+ assert_eq!(serialize(&second_selector), expected);
}
}
@@ -1558,7 +1626,7 @@ mod tests {
.join()
.unwrap();
assert_eq!(
- serialize(&bound.selectors[0]),
+ serialize(&bound.selectors.owned().next().unwrap()),
"é|DIV#😀:is(.é, :not([data-name=\"😀\"])):nth-child(2n+1 of .item)::part(label)"
.encode_utf16()
.collect::<Vec<_>>()
diff --git a/Libraries/LibWeb/Rust/src/css/selector_serialization.rs b/Libraries/LibWeb/Rust/src/css/selector_serialization.rs
index 30e2e4afa5c..d8a8f33a2f5 100644
--- a/Libraries/LibWeb/Rust/src/css/selector_serialization.rs
+++ b/Libraries/LibWeb/Rust/src/css/selector_serialization.rs
@@ -7,8 +7,9 @@
//! CSS selector serialization.
use super::selector::{
- AnPlusBPattern, AttributeCaseType, AttributeMatchType, Combinator, CompiledSelector, FfiStringView, NamespaceType,
- PseudoClassParameterType, PseudoElementValue, QualifiedName, RustSelector, SimpleSelector, TransitionNameSelector,
+ AnPlusBPattern, AttributeCaseType, AttributeMatchType, Combinator, FfiStringView, NamespaceType,
+ PseudoClassParameterType, PseudoElementValue, QualifiedName, RustSelector, Selector, SelectorListView,
+ SimpleSelector, TransitionNameSelector,
};
use super::serialize::{StringUnits, TextSink, serialize_a_string, serialize_an_identifier};
@@ -23,6 +24,13 @@ fn push_units(sink: &mut TextSink, units: &[u16]) {
}
}
+/// The name `atom` names, which the selector naming it leases.
+fn name_text(atom: crate::css::style::index::StyleAtomID) -> super::retained_fly_string::RetainedUtf16FlyString {
+ crate::css::style::process_atoms()
+ .text(atom)
+ .unwrap_or_else(super::retained_fly_string::RetainedUtf16FlyString::none)
+}
+
fn serialize_identifier<'a>(sink: &mut TextSink, value: impl Into<super::css_tokenizer::TokenizerInput<'a>>) {
super::serialize::with_fly_string_units(value, |units| serialize_an_identifier(sink, &units));
}
@@ -31,7 +39,8 @@ fn maps_to_default(qualified_name: &QualifiedName, context: &NamespaceContext<'_
context.has_default_namespace
&& qualified_name.namespace_type == NamespaceType::Named
&& context.prefixes_mapping_to_default.iter().any(|prefix| {
- let namespace = super::css_tokenizer::TokenizerInput::from(&qualified_name.namespace);
+ let namespace = name_text(qualified_name.namespace);
+ let namespace = super::css_tokenizer::TokenizerInput::from(&namespace);
prefix.len() == namespace.len()
&& prefix
.iter()
@@ -53,7 +62,7 @@ fn serialize_qualified_name(
context: &NamespaceContext<'_>,
) {
if qualified_name.namespace_type == NamespaceType::Named && !maps_to_default(qualified_name, context) {
- serialize_identifier(sink, &qualified_name.namespace);
+ serialize_identifier(sink, &name_text(qualified_name.namespace));
sink.push_ascii("|");
} else if qualified_name.namespace_type == NamespaceType::Any && context.has_default_namespace {
sink.push_ascii("*|");
@@ -64,7 +73,7 @@ fn serialize_qualified_name(
if is_universal {
sink.push_ascii("*");
} else {
- serialize_identifier(sink, &qualified_name.name);
+ serialize_identifier(sink, &name_text(qualified_name.name));
}
}
@@ -89,11 +98,7 @@ fn serialize_an_plus_b(sink: &mut TextSink, pattern: AnPlusBPattern) {
}
}
-fn serialize_selector_list(
- sink: &mut TextSink,
- selectors: &[std::sync::Arc<CompiledSelector>],
- context: &NamespaceContext<'_>,
-) {
+fn serialize_selector_list(sink: &mut TextSink, selectors: SelectorListView<'_>, context: &NamespaceContext<'_>) {
for (index, selector) in selectors.iter().enumerate() {
if index != 0 {
sink.push_ascii(", ");
@@ -108,23 +113,23 @@ fn serialize_simple_selector(sink: &mut TextSink, selector: &SimpleSelector, con
SimpleSelector::TagName(qualified_name) => serialize_qualified_name(sink, qualified_name, false, context),
SimpleSelector::Id(name) => {
sink.push_ascii("#");
- serialize_identifier(sink, &name.name);
+ serialize_identifier(sink, &name_text(name.name));
}
SimpleSelector::Class(name) => {
sink.push_ascii(".");
- serialize_identifier(sink, &name.name);
+ serialize_identifier(sink, &name_text(name.name));
}
SimpleSelector::Attribute(attribute) => {
sink.push_ascii("[");
match attribute.qualified_name.namespace_type {
NamespaceType::Named => {
- serialize_identifier(sink, &attribute.qualified_name.namespace);
+ serialize_identifier(sink, &name_text(attribute.qualified_name.namespace));
sink.push_ascii("|");
}
NamespaceType::Any => sink.push_ascii("*|"),
NamespaceType::Default | NamespaceType::None => {}
}
- serialize_identifier(sink, &attribute.qualified_name.name);
+ serialize_identifier(sink, &name_text(attribute.qualified_name.name));
if attribute.match_type != AttributeMatchType::HasAttribute {
sink.push_ascii(match attribute.match_type {
AttributeMatchType::HasAttribute => unreachable!(),
@@ -135,7 +140,7 @@ fn serialize_simple_selector(sink: &mut TextSink, selector: &SimpleSelector, con
AttributeMatchType::StartsWithString => "^=",
AttributeMatchType::EndsWithString => "$=",
});
- serialize_a_string(sink, &StringUnits::Utf16(&attribute.value));
+ serialize_a_string(sink, &StringUnits::Utf16(attribute.value));
match attribute.case_type {
AttributeCaseType::Sensitive => sink.push_ascii(" s"),
AttributeCaseType::Insensitive => sink.push_ascii(" i"),
@@ -165,17 +170,17 @@ fn serialize_simple_selector(sink: &mut TextSink, selector: &SimpleSelector, con
serialize_an_plus_b(sink, pseudo_class.an_plus_b_pattern);
if !pseudo_class.argument_selector_list.is_empty() {
sink.push_ascii(" of ");
- serialize_selector_list(sink, &pseudo_class.argument_selector_list, context);
+ serialize_selector_list(sink, pseudo_class.argument_selector_list, context);
}
}
PseudoClassParameterType::CompoundSelector
| PseudoClassParameterType::ForgivingSelectorList
| PseudoClassParameterType::RelativeSelectorList
| PseudoClassParameterType::SelectorList => {
- serialize_selector_list(sink, &pseudo_class.argument_selector_list, context);
+ serialize_selector_list(sink, pseudo_class.argument_selector_list, context);
}
PseudoClassParameterType::Ident => {
- serialize_identifier(sink, pseudo_class.identifier.as_ref().unwrap());
+ serialize_identifier(sink, pseudo_class.identifier.unwrap());
}
PseudoClassParameterType::LanguageRanges => {
for (index, language) in pseudo_class.languages.iter().enumerate() {
@@ -183,9 +188,9 @@ fn serialize_simple_selector(sink: &mut TextSink, selector: &SimpleSelector, con
sink.push_ascii(", ");
}
if language.is_string {
- serialize_a_string(sink, &StringUnits::Utf16(&language.value));
+ serialize_a_string(sink, &StringUnits::Utf16(language.value));
} else {
- serialize_identifier(sink, &language.value);
+ serialize_identifier(sink, language.value);
}
}
}
@@ -202,7 +207,7 @@ fn serialize_simple_selector(sink: &mut TextSink, selector: &SimpleSelector, con
}
SimpleSelector::PseudoElement(pseudo_element) => {
sink.push_ascii("::");
- if let Some(name) = &pseudo_element.serialized_name {
+ if let Some(name) = pseudo_element.serialized_name {
serialize_identifier(sink, name);
} else {
sink.push_ascii(pseudo_element.pseudo_element.name());
@@ -211,7 +216,7 @@ fn serialize_simple_selector(sink: &mut TextSink, selector: &SimpleSelector, con
PseudoElementValue::None => {}
PseudoElementValue::CompoundSelector(selector) => {
sink.push_ascii("(");
- serialize_selector(sink, selector, context);
+ serialize_selector(sink, *selector, context);
sink.push_ascii(")");
}
PseudoElementValue::Identifiers(identifiers) => {
@@ -228,10 +233,10 @@ fn serialize_simple_selector(sink: &mut TextSink, selector: &SimpleSelector, con
sink.push_ascii("(");
match &argument.name {
Some(TransitionNameSelector::Universal) => sink.push_ascii("*"),
- Some(TransitionNameSelector::Name(name)) => serialize_identifier(sink, name),
+ Some(TransitionNameSelector::Name(name)) => serialize_identifier(sink, *name),
None => {}
}
- for class_name in &argument.classes {
+ for class_name in argument.classes.iter() {
sink.push_ascii(".");
serialize_identifier(sink, class_name);
}
@@ -239,13 +244,13 @@ fn serialize_simple_selector(sink: &mut TextSink, selector: &SimpleSelector, con
}
}
}
- SimpleSelector::Nesting => sink.push_ascii("&"),
+ SimpleSelector::Nesting(_) => sink.push_ascii("&"),
SimpleSelector::Invalid(source) => push_units(sink, source),
}
}
-fn serialize_selector(sink: &mut TextSink, selector: &CompiledSelector, context: &NamespaceContext<'_>) {
- if let Some(first) = selector.compound_selectors.first() {
+fn serialize_selector(sink: &mut TextSink, selector: Selector<'_>, context: &NamespaceContext<'_>) {
+ if let Some(first) = selector.compound_selectors().first() {
sink.push_ascii(match first.combinator {
Combinator::ImmediateChild => "> ",
Combinator::NextSibling => "+ ",
@@ -254,21 +259,26 @@ fn serialize_selector(sink: &mut TextSink, selector: &CompiledSelector, context:
Combinator::None | Combinator::Descendant | Combinator::PseudoElement => "",
});
}
- for (index, compound) in selector.compound_selectors.iter().enumerate() {
+ for (index, compound) in selector.compound_selectors().iter().enumerate() {
if compound.simple_selectors.len() == 1
- && let SimpleSelector::Universal(qualified_name) = &compound.simple_selectors[0]
+ && let Some(SimpleSelector::Universal(qualified_name)) = compound.simple_selectors.first()
{
let followed_by_pseudo = selector
- .compound_selectors
+ .compound_selectors()
.get(index + 1)
.is_some_and(|next| next.combinator == Combinator::PseudoElement);
if !(compound.is_implicit_universal_anchor
- || followed_by_pseudo && should_skip_universal(qualified_name, context))
+ || followed_by_pseudo && should_skip_universal(&qualified_name, context))
{
- serialize_simple_selector(sink, &compound.simple_selectors[0], context);
+ serialize_simple_selector(
+ sink,
+ &compound.simple_selectors.first().expect("one simple selector"),
+ context,
+ );
}
} else {
- for simple in &compound.simple_selectors {
+ for simple in compound.simple_selectors.iter() {
+ let simple = &simple;
if let SimpleSelector::Universal(qualified_name) = simple
&& (compound.is_implicit_universal_anchor || should_skip_universal(qualified_name, context))
{
@@ -277,7 +287,7 @@ fn serialize_selector(sink: &mut TextSink, selector: &CompiledSelector, context:
serialize_simple_selector(sink, simple, context);
}
}
- if let Some(next) = selector.compound_selectors.get(index + 1) {
+ if let Some(next) = selector.compound_selectors().get(index + 1) {
sink.push_ascii(match next.combinator {
Combinator::Descendant => " ",
Combinator::ImmediateChild => " > ",
diff --git a/Libraries/LibWeb/Rust/src/css/selector_tree.rs b/Libraries/LibWeb/Rust/src/css/selector_tree.rs
new file mode 100644
index 00000000000..0f61328157f
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/selector_tree.rs
@@ -0,0 +1,243 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The tree a selector parses into, which the parser builds and packs into a selector arena as it
+//! finishes a list. Nothing keeps it after the parse.
+
+use smallvec::SmallVec;
+use std::sync::Arc;
+
+use crate::css::selector::{
+ AnPlusBPattern, AttributeCaseType, AttributeMatchType, Combinator, Direction, NameSelector, PseudoClassType,
+ PseudoElementType, QualifiedName, SearchTextMatchFilter, SelectorString,
+};
+use crate::css::style::index::StyleAtomID;
+
+pub(crate) type SelectorList = Box<[Arc<CompiledSelector>]>;
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct AttributeSelector {
+ pub match_type: AttributeMatchType,
+ pub qualified_name: QualifiedName,
+ pub value: SelectorString,
+ /// The value as a process style atom, or none for a presence test.
+ pub value_identity: StyleAtomID,
+ pub case_type: AttributeCaseType,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct LanguageRange {
+ pub value: SelectorString,
+ pub is_string: bool,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct PseudoClassSelector {
+ pub pseudo_class: PseudoClassType,
+ pub an_plus_b_pattern: AnPlusBPattern,
+ pub argument_selector_list: SelectorList,
+ pub languages: Box<[LanguageRange]>,
+ pub direction: Option<Direction>,
+ pub identifier: Option<SelectorString>,
+ /// The identifier as a process style atom, where the pseudo-class names a state by it.
+ pub identifier_identity: StyleAtomID,
+ pub levels: Box<[i64]>,
+ pub is_forgiving: bool,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum PseudoElementValue {
+ None,
+ CompoundSelector(Arc<CompiledSelector>),
+ Identifiers(Box<[SelectorString]>),
+ TransitionName(Box<TransitionNameAndClassSelector>),
+}
+
+// https://drafts.csswg.org/css-view-transitions-1/#typedef-pt-name-selector
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum TransitionNameSelector {
+ Universal,
+ Name(SelectorString),
+}
+
+// https://drafts.csswg.org/css-view-transitions-2/#typedef-pt-name-and-class-selector
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct TransitionNameAndClassSelector {
+ pub name: Option<TransitionNameSelector>,
+ pub classes: Box<[SelectorString]>,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct PseudoElementSelector {
+ pub pseudo_element: PseudoElementType,
+ pub serialized_name: Option<SelectorString>,
+ pub value: PseudoElementValue,
+ /// The process style atom of each name in `value`, when it holds identifiers.
+ pub identifier_identities: Box<[StyleAtomID]>,
+}
+
+// Keep the common ID and class selectors inline without reserving space for the larger payloads.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum SimpleSelector {
+ Universal(Box<QualifiedName>),
+ TagName(Box<QualifiedName>),
+ Id(NameSelector),
+ Class(NameSelector),
+ Attribute(Box<AttributeSelector>),
+ PseudoClass(Box<PseudoClassSelector>),
+ PseudoElement(Box<PseudoElementSelector>),
+ Nesting,
+ Invalid(SelectorString),
+ /// The start of a compound in a complex selector's flat components, with the combinator
+ /// relating it to the compound left of it. It never appears among a compound's simple
+ /// selectors.
+ Compound {
+ combinator: Combinator,
+ is_implicit_universal_anchor: bool,
+ },
+}
+
+// Keep every simple selector to one word, plus the selector tag.
+const _: () = assert!(size_of::<SimpleSelector>() == 2 * size_of::<usize>());
+
+/// A compound selector to build a complex selector from.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct CompoundSelector {
+ /// The combinator relating this compound to the compound immediately to its left. The
+ /// leftmost compound therefore has `Combinator::None`.
+ pub combinator: Combinator,
+ pub is_implicit_universal_anchor: bool,
+ pub simple_selectors: Box<[SimpleSelector]>,
+}
+
+/// One compound of a complex selector, borrowed from its flat components.
+#[derive(Clone, Copy, Debug)]
+pub struct CompoundRef<'a> {
+ /// The combinator relating this compound to the compound immediately to its left. The
+ /// leftmost compound therefore has `Combinator::None`.
+ pub combinator: Combinator,
+ pub is_implicit_universal_anchor: bool,
+ pub simple_selectors: &'a [SimpleSelector],
+}
+
+impl CompoundRef<'_> {
+ #[must_use]
+ pub fn to_compound(self) -> CompoundSelector {
+ CompoundSelector {
+ combinator: self.combinator,
+ is_implicit_universal_anchor: self.is_implicit_universal_anchor,
+ simple_selectors: self.simple_selectors.into(),
+ }
+ }
+}
+
+/// One complex selector of the tree, its compounds flat: each compound is a
+/// [`SimpleSelector::Compound`] naming its combinator, followed by its simple selectors.
+#[derive(Debug, PartialEq, Eq)]
+pub struct CompiledSelector {
+ components: Box<[SimpleSelector]>,
+}
+
+impl CompiledSelector {
+ pub(crate) fn new(compound_selectors: Box<[CompoundSelector]>) -> Arc<Self> {
+ let count = compound_selectors
+ .iter()
+ .map(|compound| compound.simple_selectors.len() + 1)
+ .sum();
+ let mut components = Vec::with_capacity(count);
+ for compound in compound_selectors {
+ components.push(SimpleSelector::Compound {
+ combinator: compound.combinator,
+ is_implicit_universal_anchor: compound.is_implicit_universal_anchor,
+ });
+ components.extend(compound.simple_selectors);
+ }
+ Arc::new(Self {
+ components: components.into_boxed_slice(),
+ })
+ }
+
+ /// The compounds of the selector, left to right.
+ #[must_use]
+ pub fn compound_selectors(&self) -> SmallVec<[CompoundRef<'_>; 4]> {
+ let mut compounds = SmallVec::new();
+ let mut index = 0;
+ while index < self.components.len() {
+ let SimpleSelector::Compound {
+ combinator,
+ is_implicit_universal_anchor,
+ } = self.components[index]
+ else {
+ unreachable!("a compound starts with its combinator");
+ };
+ let start = index + 1;
+ index = start;
+ while index < self.components.len() && !matches!(self.components[index], SimpleSelector::Compound { .. }) {
+ index += 1;
+ }
+ compounds.push(CompoundRef {
+ combinator,
+ is_implicit_universal_anchor,
+ simple_selectors: &self.components[start..index],
+ });
+ }
+ compounds
+ }
+
+ /// The compounds of the selector, to build another from.
+ #[must_use]
+ pub fn to_compounds(&self) -> Box<[CompoundSelector]> {
+ self.compound_selectors()
+ .iter()
+ .map(|compound| compound.to_compound())
+ .collect()
+ }
+}
+
+fn search_text_match_filter_of_pseudo_class(pseudo_class: &PseudoClassSelector) -> Option<SearchTextMatchFilter> {
+ match pseudo_class.pseudo_class {
+ PseudoClassType::Current => Some(SearchTextMatchFilter::Current),
+ PseudoClassType::Not => {
+ let [argument] = &*pseudo_class.argument_selector_list else {
+ return None;
+ };
+ let compounds = argument.compound_selectors();
+ let [compound] = &*compounds else {
+ return None;
+ };
+ matches!(
+ compound.simple_selectors,
+ [SimpleSelector::PseudoClass(inner)] if inner.pseudo_class == PseudoClassType::Current
+ )
+ .then_some(SearchTextMatchFilter::NotCurrent)
+ }
+ _ => None,
+ }
+}
+
+pub(crate) fn search_text_match_filter(simple: &SimpleSelector) -> Option<SearchTextMatchFilter> {
+ match simple {
+ SimpleSelector::PseudoClass(pseudo_class) => search_text_match_filter_of_pseudo_class(pseudo_class),
+ _ => None,
+ }
+}
+
+/// Whether the selector's subject is a pseudo-element, which the parser checks where one is not allowed.
+pub(crate) fn target_pseudo_element(selector: &CompiledSelector) -> Option<PseudoElementType> {
+ let compounds = selector.compound_selectors();
+ let last = compounds.last()?;
+ match last.simple_selectors.first()? {
+ SimpleSelector::PseudoElement(selector)
+ if !matches!(
+ selector.pseudo_element,
+ PseudoElementType::Part | PseudoElementType::Slotted
+ ) =>
+ {
+ Some(selector.pseudo_element)
+ }
+ _ => None,
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/serialize.rs b/Libraries/LibWeb/Rust/src/css/serialize.rs
index dc70c14b492..76d419a29ac 100644
--- a/Libraries/LibWeb/Rust/src/css/serialize.rs
+++ b/Libraries/LibWeb/Rust/src/css/serialize.rs
@@ -10,6 +10,16 @@
//! The output stays ASCII until the first non-ASCII code unit forces UTF-16 storage, matching
//! AK::Utf16String's ASCII-or-UTF16 representation, then moves a native string owner to C++.
+use crate::css::style_value::{
+ AnchorPayload, AnchorSizePayload, BackgroundSizePayload, BorderImageSlicePayload, BorderRadiusPayload,
+ BorderRadiusRectPayload, ColorFunctionPayload, ColorMixPayload, ColorSchemePayload, ConicGradientPayload,
+ ContentPayload, CounterDefinitionsPayload, CounterPayload, CounterStylePayload, CounterStyleSystemPayload,
+ CursorPayload, EasingPayload, FontSourcePayload, FunctionPayload, GridTemplateAreaPayload,
+ GridTrackPlacementPayload, GridTrackSizeListPayload, ImagePayload, ImageSetPayload, LightDarkPayload,
+ LinearGradientPayload, OpenTypeTaggedPayload, PositionPayload, RadialGradientPayload, RadialSizePayload,
+ RandomValueSharingPayload, RatioPayload, RayPayload, RectPayload, ScrollbarColorPayload, ShadowPayload,
+ ShorthandPayload, TransformationPayload, UnresolvedPayload, UrlPayload,
+};
use std::fmt::Write;
mod shorthand;
@@ -706,16 +716,18 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
sink.push_ascii(&format!("U+{min_code_point:X}-{max_code_point:X}"));
}
}
- StyleValueData::Ratio { numerator, denominator } => {
+ StyleValueData::Ratio(ratio_payload) => {
+ let RatioPayload { numerator, denominator } = &**ratio_payload;
serialize_style_value(sink, numerator.data(), mode);
sink.push_ascii(" / ");
serialize_style_value(sink, denominator.data(), mode);
}
- StyleValueData::Url {
- url,
- url_type,
- modifiers,
- } => {
+ StyleValueData::Url(url_payload) => {
+ let UrlPayload {
+ url,
+ url_type,
+ modifiers,
+ } = &**url_payload;
// https://drafts.csswg.org/cssom-1/#serialize-a-url
sink.push_ascii(if *url_type == 0 { "url(" } else { "src(" });
serialize_url_text(sink, url);
@@ -738,12 +750,13 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
serialize_style_value(sink, offset, mode);
}
}
- StyleValueData::Rect {
- top,
- right,
- bottom,
- left,
- } => {
+ StyleValueData::Rect(rect_payload) => {
+ let RectPayload {
+ top,
+ right,
+ bottom,
+ left,
+ } = &**rect_payload;
sink.push_ascii("rect(");
for (index, side) in [top, right, bottom, left].into_iter().enumerate() {
if index > 0 {
@@ -753,11 +766,12 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
}
sink.push_ascii(")");
}
- StyleValueData::BorderRadius {
- is_elliptical: _,
- horizontal_radius,
- vertical_radius,
- } => {
+ StyleValueData::BorderRadius(border_radius_payload) => {
+ let BorderRadiusPayload {
+ is_elliptical: _,
+ horizontal_radius,
+ vertical_radius,
+ } = &**border_radius_payload;
let (horizontal, vertical) = (horizontal_radius.data(), vertical_radius.data());
let mut horizontal_sink = TextSink::new();
serialize_style_value(&mut horizontal_sink, horizontal, mode);
@@ -771,24 +785,25 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
sink.push_sink(&vertical_sink);
}
}
- StyleValueData::BorderRadiusRect {
- top_left,
- top_right,
- bottom_right,
- bottom_left,
- } => {
+ StyleValueData::BorderRadiusRect(border_radius_rect_payload) => {
+ let BorderRadiusRectPayload {
+ top_left,
+ top_right,
+ bottom_right,
+ bottom_left,
+ } = &**border_radius_rect_payload;
let corners = [top_left, top_right, bottom_right, bottom_left];
let mut horizontal = Vec::with_capacity(4);
let mut vertical = Vec::with_capacity(4);
for corner in corners {
- let StyleValueData::BorderRadius {
+ let StyleValueData::BorderRadius(border_radius_payload) = corner.data() else {
+ unreachable!("BorderRadiusRect style values must have valid value graphs");
+ };
+ let BorderRadiusPayload {
horizontal_radius,
vertical_radius,
..
- } = corner.data()
- else {
- unreachable!("BorderRadiusRect style values must have valid value graphs");
- };
+ } = &**border_radius_payload;
horizontal.push(horizontal_radius.data());
vertical.push(vertical_radius.data());
}
@@ -806,11 +821,12 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
StyleValueData::Display { raw } => {
serialize_display(sink, *raw);
}
- StyleValueData::ColorScheme {
- schemes,
- scheme_codes: _,
- only,
- } => {
+ StyleValueData::ColorScheme(color_scheme_payload) => {
+ let ColorSchemePayload {
+ schemes,
+ scheme_codes: _,
+ only,
+ } = &**color_scheme_payload;
if schemes.as_slice().is_empty() {
sink.push_ascii("normal");
return;
@@ -854,15 +870,17 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
sink.push_ascii(text_underline_position_vertical::NAMES[*vertical as usize]);
}
}
- StyleValueData::Position { edge_x, edge_y } => {
+ StyleValueData::Position(position_payload) => {
+ let PositionPayload { edge_x, edge_y } = &**position_payload;
serialize_style_value(sink, edge_x.data(), mode);
sink.push_ascii(" ");
serialize_style_value(sink, edge_y.data(), mode);
}
- StyleValueData::ScrollbarColor {
- thumb_color,
- track_color,
- } => {
+ StyleValueData::ScrollbarColor(scrollbar_color_payload) => {
+ let ScrollbarColorPayload {
+ thumb_color,
+ track_color,
+ } = &**scrollbar_color_payload;
serialize_style_value(sink, thumb_color.data(), mode);
sink.push_ascii(" ");
serialize_style_value(sink, track_color.data(), mode);
@@ -875,15 +893,16 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
_ => "stable both-edges",
});
}
- StyleValueData::Shadow {
- shadow_type,
- color,
- offset_x,
- offset_y,
- blur_radius,
- spread_distance,
- placement,
- } => {
+ StyleValueData::Shadow(shadow_payload) => {
+ let ShadowPayload {
+ shadow_type,
+ color,
+ offset_x,
+ offset_y,
+ blur_radius,
+ spread_distance,
+ placement,
+ } = &**shadow_payload;
if let Some(color) = color.optional_data() {
serialize_style_value(sink, color, mode);
sink.push_ascii(" ");
@@ -946,12 +965,13 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
}
serialize_style_value(sink, value, mode);
}
- StyleValueData::OpenTypeTagged {
- mode: tagged_mode,
- tag_name: tag,
- packed_tag: _,
- value,
- } => {
+ StyleValueData::OpenTypeTagged(open_type_tagged_payload) => {
+ let OpenTypeTaggedPayload {
+ mode: tagged_mode,
+ tag_name: tag,
+ packed_tag: _,
+ value,
+ } = &**open_type_tagged_payload;
with_fly_string_units(tag, |units| serialize_a_string(sink, &units));
let mut value_sink = TextSink::new();
serialize_style_value(&mut value_sink, value.data(), mode);
@@ -1011,7 +1031,8 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
serialize_style_value(sink, value, mode);
}
}
- StyleValueData::Function { name, value } if crate::css::calc_size::is_calc_size_function_name(name) => {
+ StyleValueData::Function(function) if crate::css::calc_size::is_calc_size_function_name(&function.name) => {
+ let value = &function.value;
// https://drafts.csswg.org/css-values-5/#calc-size
// Both arguments are calculations given without a calc() around them.
sink.push_ascii("calc-size(");
@@ -1030,7 +1051,8 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
}
sink.push_ascii(")");
}
- StyleValueData::Function { name, value } => {
+ StyleValueData::Function(function_payload) => {
+ let FunctionPayload { name, value } = &**function_payload;
with_fly_string_units(name, |units| push_units_raw(sink, &units));
sink.push_ascii("(");
serialize_style_value(sink, value.data(), mode);
@@ -1105,7 +1127,8 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
sink.push_sink(angle_sink);
}
}
- StyleValueData::Cursor { image, x, y } => {
+ StyleValueData::Cursor(cursor_payload) => {
+ let CursorPayload { image, x, y } = &**cursor_payload;
serialize_style_value(sink, image.data(), mode);
if let Some(x) = x.optional_data() {
sink.push_ascii(" ");
@@ -1114,12 +1137,13 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
serialize_style_value(sink, y.data(), mode);
}
}
- StyleValueData::Image {
- url,
- url_type,
- url_modifiers,
- resource_context,
- } => {
+ StyleValueData::Image(image_payload) => {
+ let ImagePayload {
+ url,
+ url_type,
+ url_modifiers,
+ resource_context,
+ } = &**image_payload;
sink.push_ascii(if *url_type == 0 { "url(" } else { "src(" });
// NB: Image values retain their base URL separately from their source text. CSSOM exposes the resolved URL.
let resolved_url = if mode.is_resolved()
@@ -1145,18 +1169,22 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
}
sink.push_ascii(")");
}
- StyleValueData::Unresolved { source_text, .. } => {
- for &code_unit in source_text.units() {
- sink.push_code_unit(code_unit);
- }
- }
- StyleValueData::BorderImageSlice {
- top,
- right,
- bottom,
- left,
- fill,
- } => {
+ StyleValueData::Unresolved(unresolved_payload) => {
+ let unresolved_payload: &UnresolvedPayload = unresolved_payload;
+ let source_text = unresolved_payload.source_text();
+ let units = source_text;
+ for index in 0..units.len() {
+ sink.push_code_unit(units.code_unit_at(index));
+ }
+ }
+ StyleValueData::BorderImageSlice(border_image_slice_payload) => {
+ let BorderImageSlicePayload {
+ top,
+ right,
+ bottom,
+ left,
+ fill,
+ } = &**border_image_slice_payload;
let (top, right, bottom, left) = (top.data(), right.data(), bottom.data(), left.data());
serialize_style_value(sink, top, mode);
// NOTE: The C++ serializer compares values, which is content equality here.
@@ -1176,19 +1204,21 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
sink.push_ascii(" fill");
}
}
- StyleValueData::Content { content, alt_text } => {
+ StyleValueData::Content(content_payload) => {
+ let ContentPayload { content, alt_text } = &**content_payload;
serialize_style_value(sink, content.data(), mode);
if let Some(alt_text) = alt_text.optional_data() {
sink.push_ascii(" / ");
serialize_style_value(sink, alt_text, mode);
}
}
- StyleValueData::Counter {
- function,
- counter_name,
- counter_style,
- join_string,
- } => {
+ StyleValueData::Counter(counter_payload) => {
+ let CounterPayload {
+ function,
+ counter_name,
+ counter_style,
+ join_string,
+ } = &**counter_payload;
let is_counters = *function == COUNTER_FUNCTION_COUNTERS;
sink.push_ascii(if is_counters { "counters(" } else { "counter(" });
with_fly_string_units(counter_name, |units| serialize_an_identifier(sink, &units));
@@ -1204,12 +1234,13 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
}
sink.push_ascii(")");
}
- StyleValueData::CounterStyle {
- is_symbols,
- name,
- symbols_type,
- symbols,
- } => {
+ StyleValueData::CounterStyle(counter_style_payload) => {
+ let CounterStylePayload {
+ is_symbols,
+ name,
+ symbols_type,
+ symbols,
+ } = &**counter_style_payload;
use crate::css::css_enums::symbols_type as symbols_type_enum;
if !*is_symbols {
with_fly_string_units(name, |units| push_units_raw(sink, &units));
@@ -1228,12 +1259,13 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
}
sink.push_ascii(")");
}
- StyleValueData::CounterStyleSystem {
- kind,
- system,
- first_symbol,
- name,
- } => {
+ StyleValueData::CounterStyleSystem(counter_style_system_payload) => {
+ let CounterStyleSystemPayload {
+ kind,
+ system,
+ first_symbol,
+ name,
+ } = &**counter_style_system_payload;
use crate::css::css_enums::counter_style_system;
match kind {
0 => sink.push_ascii(counter_style_system::NAMES[*system as usize]),
@@ -1250,7 +1282,8 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
}
}
}
- StyleValueData::CounterDefinitions { counter_definitions } => {
+ StyleValueData::CounterDefinitions(counter_definitions_payload) => {
+ let CounterDefinitionsPayload { counter_definitions } = &**counter_definitions_payload;
for (index, definition) in counter_definitions.as_slice().iter().enumerate() {
if index > 0 {
sink.push_ascii(" ");
@@ -1268,13 +1301,14 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
}
}
}
- StyleValueData::GridTrackPlacement {
- kind,
- value,
- has_name,
- name,
- ..
- } => {
+ StyleValueData::GridTrackPlacement(grid_track_placement_payload) => {
+ let GridTrackPlacementPayload {
+ kind,
+ value,
+ has_name,
+ name,
+ ..
+ } = &**grid_track_placement_payload;
// GridTrackPlacement::Type: Auto is 0, Span is 1, AreaOrLine is 2.
match kind {
0 => sink.push_ascii("auto"),
@@ -1304,13 +1338,14 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
}
}
}
- StyleValueData::RandomValueSharing {
- fixed_value,
- is_auto,
- has_name: _,
- name,
- element_shared,
- } => {
+ StyleValueData::RandomValueSharing(random_value_sharing_payload) => {
+ let RandomValueSharingPayload {
+ fixed_value,
+ is_auto,
+ has_name: _,
+ name,
+ element_shared,
+ } = &**random_value_sharing_payload;
if let Some(fixed_value) = fixed_value.optional_data() {
sink.push_ascii("fixed ");
return serialize_style_value(sink, fixed_value, mode);
@@ -1327,12 +1362,13 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
sink.push_ascii("element-shared");
}
}
- StyleValueData::Anchor {
- has_anchor_name,
- anchor_name,
- anchor_side,
- fallback_value,
- } => {
+ StyleValueData::Anchor(anchor_payload) => {
+ let AnchorPayload {
+ has_anchor_name,
+ anchor_name,
+ anchor_side,
+ fallback_value,
+ } = &**anchor_payload;
sink.push_ascii("anchor(");
if *has_anchor_name {
with_fly_string_units(anchor_name, |units| serialize_an_identifier(sink, &units));
@@ -1345,13 +1381,14 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
}
sink.push_ascii(")");
}
- StyleValueData::AnchorSize {
- has_anchor_name,
- anchor_name,
- has_anchor_size,
- anchor_size,
- fallback_value,
- } => {
+ StyleValueData::AnchorSize(anchor_size_payload) => {
+ let AnchorSizePayload {
+ has_anchor_name,
+ anchor_name,
+ has_anchor_size,
+ anchor_size,
+ fallback_value,
+ } = &**anchor_size_payload;
use crate::css::css_enums::anchor_size as anchor_size_enum;
sink.push_ascii("anchor-size(");
if *has_anchor_name {
@@ -1371,7 +1408,8 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
}
sink.push_ascii(")");
}
- StyleValueData::BackgroundSize { size_x, size_y } => {
+ StyleValueData::BackgroundSize(background_size_payload) => {
+ let BackgroundSizePayload { size_x, size_y } = &**background_size_payload;
let (size_x, size_y) = (size_x.data(), size_y.data());
if value_has_auto(size_x) && value_has_auto(size_y) {
sink.push_ascii("auto");
@@ -1381,7 +1419,8 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
sink.push_ascii(" ");
serialize_style_value(sink, size_y, mode);
}
- StyleValueData::LightDark { light, dark, .. } => {
+ StyleValueData::LightDark(light_dark_payload) => {
+ let LightDarkPayload { light, dark, .. } = &**light_dark_payload;
// FIXME: We don't have enough information to determine the computed value here.
// (Matches the C++ FIXME.)
sink.push_ascii("light-dark(");
@@ -1395,17 +1434,18 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
serialize_style_value(sink, color.data(), mode);
sink.push_ascii(")");
}
- StyleValueData::Easing {
- kind,
- linear_stops,
- x1,
- y1,
- x2,
- y2,
- number_of_intervals,
- step_position,
- ..
- } => {
+ StyleValueData::Easing(easing_payload) => {
+ let EasingPayload {
+ kind,
+ linear_stops,
+ x1,
+ y1,
+ x2,
+ y2,
+ number_of_intervals,
+ step_position,
+ ..
+ } = &**easing_payload;
use crate::css::css_enums::step_position as step_position_enum;
match kind {
// Easing kinds: linear is 0, cubic-bezier is 1, steps is 2.
@@ -1468,12 +1508,13 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
serialize_style_value(sink, value.data(), mode);
sink.push_ascii(")");
}
- StyleValueData::Ray {
- size,
- contain,
- angle,
- position,
- } => {
+ StyleValueData::Ray(ray_payload) => {
+ let RayPayload {
+ size,
+ contain,
+ angle,
+ position,
+ } = &**ray_payload;
// https://drafts.csswg.org/motion-1/#ray-function
// NB: The default <ray-size>, closest-side, is omitted.
sink.push_ascii("ray(");
@@ -1491,15 +1532,16 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
}
sink.push_ascii(")");
}
- StyleValueData::RadialSize {
- component_count,
- is_extent_0,
- extent_0,
- value_0,
- is_extent_1,
- extent_1,
- value_1,
- } => {
+ StyleValueData::RadialSize(radial_size_payload) => {
+ let RadialSizePayload {
+ component_count,
+ is_extent_0,
+ extent_0,
+ value_0,
+ is_extent_1,
+ extent_1,
+ value_1,
+ } = &**radial_size_payload;
use crate::css::css_enums::radial_extent;
let components = [(is_extent_0, extent_0, value_0), (is_extent_1, extent_1, value_1)];
for (index, (is_extent, extent, value)) in
@@ -1522,16 +1564,17 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
} => {
serialize_color_interpolation_method(sink, *is_polar, *color_space, *hue_interpolation_method);
}
- StyleValueData::LinearGradient {
- has_direction_value,
- direction_value,
- side_or_corner,
- color_stop_list,
- gradient_type,
- repeating,
- color_interpolation_method,
- color_syntax,
- } => {
+ StyleValueData::LinearGradient(linear_gradient_payload) => {
+ let LinearGradientPayload {
+ has_direction_value,
+ direction_value,
+ side_or_corner,
+ color_stop_list,
+ gradient_type,
+ repeating,
+ color_interpolation_method,
+ color_syntax,
+ } = &**linear_gradient_payload;
// The parser numbers the gradient type Standard 0 and WebKit 1, and the side or corner Top, Bottom,
// Left, Right, TopLeft, TopRight, BottomLeft, BottomRight.
let is_webkit = *gradient_type == 1;
@@ -1582,14 +1625,15 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
serialize_color_stop_list(sink, color_stop_list, mode);
sink.push_ascii(")");
}
- StyleValueData::ConicGradient {
- from_angle,
- position,
- color_stop_list,
- repeating,
- color_interpolation_method,
- color_syntax,
- } => {
+ StyleValueData::ConicGradient(conic_gradient_payload) => {
+ let ConicGradientPayload {
+ from_angle,
+ position,
+ color_stop_list,
+ repeating,
+ color_interpolation_method,
+ color_syntax,
+ } = &**conic_gradient_payload;
if *repeating {
sink.push_ascii("repeating-");
}
@@ -1632,15 +1676,16 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
serialize_color_stop_list(sink, color_stop_list, mode);
sink.push_ascii(")");
}
- StyleValueData::RadialGradient {
- ending_shape: _,
- size,
- position,
- color_stop_list,
- repeating,
- color_interpolation_method,
- color_syntax,
- } => {
+ StyleValueData::RadialGradient(radial_gradient_payload) => {
+ let RadialGradientPayload {
+ ending_shape: _,
+ size,
+ position,
+ color_stop_list,
+ repeating,
+ color_interpolation_method,
+ color_syntax,
+ } = &**radial_gradient_payload;
if *repeating {
sink.push_ascii("repeating-");
}
@@ -1679,7 +1724,8 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
serialize_color_stop_list(sink, color_stop_list, mode);
sink.push_ascii(")");
}
- StyleValueData::ImageSet { options } => {
+ StyleValueData::ImageSet(image_set_payload) => {
+ let ImageSetPayload { options } = &**image_set_payload;
sink.push_ascii("image-set(");
for (index, option) in options.as_slice().iter().enumerate() {
if index > 0 {
@@ -1697,11 +1743,12 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
}
sink.push_ascii(")");
}
- StyleValueData::GridTemplateArea {
- grid_areas,
- row_count,
- column_count,
- } => {
+ StyleValueData::GridTemplateArea(grid_template_area_payload) => {
+ let GridTemplateAreaPayload {
+ grid_areas,
+ row_count,
+ column_count,
+ } = &**grid_template_area_payload;
if *row_count == 0 {
sink.push_ascii("none");
return;
@@ -1723,11 +1770,12 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
serialize_a_string_sink(sink, &row_sink);
}
}
- StyleValueData::GridTrackSizeList {
- is_subgrid,
- preserve_line_name_sets: _,
- entries,
- } => {
+ StyleValueData::GridTrackSizeList(grid_track_size_list_payload) => {
+ let GridTrackSizeListPayload {
+ is_subgrid,
+ preserve_line_name_sets: _,
+ entries,
+ } = &**grid_track_size_list_payload;
// Tentatively, an auto-repeat with intrinsic track sizes resolves to none on a box that
// is not a laid-out grid container (a grid container serializes its used track list and
// never reaches this rule); see the css/css-grid/parsing
@@ -1836,12 +1884,13 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
}
}
}
- StyleValueData::Transformation {
- property,
- transform_function,
- values,
- ..
- } => {
+ StyleValueData::Transformation(transformation_payload) => {
+ let TransformationPayload {
+ property,
+ transform_function,
+ values,
+ ..
+ } = &**transformation_payload;
use crate::css::property_metadata::property_id;
let entries = values.as_slice();
let entry_data = |index: usize| entries.get(index).map(|value| value.data());
@@ -2012,16 +2061,17 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
}
sink.push_ascii(")");
}
- StyleValueData::FontSource {
- is_local,
- local_name,
- url,
- url_type,
- url_modifiers,
- has_format,
- format,
- tech,
- } => {
+ StyleValueData::FontSource(font_source_payload) => {
+ let FontSourcePayload {
+ is_local,
+ local_name,
+ url,
+ url_type,
+ url_modifiers,
+ has_format,
+ format,
+ tech,
+ } = &**font_source_payload;
use crate::css::css_enums::font_tech;
// NOTE: The C++ serializer ignores the mode, forcing Normal for local names.
if *is_local {
@@ -2053,28 +2103,32 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
sink.push_ascii(")");
}
}
- StyleValueData::Shorthand {
- shorthand_property,
- sub_properties,
- values,
- } => serialize_shorthand(
- sink,
- value,
- *shorthand_property,
- sub_properties.as_slice(),
- values,
- mode,
- ),
- StyleValueData::ColorFunction {
- color_base,
- channel_0,
- channel_1,
- channel_2,
- alpha,
- has_name,
- name,
- origin_color,
- } => {
+ StyleValueData::Shorthand(shorthand_payload) => {
+ let ShorthandPayload {
+ shorthand_property,
+ sub_properties,
+ values,
+ } = &**shorthand_payload;
+ serialize_shorthand(
+ sink,
+ value,
+ *shorthand_property,
+ sub_properties.as_slice(),
+ values,
+ mode,
+ );
+ }
+ StyleValueData::ColorFunction(color_function_payload) => {
+ let ColorFunctionPayload {
+ color_base,
+ channel_0,
+ channel_1,
+ channel_2,
+ alpha,
+ has_name,
+ name,
+ origin_color,
+ } = &**color_function_payload;
use crate::css::color_resolution::{
EMPTY_INPUT, SerializationBehavior, descriptor_for_color_type, to_color,
};
@@ -2186,12 +2240,13 @@ pub(crate) fn serialize_style_value(sink: &mut TextSink, value: &StyleValueData,
}
sink.push_ascii(")");
}
- StyleValueData::ColorMix {
- color_interpolation_method,
- colors,
- percentages,
- ..
- } => {
+ StyleValueData::ColorMix(color_mix_payload) => {
+ let ColorMixPayload {
+ color_interpolation_method,
+ colors,
+ percentages,
+ ..
+ } = &**color_mix_payload;
use crate::css::css_enums::rectangular_color_space;
// https://drafts.csswg.org/css-color-5/#serial-color-mix
sink.push_ascii("color-mix(");
@@ -2578,9 +2633,10 @@ fn edge_is_center(edge: &StyleValueData, mode: SerializationMode) -> bool {
/// Port of PositionStyleValue::is_center.
fn position_is_center(position: &StyleValueData, mode: SerializationMode) -> bool {
- let StyleValueData::Position { edge_x, edge_y } = position else {
+ let StyleValueData::Position(position_payload) = position else {
return false;
};
+ let PositionPayload { edge_x, edge_y } = &**position_payload;
edge_is_center(edge_x.data(), mode) && edge_is_center(edge_y.data(), mode)
}
@@ -2613,16 +2669,16 @@ fn alpha_should_be_serialized(alpha: &StyleValueData) -> bool {
// https://drafts.csswg.org/css-color-4/#missing
pub(crate) fn color_function_has_missing_component(value: &StyleValueData) -> bool {
use crate::css::style_value::is_none_keyword;
- let StyleValueData::ColorFunction {
+ let StyleValueData::ColorFunction(color_function_payload) = value else {
+ return false;
+ };
+ let ColorFunctionPayload {
channel_0,
channel_1,
channel_2,
alpha,
..
- } = value
- else {
- return false;
- };
+ } = &**color_function_payload;
[channel_0, channel_1, channel_2, alpha]
.iter()
.any(|component| component.optional_data().is_some_and(is_none_keyword))
@@ -3286,12 +3342,12 @@ fn serialize_shorthand(
longhand(property_id::BORDER_BOTTOM_LEFT_RADIUS),
];
let radius_sink = |corner: &StyleValueData, vertical: bool| {
- if let StyleValueData::BorderRadius {
- horizontal_radius,
- vertical_radius,
- ..
- } = corner
- {
+ if let StyleValueData::BorderRadius(border_radius_payload) = corner {
+ let BorderRadiusPayload {
+ horizontal_radius,
+ vertical_radius,
+ ..
+ } = &**border_radius_payload;
let radius = if vertical { vertical_radius } else { horizontal_radius };
return sub_sink(radius.data());
}
@@ -3449,7 +3505,7 @@ fn serialize_shorthand(
let (Some(start), Some(end)) = (longhand(start_id), longhand(end_id)) else {
unreachable!("Shorthand style values must have valid value graphs");
};
- let end_is_auto_placement = matches!(end, StyleValueData::GridTrackPlacement { kind: 0, .. });
+ let end_is_auto_placement = matches!(end, StyleValueData::GridTrackPlacement(placement) if placement.kind == 0);
// NB: When the start line is a lone <custom-ident>, omitting the end line would make it copy
// that ident on re-parse, so "/ auto" must be kept.
let start_is_lone_custom_ident = crate::css::parser::grid_parser::is_custom_ident_placement(start);
diff --git a/Libraries/LibWeb/Rust/src/css/serialize/shorthand.rs b/Libraries/LibWeb/Rust/src/css/serialize/shorthand.rs
index 08a9443f4ae..dc2d29708b3 100644
--- a/Libraries/LibWeb/Rust/src/css/serialize/shorthand.rs
+++ b/Libraries/LibWeb/Rust/src/css/serialize/shorthand.rs
@@ -7,7 +7,9 @@
use super::*;
use crate::css::parser::value_parser::{ParseContext, ParseOutcome, parse_css_value};
use crate::css::property_metadata::{longhands_for_shorthand, property_id};
+use crate::css::style_value::{GridTemplateAreaPayload, GridTrackSizeListPayload, ShorthandPayload, StyleValueBox};
use crate::css::style_value::{RetainedPropertyIdList, RetainedStyleValueData, RetainedStyleValueDataList};
+use crate::css::style_value_arc::StyleValueArc;
use std::borrow::Cow;
#[cfg(test)]
@@ -193,19 +195,19 @@ mod tests {
}
fn longhand(value: &StyleValueData, property: u16) -> Option<&StyleValueData> {
- let StyleValueData::Shorthand {
- sub_properties, values, ..
- } = value
- else {
+ let StyleValueData::Shorthand(shorthand_payload) = value else {
return None;
};
+ let ShorthandPayload {
+ sub_properties, values, ..
+ } = &**shorthand_payload;
values
.as_slice()
.get(sub_properties.as_slice().iter().position(|id| *id == property)?)
.map(|value| value.data())
}
-fn parse(property: u16, source: TokenizerInput<'_>) -> Option<std::sync::Arc<StyleValueData>> {
+fn parse(property: u16, source: TokenizerInput<'_>) -> Option<StyleValueArc> {
use crate::css::css_tokenizer::tokenize_for_parser;
use crate::css::parser::component_value::consume_a_list_of_component_values;
let values = consume_a_list_of_component_values(tokenize_for_parser(source)).ok()?;
@@ -220,7 +222,7 @@ fn parse(property: u16, source: TokenizerInput<'_>) -> Option<std::sync::Arc<Sty
pub(super) fn initial(property: u16) -> Cow<'static, StyleValueData> {
let longhands = longhands_for_shorthand(property);
if !longhands.is_empty() {
- return Cow::Owned(StyleValueData::Shorthand {
+ return Cow::Owned(StyleValueData::Shorthand(StyleValueBox::new(ShorthandPayload {
shorthand_property: property,
sub_properties: RetainedPropertyIdList::from_property_ids(longhands.to_vec()),
values: RetainedStyleValueDataList::from_retained_values(
@@ -229,7 +231,7 @@ pub(super) fn initial(property: u16) -> Cow<'static, StyleValueData> {
.map(|id| RetainedStyleValueData::from_owned(initial(*id).into_owned()))
.collect(),
),
- });
+ })));
}
// Every longhand's initial value parses, which value_parser's tests check.
crate::css::style_compute::initial_value(property).map_or(
@@ -282,9 +284,10 @@ pub(super) fn serialize(
| property_id::TRANSITION
| property_id::SCROLL_TIMELINE
| property_id::VIEW_TIMELINE => {
- let StyleValueData::Shorthand { sub_properties, .. } = whole else {
+ let StyleValueData::Shorthand(shorthand_payload) = whole else {
unreachable!("Shorthand style values retain values of the expected type");
};
+ let ShorthandPayload { sub_properties, .. } = &**shorthand_payload;
let reset_only = |id| {
property == property_id::ANIMATION
&& matches!(
@@ -530,9 +533,10 @@ pub(super) fn serialize(
property_id::BORDER_STYLE,
property_id::BORDER_COLOR,
] {
- let StyleValueData::Shorthand { values, .. } = get(id) else {
+ let StyleValueData::Shorthand(shorthand_payload) = get(id) else {
unreachable!("Shorthand style values retain values of the expected type");
};
+ let ShorthandPayload { values, .. } = &**shorthand_payload;
if !values
.as_slice()
.iter()
@@ -737,7 +741,7 @@ pub(super) fn serialize(
get(property_id::GRID_ROW_END),
get(property_id::GRID_COLUMN_END),
];
- let auto = |value: &StyleValueData| matches!(value, StyleValueData::GridTrackPlacement { kind: 0, .. });
+ let auto = |value: &StyleValueData| matches!(value, StyleValueData::GridTrackPlacement(placement) if placement.kind == 0);
let ident = |value: &StyleValueData| matches!(value, StyleValueData::CustomIdent { .. });
if auto(values[3]) && ident(values[1]) {
values[3] = values[1];
@@ -819,21 +823,9 @@ pub(super) fn serialize(
}
}
let (
- StyleValueData::GridTemplateArea {
- grid_areas,
- row_count,
- column_count,
- },
- StyleValueData::GridTrackSizeList {
- is_subgrid: rows_subgrid,
- entries: rows,
- ..
- },
- StyleValueData::GridTrackSizeList {
- is_subgrid: columns_subgrid,
- entries: columns,
- ..
- },
+ StyleValueData::GridTemplateArea(grid_template_area_payload_1),
+ StyleValueData::GridTrackSizeList(grid_track_size_list_payload_1),
+ StyleValueData::GridTrackSizeList(grid_track_size_list_payload_2),
) = (
get(property_id::GRID_TEMPLATE_AREAS),
get(property_id::GRID_TEMPLATE_ROWS),
@@ -843,6 +835,22 @@ pub(super) fn serialize(
default(sink);
return;
};
+ let GridTemplateAreaPayload {
+ grid_areas,
+ row_count,
+ column_count,
+ } = &**grid_template_area_payload_1;
+ let GridTrackSizeListPayload {
+ is_subgrid: rows_subgrid,
+ entries: rows,
+ ..
+ } = &**grid_track_size_list_payload_1;
+ let GridTrackSizeListPayload {
+ is_subgrid: columns_subgrid,
+ entries: columns,
+ ..
+ } = &**grid_track_size_list_payload_2;
+
let rows = rows.as_slice();
let columns = columns.as_slice();
if *row_count == 0 {
diff --git a/Libraries/LibWeb/Rust/src/css/style/style_invalidation.rs b/Libraries/LibWeb/Rust/src/css/style/style_invalidation.rs
index 493f3ccf5e8..455cfda87d5 100644
--- a/Libraries/LibWeb/Rust/src/css/style/style_invalidation.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/style_invalidation.rs
@@ -582,8 +582,8 @@ fn property_invalidation(property: u16, old: ComputedValuesView<'_>, new: Comput
) && (!old.text_reset().text_decoration_lines.as_slice().is_empty()
|| !new.text_reset().text_decoration_lines.as_slice().is_empty())
{
- result.repaint_text_decorations = property != property_id::COLOR
- || old.text_reset().text_decoration_color != new.text_reset().text_decoration_color;
+ result.repaint_text_decorations =
+ property != property_id::COLOR || old.text_decoration_color() != new.text_decoration_color();
}
// https://drafts.csswg.org/css-viewport/#effective-zoom
// NB: The lengths of each descendant are zoomed by its effective zoom, which the element's zoom is part of.
diff --git a/Libraries/LibWeb/Rust/src/css/style_compute.rs b/Libraries/LibWeb/Rust/src/css/style_compute.rs
index e938bbc128d..1a4d6dfd68d 100644
--- a/Libraries/LibWeb/Rust/src/css/style_compute.rs
+++ b/Libraries/LibWeb/Rust/src/css/style_compute.rs
@@ -15,16 +15,27 @@
//! Element-bound inputs, such as container sizes and tree positions, are
//! snapshotted by C++ before entering the Rust computation drive.
+use crate::css::computed_values::GroupValuesWriter;
use crate::css::css_string::CssString;
use crate::css::ffi_support::OwnedBox;
-use std::borrow::Cow;
+use crate::css::style_value::{
+ BackgroundSizePayload, BorderImageSlicePayload, BorderRadiusPayload, BorderRadiusRectPayload, CalculatedPayload,
+ ColorFunctionPayload, ColorMixPayload, ColorSchemePayload, ConicGradientPayload, ContentPayload,
+ CounterDefinitionsPayload, CounterPayload, CounterStylePayload, CursorPayload, EasingPayload, FunctionPayload,
+ GridTrackPlacementPayload, GridTrackSizeListPayload, ImagePayload, ImageSetPayload, LightDarkPayload,
+ LinearGradientPayload, OpenTypeTaggedPayload, PositionPayload, RadialGradientPayload, RadialSizePayload,
+ RandomValueSharingPayload, RatioPayload, RayPayload, RectPayload, ScrollbarColorPayload, ShadowPayload,
+ ShorthandPayload, UrlPayload,
+};
+use crate::css::style_value_arc::StyleValueArc;
+use smallvec::SmallVec;
use std::ffi::c_void;
-use std::sync::{Arc, OnceLock};
+use std::sync::OnceLock;
use crate::css::animated_overlay::{AnimatedOverlay, overlay_wins};
use crate::css::cascaded_properties::{CascadeOrigin, CascadedPropertyStore};
use crate::css::computed_longhand_table::{
- ComputedLonghandTable, HIGHLIGHT_COLOR_IS_CURRENT_COLOR, HIGHLIGHT_COLORS_AUTHORED,
+ HIGHLIGHT_COLOR_IS_CURRENT_COLOR, HIGHLIGHT_COLORS_AUTHORED, LonghandTableFlags,
};
use crate::css::css_pixels::{CssPixelRect, CssPixels};
use crate::css::display::FfiDisplay;
@@ -481,8 +492,7 @@ pub struct FfiComputedNumber {
/// Result of computing line-height: like FfiComputedNumber, but a resolved
/// calc may produce either a pixel length or a unitless number multiplier.
-#[repr(C)]
-pub struct FfiComputedLineHeight {
+pub struct ComputedLineHeight {
/// False when the value needs C++ handling (calc the core cannot resolve).
pub handled: bool,
/// True when the absolutized value is already the computed value.
@@ -492,7 +502,7 @@ pub struct FfiComputedLineHeight {
pub value: f64,
}
-const LINE_HEIGHT_UNHANDLED: FfiComputedLineHeight = FfiComputedLineHeight {
+const LINE_HEIGHT_UNHANDLED: ComputedLineHeight = ComputedLineHeight {
handled: false,
unchanged: false,
is_number: false,
@@ -827,21 +837,18 @@ pub enum FontSizeRecascadeStatus {
NeedsCppLengthResolution,
}
-#[repr(C)]
-pub struct FfiFontSizeRecascadeBatch {
+pub struct FontSizeRecascadeBatch {
pub status: FontSizeRecascadeStatus,
pub next_index: usize,
pub current_size_raw: i32,
pub depends_on_viewport_metrics: bool,
- pub skipped_calculated_value: bool,
}
/// The document's side of the lengths a monospace font-size recascade resolves on its own. Each
/// caller passes the inputs it computes with: C++ its own root metrics and viewport, which move
/// when it recomputes the root, and the style engine the inputs it prepared for the batch.
-#[repr(C)]
#[derive(Clone, Copy)]
-pub struct FfiFontSizeRecascadeDocumentInputs {
+pub struct FontSizeRecascadeDocumentInputs {
pub root_font_size: f64,
pub root_effective_zoom: f64,
pub root_font_metrics_depend_on_viewport_metrics: bool,
@@ -849,7 +856,7 @@ pub struct FfiFontSizeRecascadeDocumentInputs {
pub viewport_height: f64,
}
-impl FfiFontSizeRecascadeDocumentInputs {
+impl FontSizeRecascadeDocumentInputs {
pub(crate) fn from_document(inputs: &crate::css::style::bridge::FfiDocumentStyleComputationInputs) -> Self {
Self {
root_font_size: inputs.root_font_size,
@@ -882,9 +889,9 @@ pub(crate) fn recascade_font_size_batch<'a>(
current_size_raw: i32,
current_depends_on_viewport_metrics: bool,
default_size_raw: i32,
- document_inputs: FfiFontSizeRecascadeDocumentInputs,
+ document_inputs: FontSizeRecascadeDocumentInputs,
supplied_length_resolution_context: Option<&FfiLengthResolutionContext>,
-) -> FfiFontSizeRecascadeBatch {
+) -> FontSizeRecascadeBatch {
assert!(start_index <= value_count);
let mut current_size = CssPixels::from_raw(current_size_raw);
let mut depends_on_viewport_metrics = current_depends_on_viewport_metrics;
@@ -894,17 +901,12 @@ pub(crate) fn recascade_font_size_batch<'a>(
} else {
1.0
};
- let mut skipped_calculated_value = false;
- let stopped =
- |status, next_index, current_size: CssPixels, depends_on_viewport_metrics, skipped_calculated_value| {
- FfiFontSizeRecascadeBatch {
- status,
- next_index,
- current_size_raw: current_size.raw_value(),
- depends_on_viewport_metrics,
- skipped_calculated_value,
- }
- };
+ let stopped = |status, next_index, current_size: CssPixels, depends_on_viewport_metrics| FontSizeRecascadeBatch {
+ status,
+ next_index,
+ current_size_raw: current_size.raw_value(),
+ depends_on_viewport_metrics,
+ };
for index in start_index..value_count {
// NB: Keep the size before this ancestor for a batch that must retry this index with font metrics.
@@ -993,7 +995,6 @@ pub(crate) fn recascade_font_size_batch<'a>(
index,
inherited_size,
depends_on_viewport_metrics,
- skipped_calculated_value,
);
};
let result = absolutize_length(*value, *unit as usize, length_resolution_context);
@@ -1003,7 +1004,6 @@ pub(crate) fn recascade_font_size_batch<'a>(
index,
inherited_size,
depends_on_viewport_metrics,
- skipped_calculated_value,
);
}
current_size = CssPixels::nearest_value_for(result.px);
@@ -1011,7 +1011,6 @@ pub(crate) fn recascade_font_size_batch<'a>(
continue;
}
StyleValueData::Calculated { .. } => {
- skipped_calculated_value = true;
continue;
}
_ => {}
@@ -1021,20 +1020,13 @@ pub(crate) fn recascade_font_size_batch<'a>(
} else {
FontSizeRecascadeStatus::NeedsLengthResolution
};
- return stopped(
- status,
- index,
- inherited_size,
- depends_on_viewport_metrics,
- skipped_calculated_value,
- );
+ return stopped(status, index, inherited_size, depends_on_viewport_metrics);
}
stopped(
FontSizeRecascadeStatus::Complete,
value_count,
current_size,
depends_on_viewport_metrics,
- skipped_calculated_value,
)
}
@@ -1043,14 +1035,20 @@ pub(crate) fn recascade_font_size_batch<'a>(
/// the registry it was computed against, whichever side computed it.
pub(crate) fn content_reads_counter_style_environment(value: &StyleValueData) -> bool {
match value {
- StyleValueData::Counter { counter_style, .. } => matches!(
- counter_style.optional_data(),
- Some(StyleValueData::CounterStyle { is_symbols: false, .. })
- ),
- StyleValueData::Content { content, alt_text } => [content, alt_text].into_iter().any(|part| {
- part.optional_data()
- .is_some_and(content_reads_counter_style_environment)
- }),
+ StyleValueData::Counter(counter_payload) => {
+ let CounterPayload { counter_style, .. } = &**counter_payload;
+ matches!(
+ counter_style.optional_data().and_then(StyleValueData::as_counter_style),
+ Some(CounterStylePayload { is_symbols: false, .. })
+ )
+ }
+ StyleValueData::Content(content_payload) => {
+ let ContentPayload { content, alt_text } = &**content_payload;
+ [content, alt_text].into_iter().any(|part| {
+ part.optional_data()
+ .is_some_and(content_reads_counter_style_environment)
+ })
+ }
StyleValueData::ValueList { values, .. } => values.as_slice().iter().any(|item| {
item.optional_data()
.is_some_and(content_reads_counter_style_environment)
@@ -1059,11 +1057,6 @@ pub(crate) fn content_reads_counter_style_environment(value: &StyleValueData) ->
}
}
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_content_reads_counter_style_environment(value: &StyleValueData) -> bool {
- content_reads_counter_style_environment(value)
-}
-
/// The counter-style names no @counter-style rule overrides: decimal, disc, square, circle,
/// disclosure-open and disclosure-closed.
fn counter_style_name_is_non_overridable(name: &[u16]) -> bool {
@@ -1095,11 +1088,9 @@ pub(crate) fn style_reads_counter_style_environment(
) -> bool {
content.is_some_and(content_reads_counter_style_environment)
|| match list_style_type {
- Some(StyleValueData::CounterStyle {
- is_symbols: false,
- name,
- ..
- }) => is_pseudo || !counter_style_name_is_non_overridable(name.units()),
+ Some(StyleValueData::CounterStyle(counter_style)) if !counter_style.is_symbols => {
+ is_pseudo || !counter_style_name_is_non_overridable(counter_style.name.units())
+ }
_ => false,
}
}
@@ -1208,39 +1199,51 @@ pub(crate) fn value_is_computationally_independent(value: &StyleValueData) -> Op
StyleValueData::LightDark { .. } | StyleValueData::TreeCountingFunction { .. } => Some(false),
// The calculation tree decides natively; its style value leaves resolve through the
// same decision, falling back for the types the core cannot decide.
- StyleValueData::Calculated { rust_calculation, .. } => {
+ StyleValueData::Calculated(calculated_payload) => {
+ let CalculatedPayload { rust_calculation, .. } = &**calculated_payload;
Some(rust_calculation.node().is_computationally_independent(
&|unit| !length_unit_is_font_or_container_relative(unit),
&|retained| value_is_computationally_independent(retained.data()).unwrap_or_default(),
))
}
- StyleValueData::Ratio {
- numerator, denominator, ..
- } => all_data(&[numerator, denominator]),
+ StyleValueData::Ratio(ratio_payload) => {
+ let RatioPayload {
+ numerator, denominator, ..
+ } = &**ratio_payload;
+ all_data(&[numerator, denominator])
+ }
StyleValueData::Edge { offset, .. } => match offset.optional_data() {
Some(offset) => value_is_computationally_independent(offset),
None => Some(true),
},
- StyleValueData::Function { value, .. } => all_data(&[value]),
+ StyleValueData::Function(function_payload) => {
+ let FunctionPayload { value, .. } = &**function_payload;
+ all_data(&[value])
+ }
StyleValueData::OpacityValue { value } => all_data(&[value]),
// Auto placements carry no value; spans and lines recurse into theirs.
- StyleValueData::GridTrackPlacement { value, .. } => match value.optional_data() {
- Some(value) => value_is_computationally_independent(value),
- None => Some(true),
- },
- StyleValueData::GridTrackSizeList { entries, .. } => {
+ StyleValueData::GridTrackPlacement(grid_track_placement_payload) => {
+ let GridTrackPlacementPayload { value, .. } = &**grid_track_placement_payload;
+ match value.optional_data() {
+ Some(value) => value_is_computationally_independent(value),
+ None => Some(true),
+ }
+ }
+ StyleValueData::GridTrackSizeList(grid_track_size_list_payload) => {
+ let GridTrackSizeListPayload { entries, .. } = &**grid_track_size_list_payload;
grid_entries_are_computationally_independent(entries.as_slice())
}
// FIXME: Consider sub-values once we support <custom-color-space> values
StyleValueData::ColorInterpolationMethod { .. } => Some(true),
- StyleValueData::ColorFunction {
- channel_0,
- channel_1,
- channel_2,
- alpha,
- origin_color,
- ..
- } => {
+ StyleValueData::ColorFunction(color_function_payload) => {
+ let ColorFunctionPayload {
+ channel_0,
+ channel_1,
+ channel_2,
+ alpha,
+ origin_color,
+ ..
+ } = &**color_function_payload;
let mut independent = true;
for value in [channel_0, channel_1, channel_2, alpha, origin_color] {
if let Some(value) = value.optional_data() {
@@ -1249,14 +1252,18 @@ pub(crate) fn value_is_computationally_independent(value: &StyleValueData) -> Op
}
Some(independent)
}
- StyleValueData::BorderImageSlice {
- top,
- right,
- bottom,
- left,
- ..
- } => all_data(&[top, right, bottom, left]),
- StyleValueData::Content { content, alt_text } => {
+ StyleValueData::BorderImageSlice(border_image_slice_payload) => {
+ let BorderImageSlicePayload {
+ top,
+ right,
+ bottom,
+ left,
+ ..
+ } = &**border_image_slice_payload;
+ all_data(&[top, right, bottom, left])
+ }
+ StyleValueData::Content(content_payload) => {
+ let ContentPayload { content, alt_text } = &**content_payload;
let mut independent = value_is_computationally_independent(content.data())?;
if let Some(alt_text) = alt_text.optional_data() {
independent = independent && value_is_computationally_independent(alt_text)?;
@@ -1264,14 +1271,15 @@ pub(crate) fn value_is_computationally_independent(value: &StyleValueData) -> Op
Some(independent)
}
// Extent components carry no value; explicit sizes recurse into theirs.
- StyleValueData::RadialSize {
- component_count,
- is_extent_0,
- value_0,
- is_extent_1,
- value_1,
- ..
- } => {
+ StyleValueData::RadialSize(radial_size_payload) => {
+ let RadialSizePayload {
+ component_count,
+ is_extent_0,
+ value_0,
+ is_extent_1,
+ value_1,
+ ..
+ } = &**radial_size_payload;
let mut independent = true;
if !is_extent_0 {
independent = value_is_computationally_independent(value_0.data())?;
@@ -1310,20 +1318,31 @@ pub(crate) fn value_is_computationally_independent(value: &StyleValueData) -> Op
}
// Every filter kind's rule recurses into its single value.
StyleValueData::Filter { value, .. } => all_data(&[value]),
- StyleValueData::Ray { angle, position, .. } => {
+ StyleValueData::Ray(ray_payload) => {
+ let RayPayload { angle, position, .. } = &**ray_payload;
let mut independent = value_is_computationally_independent(angle.data())?;
if let Some(position) = position.optional_data() {
independent = independent && value_is_computationally_independent(position)?;
}
Some(independent)
}
- StyleValueData::Counter { counter_style, .. } => all_data(&[counter_style]),
- StyleValueData::OpenTypeTagged { value, .. } => all_data(&[value]),
- StyleValueData::RandomValueSharing { fixed_value, .. } => match fixed_value.optional_data() {
- Some(fixed_value) => value_is_computationally_independent(fixed_value),
- None => Some(true),
- },
- StyleValueData::Cursor { image, x, y } => {
+ StyleValueData::Counter(counter_payload) => {
+ let CounterPayload { counter_style, .. } = &**counter_payload;
+ all_data(&[counter_style])
+ }
+ StyleValueData::OpenTypeTagged(open_type_tagged_payload) => {
+ let OpenTypeTaggedPayload { value, .. } = &**open_type_tagged_payload;
+ all_data(&[value])
+ }
+ StyleValueData::RandomValueSharing(random_value_sharing_payload) => {
+ let RandomValueSharingPayload { fixed_value, .. } = &**random_value_sharing_payload;
+ match fixed_value.optional_data() {
+ Some(fixed_value) => value_is_computationally_independent(fixed_value),
+ None => Some(true),
+ }
+ }
+ StyleValueData::Cursor(cursor_payload) => {
+ let CursorPayload { image, x, y } = &**cursor_payload;
let mut independent = value_is_computationally_independent(image.data())?;
for coordinate in [x, y] {
if let Some(coordinate) = coordinate.optional_data() {
@@ -1334,15 +1353,16 @@ pub(crate) fn value_is_computationally_independent(value: &StyleValueData) -> Op
}
// The unused fields of the non-matching easing kinds are absent, so one
// null-tolerant conjunction covers every kind's rule.
- StyleValueData::Easing {
- linear_stops,
- x1,
- y1,
- x2,
- y2,
- number_of_intervals,
- ..
- } => {
+ StyleValueData::Easing(easing_payload) => {
+ let EasingPayload {
+ linear_stops,
+ x1,
+ y1,
+ x2,
+ y2,
+ number_of_intervals,
+ ..
+ } = &**easing_payload;
let mut independent = true;
for value in [x1, y1, x2, y2, number_of_intervals] {
if let Some(value) = value.optional_data() {
@@ -1358,14 +1378,16 @@ pub(crate) fn value_is_computationally_independent(value: &StyleValueData) -> Op
}
Some(independent)
}
- StyleValueData::ImageSet { options } => {
+ StyleValueData::ImageSet(image_set_payload) => {
+ let ImageSetPayload { options } = &**image_set_payload;
let mut independent = true;
for option in options.as_slice() {
independent = independent && all_data(&option.values())?;
}
Some(independent)
}
- StyleValueData::CounterDefinitions { counter_definitions } => {
+ StyleValueData::CounterDefinitions(counter_definitions_payload) => {
+ let CounterDefinitionsPayload { counter_definitions } = &**counter_definitions_payload;
let mut independent = true;
for definition in counter_definitions.as_slice() {
if let Some(value) = definition.value().optional_data() {
@@ -1374,12 +1396,13 @@ pub(crate) fn value_is_computationally_independent(value: &StyleValueData) -> Op
}
Some(independent)
}
- StyleValueData::LinearGradient {
- direction_value,
- color_stop_list,
- color_interpolation_method,
- ..
- } => {
+ StyleValueData::LinearGradient(linear_gradient_payload) => {
+ let LinearGradientPayload {
+ direction_value,
+ color_stop_list,
+ color_interpolation_method,
+ ..
+ } = &**linear_gradient_payload;
let mut independent = true;
for value in [direction_value, color_interpolation_method] {
if let Some(value) = value.optional_data() {
@@ -1395,13 +1418,14 @@ pub(crate) fn value_is_computationally_independent(value: &StyleValueData) -> Op
}
Some(independent)
}
- StyleValueData::ConicGradient {
- from_angle,
- position,
- color_stop_list,
- color_interpolation_method,
- ..
- } => {
+ StyleValueData::ConicGradient(conic_gradient_payload) => {
+ let ConicGradientPayload {
+ from_angle,
+ position,
+ color_stop_list,
+ color_interpolation_method,
+ ..
+ } = &**conic_gradient_payload;
let mut independent = true;
for value in [from_angle, position, color_interpolation_method] {
if let Some(value) = value.optional_data() {
@@ -1417,13 +1441,14 @@ pub(crate) fn value_is_computationally_independent(value: &StyleValueData) -> Op
}
Some(independent)
}
- StyleValueData::RadialGradient {
- size,
- position,
- color_stop_list,
- color_interpolation_method,
- ..
- } => {
+ StyleValueData::RadialGradient(radial_gradient_payload) => {
+ let RadialGradientPayload {
+ size,
+ position,
+ color_stop_list,
+ color_interpolation_method,
+ ..
+ } = &**radial_gradient_payload;
let mut independent = true;
for value in [size, position, color_interpolation_method] {
if let Some(value) = value.optional_data() {
@@ -1441,34 +1466,47 @@ pub(crate) fn value_is_computationally_independent(value: &StyleValueData) -> Op
}
StyleValueData::ContrastColor { color, .. } => all_data(&[color]),
StyleValueData::Superellipse { parameter } => all_data(&[parameter]),
- StyleValueData::ScrollbarColor {
- thumb_color,
- track_color,
- ..
- } => all_data(&[thumb_color, track_color]),
- StyleValueData::Rect {
- top,
- right,
- bottom,
- left,
- ..
- } => all_data(&[top, right, bottom, left]),
+ StyleValueData::ScrollbarColor(scrollbar_color_payload) => {
+ let ScrollbarColorPayload {
+ thumb_color,
+ track_color,
+ ..
+ } = &**scrollbar_color_payload;
+ all_data(&[thumb_color, track_color])
+ }
+ StyleValueData::Rect(rect_payload) => {
+ let RectPayload {
+ top,
+ right,
+ bottom,
+ left,
+ ..
+ } = &**rect_payload;
+ all_data(&[top, right, bottom, left])
+ }
StyleValueData::FontStyle { angle_value, .. } => match angle_value.optional_data() {
Some(angle_value) => value_is_computationally_independent(angle_value),
None => Some(true),
},
StyleValueData::TextIndent { length_percentage, .. } => all_data(&[length_percentage]),
StyleValueData::OverflowClipMargin { offset, .. } => all_data(&[offset]),
- StyleValueData::BackgroundSize { size_x, size_y, .. } => all_data(&[size_x, size_y]),
- StyleValueData::Position { edge_x, edge_y, .. } => all_data(&[edge_x, edge_y]),
- StyleValueData::Shadow {
- color,
- offset_x,
- offset_y,
- blur_radius,
- spread_distance,
- ..
- } => {
+ StyleValueData::BackgroundSize(background_size_payload) => {
+ let BackgroundSizePayload { size_x, size_y, .. } = &**background_size_payload;
+ all_data(&[size_x, size_y])
+ }
+ StyleValueData::Position(position_payload) => {
+ let PositionPayload { edge_x, edge_y, .. } = &**position_payload;
+ all_data(&[edge_x, edge_y])
+ }
+ StyleValueData::Shadow(shadow_payload) => {
+ let ShadowPayload {
+ color,
+ offset_x,
+ offset_y,
+ blur_radius,
+ spread_distance,
+ ..
+ } = &**shadow_payload;
let mut independent = value_is_computationally_independent(offset_x.data())?
&& value_is_computationally_independent(offset_y.data())?;
for value in [color, blur_radius, spread_distance] {
@@ -1478,12 +1516,13 @@ pub(crate) fn value_is_computationally_independent(value: &StyleValueData) -> Op
}
Some(independent)
}
- StyleValueData::ColorMix {
- color_interpolation_method,
- colors,
- percentages,
- ..
- } => {
+ StyleValueData::ColorMix(color_mix_payload) => {
+ let ColorMixPayload {
+ color_interpolation_method,
+ colors,
+ percentages,
+ ..
+ } = &**color_mix_payload;
let mut independent = true;
for value in std::iter::once(color_interpolation_method)
.chain(colors.as_slice())
@@ -1495,22 +1534,28 @@ pub(crate) fn value_is_computationally_independent(value: &StyleValueData) -> Op
}
Some(independent)
}
- StyleValueData::Shorthand { values, .. }
- | StyleValueData::ValueList { values, .. }
- | StyleValueData::Tuple { values }
- | StyleValueData::Transformation { values, .. } => all_data_in_list(values),
- StyleValueData::BorderRadiusRect {
- top_left,
- top_right,
- bottom_right,
- bottom_left,
- ..
- } => all_data(&[top_left, top_right, bottom_right, bottom_left]),
- StyleValueData::BorderRadius {
- horizontal_radius,
- vertical_radius,
- ..
- } => all_data(&[horizontal_radius, vertical_radius]),
+ StyleValueData::Shorthand(_)
+ | StyleValueData::ValueList { .. }
+ | StyleValueData::Tuple { .. }
+ | StyleValueData::Transformation(_) => all_data_in_list(value.child_values().unwrap()),
+ StyleValueData::BorderRadiusRect(border_radius_rect_payload) => {
+ let BorderRadiusRectPayload {
+ top_left,
+ top_right,
+ bottom_right,
+ bottom_left,
+ ..
+ } = &**border_radius_rect_payload;
+ all_data(&[top_left, top_right, bottom_right, bottom_left])
+ }
+ StyleValueData::BorderRadius(border_radius_payload) => {
+ let BorderRadiusPayload {
+ horizontal_radius,
+ vertical_radius,
+ ..
+ } = &**border_radius_payload;
+ all_data(&[horizontal_radius, vertical_radius])
+ }
_ => None,
}
}
@@ -1525,6 +1570,88 @@ pub(crate) struct ExternalValueDependencies {
pub needs_document_base_url: bool,
pub may_need_style_sheet_resource_context: bool,
pub inheritance_dependent: bool,
+ /// How much of the root element's font the value's root-relative lengths (`rem`, `rex`,
+ /// `rcap`, `rch`, `ric` or `rlh`) resolve against, which the document element's font decides.
+ pub root_font_reads: RootFontReads,
+ /// The value holds a length relative to a metric of the first available font of the element
+ /// or its parent (`ex`, `cap`, `ch` or `lh`), which a load of one of its faces moves.
+ pub font_metric_relative_length: bool,
+ /// The value resolves against the used color scheme: it holds `light-dark()` or a system color.
+ pub color_scheme_dependent: bool,
+ /// The value resolves against the device pixel ratio: it holds an `image-set()`, whose option
+ /// is chosen for the ratio.
+ pub device_pixel_ratio_dependent: bool,
+ /// The axes of the viewport the value's viewport-relative lengths resolve against, as
+ /// `VIEWPORT_WIDTH_AXIS` and `VIEWPORT_HEIGHT_AXIS` bits.
+ pub viewport_axes: u8,
+}
+
+/// The `viewport_axes` bit of a length relative to the viewport's width.
+pub(crate) const VIEWPORT_WIDTH_AXIS: u8 = 1 << 0;
+/// The `viewport_axes` bit of a length relative to the viewport's height.
+pub(crate) const VIEWPORT_HEIGHT_AXIS: u8 = 1 << 1;
+
+/// The axes of the viewport `unit` resolves against, as `viewport_axes` bits: an inline or block
+/// size, which the writing mode maps to an axis, and the smaller or larger size read either.
+/// https://drafts.csswg.org/css-values-4/#viewport-relative-lengths
+// NB: The small, large and dynamic viewports are the same size here, so their units read the same
+// axes.
+pub(crate) fn viewport_length_unit_axes(unit: u8) -> u8 {
+ let Some(name) = LENGTH_UNIT_NAMES.get(usize::from(unit)) else {
+ return 0;
+ };
+ match *name {
+ "vw" | "svw" | "lvw" | "dvw" => VIEWPORT_WIDTH_AXIS,
+ "vh" | "svh" | "lvh" | "dvh" => VIEWPORT_HEIGHT_AXIS,
+ "vi" | "svi" | "lvi" | "dvi" | "vb" | "svb" | "lvb" | "dvb" | "vmin" | "svmin" | "lvmin" | "dvmin" | "vmax"
+ | "svmax" | "lvmax" | "dvmax" => VIEWPORT_WIDTH_AXIS | VIEWPORT_HEIGHT_AXIS,
+ _ => 0,
+ }
+}
+
+/// Whether `unit` is relative to a metric of the element's or its parent's first available font,
+/// rather than to its font size alone.
+pub(crate) fn is_font_metric_relative_length_unit(unit: u8) -> bool {
+ matches!(
+ length_unit_kinds().get(usize::from(unit)),
+ Some(LengthUnitKind::FontRelative { root: false, metric }) if !matches!(metric, FontMetricSelector::FontSize)
+ )
+}
+
+/// How much of the root element's font a style resolves lengths against, ordered by what moves of
+/// that font it resolves them again for. As the move of a root element's font, the least a style
+/// must read of it to resolve its lengths again.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
+#[repr(u8)]
+pub(crate) enum RootFontReads {
+ #[default]
+ None,
+ /// Its font size, as zoomed, through `rem` or `ric`. As a move, the size moved, and with it
+ /// what every root-relative length resolves against.
+ FontSize,
+ /// A metric of its first available font, through `rex`, `rcap`, `rch` or `rlh`, which a load
+ /// of one of its faces moves without its size. As a move, only those metrics moved.
+ Metrics,
+}
+
+impl RootFontReads {
+ /// Whether a style reading this much of the root element's font resolves its lengths again
+ /// when the font makes the move `moved`.
+ pub(crate) fn reads_move(self, moved: RootFontReads) -> bool {
+ self != RootFontReads::None && moved != RootFontReads::None && self >= moved
+ }
+}
+
+/// How much of the root element's font `unit` is relative to.
+pub(crate) fn root_font_reads_of_length_unit(unit: u8) -> RootFontReads {
+ match length_unit_kinds().get(usize::from(unit)) {
+ Some(LengthUnitKind::FontRelative {
+ root: true,
+ metric: FontMetricSelector::FontSize,
+ }) => RootFontReads::FontSize,
+ Some(LengthUnitKind::FontRelative { root: true, .. }) => RootFontReads::Metrics,
+ _ => RootFontReads::None,
+ }
}
pub(crate) fn container_relative_length_unit_bit(unit: u8) -> u8 {
@@ -1595,6 +1722,9 @@ pub(crate) fn collect_external_value_dependencies(value: &StyleValueData) -> Ext
match node {
crate::css::calc::CalcNode::Numeric(crate::css::calc::CalcNumericValue::Length { unit, .. }) => {
dependencies.container_relative_length_unit_mask |= container_relative_length_unit_bit(*unit);
+ dependencies.root_font_reads = dependencies.root_font_reads.max(root_font_reads_of_length_unit(*unit));
+ dependencies.font_metric_relative_length |= is_font_metric_relative_length_unit(*unit);
+ dependencies.viewport_axes |= viewport_length_unit_axes(*unit);
}
crate::css::calc::CalcNode::Random { sharing, .. } => {
dependencies.uses_random_function = true;
@@ -1611,16 +1741,26 @@ pub(crate) fn collect_external_value_dependencies(value: &StyleValueData) -> Ext
fn collect(value: &StyleValueData, dependencies: &mut ExternalValueDependencies) {
match value {
StyleValueData::TreeCountingFunction { .. } => dependencies.uses_tree_counting_function = true,
+ // https://drafts.csswg.org/css-color-4/#css-system-colors
+ StyleValueData::Keyword { keyword } => {
+ dependencies.color_scheme_dependent |=
+ crate::css::color_resolution::system_color_for_keyword(*keyword, false).is_some();
+ }
StyleValueData::Length { unit, .. } => {
dependencies.container_relative_length_unit_mask |= container_relative_length_unit_bit(*unit);
- }
- StyleValueData::Image {
- url, resource_context, ..
- } => {
+ dependencies.root_font_reads = dependencies.root_font_reads.max(root_font_reads_of_length_unit(*unit));
+ dependencies.font_metric_relative_length |= is_font_metric_relative_length_unit(*unit);
+ dependencies.viewport_axes |= viewport_length_unit_axes(*unit);
+ }
+ StyleValueData::Image(image_payload) => {
+ let ImagePayload {
+ url, resource_context, ..
+ } = &**image_payload;
dependencies.needs_document_base_url |= !url.is_empty() && !resource_context.has_base_url;
dependencies.may_need_style_sheet_resource_context |= !url.is_empty();
}
- StyleValueData::Url { url, .. } => {
+ StyleValueData::Url(url_payload) => {
+ let UrlPayload { url, .. } = &**url_payload;
if !url.is_empty() && !url.is_fragment() {
let needs_base_url =
liburl_rust::basic_parse(url.url_input(), liburl_rust::BasicParseOptions::new()).is_none();
@@ -1628,58 +1768,75 @@ pub(crate) fn collect_external_value_dependencies(value: &StyleValueData) -> Ext
dependencies.may_need_style_sheet_resource_context |= needs_base_url;
}
}
- StyleValueData::Calculated { rust_calculation, .. } => {
+ StyleValueData::Calculated(calculated_payload) => {
+ let CalculatedPayload { rust_calculation, .. } = &**calculated_payload;
collect_calculation(rust_calculation.node(), dependencies);
}
- StyleValueData::Ratio {
- numerator, denominator, ..
- } => {
+ StyleValueData::Ratio(ratio_payload) => {
+ let RatioPayload {
+ numerator, denominator, ..
+ } = &**ratio_payload;
collect_values(&[numerator, denominator], dependencies);
}
StyleValueData::Edge { offset, .. } => collect_optional(offset, dependencies),
- StyleValueData::Anchor { fallback_value, .. } | StyleValueData::AnchorSize { fallback_value, .. } => {
+ StyleValueData::Anchor(_) | StyleValueData::AnchorSize(_) => {
+ let (_, _, fallback_value) = value.anchor_name_and_fallback().unwrap();
collect_optional(fallback_value, dependencies);
}
- StyleValueData::Ray { angle, position, .. } => {
+ StyleValueData::Ray(ray_payload) => {
+ let RayPayload { angle, position, .. } = &**ray_payload;
collect_optional(angle, dependencies);
collect_optional(position, dependencies);
}
- StyleValueData::Function { value, .. }
- | StyleValueData::OpacityValue { value }
- | StyleValueData::Filter { value, .. }
- | StyleValueData::OpenTypeTagged { value, .. }
- | StyleValueData::GridTrackPlacement { value, .. } => collect_optional(value, dependencies),
- StyleValueData::GridTrackSizeList { entries, .. } => {
+ StyleValueData::Function(function) => collect_optional(&function.value, dependencies),
+ StyleValueData::OpenTypeTagged(open_type_tagged) => collect_optional(&open_type_tagged.value, dependencies),
+ StyleValueData::GridTrackPlacement(grid_track_placement) => {
+ collect_optional(&grid_track_placement.value, dependencies);
+ }
+ StyleValueData::OpacityValue { value } | StyleValueData::Filter { value, .. } => {
+ collect_optional(value, dependencies);
+ }
+ StyleValueData::GridTrackSizeList(grid_track_size_list_payload) => {
+ let GridTrackSizeListPayload { entries, .. } = &**grid_track_size_list_payload;
collect_grid_entries(entries.as_slice(), dependencies);
}
- StyleValueData::ColorFunction {
- channel_0,
- channel_1,
- channel_2,
- alpha,
- origin_color,
- ..
- } => collect_values(&[channel_0, channel_1, channel_2, alpha, origin_color], dependencies),
- StyleValueData::BorderImageSlice {
- top,
- right,
- bottom,
- left,
- ..
+ StyleValueData::ColorFunction(color_function_payload) => {
+ let ColorFunctionPayload {
+ channel_0,
+ channel_1,
+ channel_2,
+ alpha,
+ origin_color,
+ ..
+ } = &**color_function_payload;
+ collect_values(&[channel_0, channel_1, channel_2, alpha, origin_color], dependencies);
+ }
+ StyleValueData::BorderImageSlice(border_image_slice) => {
+ let BorderImageSlicePayload {
+ top,
+ right,
+ bottom,
+ left,
+ ..
+ } = &**border_image_slice;
+ collect_values(&[top, right, bottom, left], dependencies);
}
- | StyleValueData::Rect {
- top,
- right,
- bottom,
- left,
- } => {
+ StyleValueData::Rect(rect_payload) => {
+ let RectPayload {
+ top,
+ right,
+ bottom,
+ left,
+ } = &**rect_payload;
collect_values(&[top, right, bottom, left], dependencies);
}
- StyleValueData::Content { content, alt_text } => {
+ StyleValueData::Content(content_payload) => {
+ let ContentPayload { content, alt_text } = &**content_payload;
collect(content.data(), dependencies);
collect_optional(alt_text, dependencies);
}
- StyleValueData::RadialSize { value_0, value_1, .. } => {
+ StyleValueData::RadialSize(radial_size_payload) => {
+ let RadialSizePayload { value_0, value_1, .. } = &**radial_size_payload;
collect_values(&[value_0, value_1], dependencies);
}
StyleValueData::BasicShape { shape } => {
@@ -1699,8 +1856,12 @@ pub(crate) fn collect_external_value_dependencies(value: &StyleValueData) -> Ext
}
}
}
- StyleValueData::Counter { counter_style, .. } => collect(counter_style.data(), dependencies),
- StyleValueData::RandomValueSharing { fixed_value, .. } => {
+ StyleValueData::Counter(counter_payload) => {
+ let CounterPayload { counter_style, .. } = &**counter_payload;
+ collect(counter_style.data(), dependencies);
+ }
+ StyleValueData::RandomValueSharing(random_value_sharing_payload) => {
+ let RandomValueSharingPayload { fixed_value, .. } = &**random_value_sharing_payload;
dependencies.uses_random_function = true;
if fixed_value.optional_data().is_some() {
collect_optional(fixed_value, dependencies);
@@ -1708,19 +1869,21 @@ pub(crate) fn collect_external_value_dependencies(value: &StyleValueData) -> Ext
dependencies.has_unfixed_random_sharing = true;
}
}
- StyleValueData::Cursor { image, x, y } => {
+ StyleValueData::Cursor(cursor_payload) => {
+ let CursorPayload { image, x, y } = &**cursor_payload;
collect(image.data(), dependencies);
collect_values(&[x, y], dependencies);
}
- StyleValueData::Easing {
- linear_stops,
- x1,
- y1,
- x2,
- y2,
- number_of_intervals,
- ..
- } => {
+ StyleValueData::Easing(easing_payload) => {
+ let EasingPayload {
+ linear_stops,
+ x1,
+ y1,
+ x2,
+ y2,
+ number_of_intervals,
+ ..
+ } = &**easing_payload;
collect_values(&[x1, y1, x2, y2, number_of_intervals], dependencies);
for stop in linear_stops.as_slice() {
for value in stop.values() {
@@ -1728,24 +1891,28 @@ pub(crate) fn collect_external_value_dependencies(value: &StyleValueData) -> Ext
}
}
}
- StyleValueData::ImageSet { options } => {
+ StyleValueData::ImageSet(image_set_payload) => {
+ let ImageSetPayload { options } = &**image_set_payload;
+ dependencies.device_pixel_ratio_dependent = true;
for option in options.as_slice() {
for value in option.values() {
collect_optional(value, dependencies);
}
}
}
- StyleValueData::CounterDefinitions { counter_definitions } => {
+ StyleValueData::CounterDefinitions(counter_definitions_payload) => {
+ let CounterDefinitionsPayload { counter_definitions } = &**counter_definitions_payload;
for definition in counter_definitions.as_slice() {
collect_optional(definition.value(), dependencies);
}
}
- StyleValueData::LinearGradient {
- direction_value,
- color_stop_list,
- color_interpolation_method,
- ..
- } => {
+ StyleValueData::LinearGradient(linear_gradient_payload) => {
+ let LinearGradientPayload {
+ direction_value,
+ color_stop_list,
+ color_interpolation_method,
+ ..
+ } = &**linear_gradient_payload;
collect_values(&[direction_value, color_interpolation_method], dependencies);
for stop in color_stop_list.as_slice() {
for value in stop.values() {
@@ -1753,13 +1920,14 @@ pub(crate) fn collect_external_value_dependencies(value: &StyleValueData) -> Ext
}
}
}
- StyleValueData::ConicGradient {
- from_angle,
- position,
- color_stop_list,
- color_interpolation_method,
- ..
- } => {
+ StyleValueData::ConicGradient(conic_gradient_payload) => {
+ let ConicGradientPayload {
+ from_angle,
+ position,
+ color_stop_list,
+ color_interpolation_method,
+ ..
+ } = &**conic_gradient_payload;
collect_values(&[from_angle, position, color_interpolation_method], dependencies);
for stop in color_stop_list.as_slice() {
for value in stop.values() {
@@ -1767,13 +1935,14 @@ pub(crate) fn collect_external_value_dependencies(value: &StyleValueData) -> Ext
}
}
}
- StyleValueData::RadialGradient {
- size,
- position,
- color_stop_list,
- color_interpolation_method,
- ..
- } => {
+ StyleValueData::RadialGradient(radial_gradient_payload) => {
+ let RadialGradientPayload {
+ size,
+ position,
+ color_stop_list,
+ color_interpolation_method,
+ ..
+ } = &**radial_gradient_payload;
collect_values(&[size, position, color_interpolation_method], dependencies);
for stop in color_stop_list.as_slice() {
for value in stop.values() {
@@ -1781,23 +1950,29 @@ pub(crate) fn collect_external_value_dependencies(value: &StyleValueData) -> Ext
}
}
}
- StyleValueData::ColorMix {
- color_interpolation_method,
- colors,
- percentages,
- ..
- } => {
+ StyleValueData::ColorMix(color_mix_payload) => {
+ let ColorMixPayload {
+ color_interpolation_method,
+ colors,
+ percentages,
+ ..
+ } = &**color_mix_payload;
collect_values(&[color_interpolation_method], dependencies);
collect_values(&colors.as_slice().iter().collect::<Vec<_>>(), dependencies);
collect_values(&percentages.as_slice().iter().collect::<Vec<_>>(), dependencies);
}
StyleValueData::ContrastColor { color, .. } => collect(color.data(), dependencies),
- StyleValueData::LightDark { light, dark, .. } => collect_values(&[light, dark], dependencies),
+ StyleValueData::LightDark(light_dark_payload) => {
+ let LightDarkPayload { light, dark, .. } = &**light_dark_payload;
+ dependencies.color_scheme_dependent = true;
+ collect_values(&[light, dark], dependencies);
+ }
StyleValueData::Superellipse { parameter } => collect_optional(parameter, dependencies),
- StyleValueData::ScrollbarColor {
- thumb_color,
- track_color,
- } => {
+ StyleValueData::ScrollbarColor(scrollbar_color_payload) => {
+ let ScrollbarColorPayload {
+ thumb_color,
+ track_color,
+ } = &**scrollbar_color_payload;
collect_values(&[thumb_color, track_color], dependencies);
}
StyleValueData::FontStyle { angle_value, .. } => collect_optional(angle_value, dependencies),
@@ -1805,39 +1980,48 @@ pub(crate) fn collect_external_value_dependencies(value: &StyleValueData) -> Ext
collect_optional(length_percentage, dependencies);
}
StyleValueData::OverflowClipMargin { offset, .. } => collect_optional(offset, dependencies),
- StyleValueData::BackgroundSize { size_x, size_y } => collect_values(&[size_x, size_y], dependencies),
- StyleValueData::Position { edge_x, edge_y } => collect_values(&[edge_x, edge_y], dependencies),
- StyleValueData::Shadow {
- color,
- offset_x,
- offset_y,
- blur_radius,
- spread_distance,
- ..
- } => {
+ StyleValueData::BackgroundSize(background_size_payload) => {
+ let BackgroundSizePayload { size_x, size_y } = &**background_size_payload;
+ collect_values(&[size_x, size_y], dependencies);
+ }
+ StyleValueData::Position(position_payload) => {
+ let PositionPayload { edge_x, edge_y } = &**position_payload;
+ collect_values(&[edge_x, edge_y], dependencies);
+ }
+ StyleValueData::Shadow(shadow_payload) => {
+ let ShadowPayload {
+ color,
+ offset_x,
+ offset_y,
+ blur_radius,
+ spread_distance,
+ ..
+ } = &**shadow_payload;
collect_values(&[color, offset_x, offset_y, blur_radius, spread_distance], dependencies);
}
- StyleValueData::Shorthand { values, .. }
- | StyleValueData::ValueList { values, .. }
- | StyleValueData::Tuple { values }
- | StyleValueData::Transformation { values, .. } => {
- for value in values.as_slice() {
+ StyleValueData::Shorthand(_)
+ | StyleValueData::ValueList { .. }
+ | StyleValueData::Tuple { .. }
+ | StyleValueData::Transformation(_) => {
+ for value in value.child_values().unwrap().as_slice() {
collect_optional(value, dependencies);
}
}
- StyleValueData::BorderRadiusRect {
- top_left,
- top_right,
- bottom_right,
- bottom_left,
- } => {
+ StyleValueData::BorderRadiusRect(border_radius_rect_payload) => {
+ let BorderRadiusRectPayload {
+ top_left,
+ top_right,
+ bottom_right,
+ bottom_left,
+ } = &**border_radius_rect_payload;
collect_values(&[top_left, top_right, bottom_right, bottom_left], dependencies);
}
- StyleValueData::BorderRadius {
- horizontal_radius,
- vertical_radius,
- ..
- } => {
+ StyleValueData::BorderRadius(border_radius_payload) => {
+ let BorderRadiusPayload {
+ horizontal_radius,
+ vertical_radius,
+ ..
+ } = &**border_radius_payload;
collect_values(&[horizontal_radius, vertical_radius], dependencies);
}
_ => {}
@@ -1853,6 +2037,15 @@ pub(crate) fn value_may_need_style_sheet_resource_context(value: &StyleValueData
collect_external_value_dependencies(value).may_need_style_sheet_resource_context
}
+/// The external dependencies of a value, or `None` for one whose computational independence is
+/// not known, which only a value that never reaches computation has.
+pub(crate) fn try_external_value_dependencies(value: &StyleValueData) -> Option<ExternalValueDependencies> {
+ let mut dependencies = collect_external_value_dependencies(value);
+ dependencies.inheritance_dependent =
+ crate::css::style_value::value_depends_on_current_color(value) || !value_is_computationally_independent(value)?;
+ Some(dependencies)
+}
+
pub(crate) fn external_value_dependencies(value: &StyleValueData) -> ExternalValueDependencies {
let mut dependencies = collect_external_value_dependencies(value);
dependencies.inheritance_dependent = crate::css::style_value::value_depends_on_current_color(value)
@@ -1866,16 +2059,16 @@ pub(crate) fn external_value_dependencies(value: &StyleValueData) -> ExternalVal
/// as an `element-shared` one is.
/// https://drafts.csswg.org/css-values-5/#random-caching
pub(crate) fn random_caching_key(sharing: &StyleValueData) -> (&[u16], bool) {
- let StyleValueData::RandomValueSharing {
+ let StyleValueData::RandomValueSharing(random_value_sharing_payload) = sharing else {
+ unreachable!("a random caching key is a random sharing's");
+ };
+ let RandomValueSharingPayload {
has_name,
name,
element_shared,
is_auto,
..
- } = sharing
- else {
- unreachable!("a random caching key is a random sharing's");
- };
+ } = &**random_value_sharing_payload;
(if *has_name { name.units() } else { &[] }, *element_shared || !*is_auto)
}
@@ -1904,48 +2097,67 @@ pub(crate) fn collect_unfixed_random_sharings_in_value(
}
};
match value {
- StyleValueData::Calculated { rust_calculation, .. } => {
+ StyleValueData::Calculated(calculated_payload) => {
+ let CalculatedPayload { rust_calculation, .. } = &**calculated_payload;
crate::css::calc::collect_unfixed_random_sharings(rust_calculation.node(), sharings);
}
- StyleValueData::RandomValueSharing { fixed_value, .. } => match fixed_value.optional_data() {
- Some(fixed_value) => collect_unfixed_random_sharings_in_value(fixed_value, sharings),
- None => {
- if !sharings.contains(&std::ptr::from_ref(value)) {
- sharings.push(value);
+ StyleValueData::RandomValueSharing(random_value_sharing_payload) => {
+ let RandomValueSharingPayload { fixed_value, .. } = &**random_value_sharing_payload;
+ match fixed_value.optional_data() {
+ Some(fixed_value) => collect_unfixed_random_sharings_in_value(fixed_value, sharings),
+ None => {
+ if !sharings.contains(&std::ptr::from_ref(value)) {
+ sharings.push(value);
+ }
}
}
- },
- StyleValueData::Ratio { numerator, denominator } => collect_values(&[numerator, denominator], sharings),
+ }
+ StyleValueData::Ratio(ratio_payload) => {
+ let RatioPayload { numerator, denominator } = &**ratio_payload;
+ collect_values(&[numerator, denominator], sharings);
+ }
StyleValueData::Edge { offset, .. } => collect_values(&[offset], sharings),
- StyleValueData::Ray { angle, position, .. } => collect_values(&[angle, position], sharings),
- StyleValueData::Function { value, .. }
- | StyleValueData::OpacityValue { value }
- | StyleValueData::Filter { value, .. }
- | StyleValueData::OpenTypeTagged { value, .. }
- | StyleValueData::GridTrackPlacement { value, .. } => collect_values(&[value], sharings),
- StyleValueData::ColorFunction {
- channel_0,
- channel_1,
- channel_2,
- alpha,
- origin_color,
- ..
- } => collect_values(&[channel_0, channel_1, channel_2, alpha, origin_color], sharings),
- StyleValueData::BorderImageSlice {
- top,
- right,
- bottom,
- left,
- ..
- }
- | StyleValueData::Rect {
- top,
- right,
- bottom,
- left,
- } => collect_values(&[top, right, bottom, left], sharings),
- StyleValueData::Content { content, alt_text } => collect_values(&[content, alt_text], sharings),
- StyleValueData::RadialSize { value_0, value_1, .. } => collect_values(&[value_0, value_1], sharings),
+ StyleValueData::Ray(ray_payload) => {
+ let RayPayload { angle, position, .. } = &**ray_payload;
+ collect_values(&[angle, position], sharings);
+ }
+ StyleValueData::Function(function) => collect_values(&[&function.value], sharings),
+ StyleValueData::OpenTypeTagged(open_type_tagged) => collect_values(&[&open_type_tagged.value], sharings),
+ StyleValueData::GridTrackPlacement(grid_track_placement) => {
+ collect_values(&[&grid_track_placement.value], sharings);
+ }
+ StyleValueData::OpacityValue { value } | StyleValueData::Filter { value, .. } => {
+ collect_values(&[value], sharings);
+ }
+ StyleValueData::ColorFunction(color_function_payload) => {
+ let ColorFunctionPayload {
+ channel_0,
+ channel_1,
+ channel_2,
+ alpha,
+ origin_color,
+ ..
+ } = &**color_function_payload;
+ collect_values(&[channel_0, channel_1, channel_2, alpha, origin_color], sharings);
+ }
+ StyleValueData::BorderImageSlice(border_image_slice) => collect_values(
+ &[
+ &border_image_slice.top,
+ &border_image_slice.right,
+ &border_image_slice.bottom,
+ &border_image_slice.left,
+ ],
+ sharings,
+ ),
+ StyleValueData::Rect(rect) => collect_values(&[&rect.top, &rect.right, &rect.bottom, &rect.left], sharings),
+ StyleValueData::Content(content_payload) => {
+ let ContentPayload { content, alt_text } = &**content_payload;
+ collect_values(&[content, alt_text], sharings);
+ }
+ StyleValueData::RadialSize(radial_size_payload) => {
+ let RadialSizePayload { value_0, value_1, .. } = &**radial_size_payload;
+ collect_values(&[value_0, value_1], sharings);
+ }
StyleValueData::BasicShape { shape } => {
let BasicShapeData {
v0,
@@ -1961,120 +2173,154 @@ pub(crate) fn collect_unfixed_random_sharings_in_value(
collect_values(&point.values(), sharings);
}
}
- StyleValueData::Counter { counter_style, .. } => collect_values(&[counter_style], sharings),
- StyleValueData::Cursor { image, x, y } => collect_values(&[image, x, y], sharings),
- StyleValueData::Easing {
- linear_stops,
- x1,
- y1,
- x2,
- y2,
- number_of_intervals,
- ..
- } => {
+ StyleValueData::Counter(counter_payload) => {
+ let CounterPayload { counter_style, .. } = &**counter_payload;
+ collect_values(&[counter_style], sharings);
+ }
+ StyleValueData::Cursor(cursor_payload) => {
+ let CursorPayload { image, x, y } = &**cursor_payload;
+ collect_values(&[image, x, y], sharings);
+ }
+ StyleValueData::Easing(easing_payload) => {
+ let EasingPayload {
+ linear_stops,
+ x1,
+ y1,
+ x2,
+ y2,
+ number_of_intervals,
+ ..
+ } = &**easing_payload;
collect_values(&[x1, y1, x2, y2, number_of_intervals], sharings);
for stop in linear_stops.as_slice() {
collect_values(&stop.values(), sharings);
}
}
- StyleValueData::ImageSet { options } => {
+ StyleValueData::ImageSet(image_set_payload) => {
+ let ImageSetPayload { options } = &**image_set_payload;
for option in options.as_slice() {
collect_values(&option.values(), sharings);
}
}
- StyleValueData::CounterDefinitions { counter_definitions } => {
+ StyleValueData::CounterDefinitions(counter_definitions_payload) => {
+ let CounterDefinitionsPayload { counter_definitions } = &**counter_definitions_payload;
for definition in counter_definitions.as_slice() {
collect_optional(definition.value(), sharings);
}
}
- StyleValueData::LinearGradient {
- direction_value,
- color_stop_list,
- color_interpolation_method,
- ..
- } => {
+ StyleValueData::LinearGradient(linear_gradient_payload) => {
+ let LinearGradientPayload {
+ direction_value,
+ color_stop_list,
+ color_interpolation_method,
+ ..
+ } = &**linear_gradient_payload;
collect_values(&[direction_value, color_interpolation_method], sharings);
for stop in color_stop_list.as_slice() {
collect_values(&stop.values(), sharings);
}
}
- StyleValueData::ConicGradient {
- from_angle,
- position,
- color_stop_list,
- color_interpolation_method,
- ..
- } => {
+ StyleValueData::ConicGradient(conic_gradient_payload) => {
+ let ConicGradientPayload {
+ from_angle,
+ position,
+ color_stop_list,
+ color_interpolation_method,
+ ..
+ } = &**conic_gradient_payload;
collect_values(&[from_angle, position, color_interpolation_method], sharings);
for stop in color_stop_list.as_slice() {
collect_values(&stop.values(), sharings);
}
}
- StyleValueData::RadialGradient {
- size,
- position,
- color_stop_list,
- color_interpolation_method,
- ..
- } => {
+ StyleValueData::RadialGradient(radial_gradient_payload) => {
+ let RadialGradientPayload {
+ size,
+ position,
+ color_stop_list,
+ color_interpolation_method,
+ ..
+ } = &**radial_gradient_payload;
collect_values(&[size, position, color_interpolation_method], sharings);
for stop in color_stop_list.as_slice() {
collect_values(&stop.values(), sharings);
}
}
- StyleValueData::ColorMix {
- color_interpolation_method,
- colors,
- percentages,
- ..
- } => {
+ StyleValueData::ColorMix(color_mix_payload) => {
+ let ColorMixPayload {
+ color_interpolation_method,
+ colors,
+ percentages,
+ ..
+ } = &**color_mix_payload;
collect_values(&[color_interpolation_method], sharings);
collect_values(&colors.as_slice().iter().collect::<Vec<_>>(), sharings);
collect_values(&percentages.as_slice().iter().collect::<Vec<_>>(), sharings);
}
StyleValueData::ContrastColor { color, .. } => collect_values(&[color], sharings),
- StyleValueData::LightDark { light, dark, .. } => collect_values(&[light, dark], sharings),
+ StyleValueData::LightDark(light_dark_payload) => {
+ let LightDarkPayload { light, dark, .. } = &**light_dark_payload;
+ collect_values(&[light, dark], sharings);
+ }
StyleValueData::Superellipse { parameter } => collect_values(&[parameter], sharings),
- StyleValueData::ScrollbarColor {
- thumb_color,
- track_color,
- } => collect_values(&[thumb_color, track_color], sharings),
+ StyleValueData::ScrollbarColor(scrollbar_color_payload) => {
+ let ScrollbarColorPayload {
+ thumb_color,
+ track_color,
+ } = &**scrollbar_color_payload;
+ collect_values(&[thumb_color, track_color], sharings);
+ }
StyleValueData::FontStyle { angle_value, .. } => collect_values(&[angle_value], sharings),
StyleValueData::TextIndent { length_percentage, .. } => collect_values(&[length_percentage], sharings),
StyleValueData::OverflowClipMargin { offset, .. } => collect_values(&[offset], sharings),
- StyleValueData::BackgroundSize { size_x, size_y } => collect_values(&[size_x, size_y], sharings),
- StyleValueData::Position { edge_x, edge_y } => collect_values(&[edge_x, edge_y], sharings),
- StyleValueData::Shadow {
- color,
- offset_x,
- offset_y,
- blur_radius,
- spread_distance,
- ..
- } => collect_values(&[color, offset_x, offset_y, blur_radius, spread_distance], sharings),
- StyleValueData::Shorthand { values, .. }
- | StyleValueData::ValueList { values, .. }
- | StyleValueData::Tuple { values }
- | StyleValueData::Transformation { values, .. } => collect_list(values, sharings),
- StyleValueData::BorderRadiusRect {
- top_left,
- top_right,
- bottom_right,
- bottom_left,
- } => collect_values(&[top_left, top_right, bottom_right, bottom_left], sharings),
- StyleValueData::BorderRadius {
- horizontal_radius,
- vertical_radius,
- ..
- } => collect_values(&[horizontal_radius, vertical_radius], sharings),
- _ => {}
- }
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_style_value_is_computationally_independent(data: &StyleValueData) -> bool {
- value_is_computationally_independent(data).expect("computational independence requested for an unsupported value")
-}
+ StyleValueData::BackgroundSize(background_size_payload) => {
+ let BackgroundSizePayload { size_x, size_y } = &**background_size_payload;
+ collect_values(&[size_x, size_y], sharings);
+ }
+ StyleValueData::Position(position_payload) => {
+ let PositionPayload { edge_x, edge_y } = &**position_payload;
+ collect_values(&[edge_x, edge_y], sharings);
+ }
+ StyleValueData::Shadow(shadow_payload) => {
+ let ShadowPayload {
+ color,
+ offset_x,
+ offset_y,
+ blur_radius,
+ spread_distance,
+ ..
+ } = &**shadow_payload;
+ collect_values(&[color, offset_x, offset_y, blur_radius, spread_distance], sharings);
+ }
+ StyleValueData::Shorthand(_)
+ | StyleValueData::ValueList { .. }
+ | StyleValueData::Tuple { .. }
+ | StyleValueData::Transformation(_) => collect_list(value.child_values().unwrap(), sharings),
+ StyleValueData::BorderRadiusRect(border_radius_rect_payload) => {
+ let BorderRadiusRectPayload {
+ top_left,
+ top_right,
+ bottom_right,
+ bottom_left,
+ } = &**border_radius_rect_payload;
+ collect_values(&[top_left, top_right, bottom_right, bottom_left], sharings);
+ }
+ StyleValueData::BorderRadius(border_radius_payload) => {
+ let BorderRadiusPayload {
+ horizontal_radius,
+ vertical_radius,
+ ..
+ } = &**border_radius_payload;
+ collect_values(&[horizontal_radius, vertical_radius], sharings);
+ }
+ _ => {}
+ }
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_style_value_is_computationally_independent(data: &StyleValueData) -> bool {
+ value_is_computationally_independent(data).expect("computational independence requested for an unsupported value")
+}
// The computed value of the math-depth value is determined as follows:
fn compute_math_depth(
@@ -2107,7 +2353,8 @@ fn compute_math_depth(
}
// - If the specified value of math-depth is of the form add(<integer>) then the computed
// value of math-depth of the element is its inherited value plus the specified integer.
- StyleValueData::Function { value, .. } => {
+ StyleValueData::Function(function_payload) => {
+ let FunctionPayload { value, .. } = &**function_payload;
let Some(value) = value.optional_data() else {
return NUMBER_UNHANDLED;
};
@@ -2129,25 +2376,25 @@ fn compute_math_depth(
}
// https://drafts.csswg.org/css-inline-3/#line-height-property
-fn compute_line_height(value: &StyleValueData, computed_font_size: CssPixels) -> FfiComputedLineHeight {
+fn compute_line_height(value: &StyleValueData, computed_font_size: CssPixels) -> ComputedLineHeight {
match value {
// normal
// <length [0,inf]>
// <number [0,inf]>
- StyleValueData::Keyword { keyword } if *keyword == keyword::NORMAL => FfiComputedLineHeight {
+ StyleValueData::Keyword { keyword } if *keyword == keyword::NORMAL => ComputedLineHeight {
handled: true,
unchanged: true,
is_number: false,
value: 0.0,
},
- StyleValueData::Length { .. } | StyleValueData::Number { .. } => FfiComputedLineHeight {
+ StyleValueData::Length { .. } | StyleValueData::Number { .. } => ComputedLineHeight {
handled: true,
unchanged: true,
is_number: false,
value: 0.0,
},
// <percentage [0,inf]>
- StyleValueData::Percentage { value } => FfiComputedLineHeight {
+ StyleValueData::Percentage { value } => ComputedLineHeight {
handled: true,
unchanged: false,
is_number: false,
@@ -2161,13 +2408,13 @@ fn compute_line_height(value: &StyleValueData, computed_font_size: CssPixels) ->
value,
computed_font_size.to_double(),
) {
- Some(crate::css::calc::ResolvedLineHeightCalc::Px(px)) => FfiComputedLineHeight {
+ Some(crate::css::calc::ResolvedLineHeightCalc::Px(px)) => ComputedLineHeight {
handled: true,
unchanged: false,
is_number: false,
value: px,
},
- Some(crate::css::calc::ResolvedLineHeightCalc::Number(number)) => FfiComputedLineHeight {
+ Some(crate::css::calc::ResolvedLineHeightCalc::Number(number)) => ComputedLineHeight {
handled: true,
unchanged: false,
is_number: true,
@@ -2306,7 +2553,7 @@ pub(crate) fn font_family_is_monospace(value: &StyleValueData) -> bool {
/// the survivors ascending by tag.
/// https://drafts.csswg.org/css-fonts/#font-feature-settings-prop
#[allow(clippy::arc_with_non_send_sync)]
-fn compute_font_feature_tag_value_list(value: &StyleValueData) -> Arc<StyleValueData> {
+fn compute_font_feature_tag_value_list(value: &StyleValueData) -> StyleValueArc {
let StyleValueData::ValueList {
values,
separator,
@@ -2317,7 +2564,10 @@ fn compute_font_feature_tag_value_list(value: &StyleValueData) -> Arc<StyleValue
};
let values = values.as_slice();
let packed_tag = |index: usize| match values[index].data() {
- StyleValueData::OpenTypeTagged { packed_tag, .. } => *packed_tag,
+ StyleValueData::OpenTypeTagged(open_type_tagged_payload) => {
+ let OpenTypeTaggedPayload { packed_tag, .. } = &**open_type_tagged_payload;
+ *packed_tag
+ }
_ => unreachable!("font feature settings must contain OpenType tagged values"),
};
@@ -2330,7 +2580,7 @@ fn compute_font_feature_tag_value_list(value: &StyleValueData) -> Arc<StyleValue
.into_iter()
.map(|index| values[index].clone_retained())
.collect();
- Arc::new(StyleValueData::ValueList {
+ StyleValueArc::new(StyleValueData::ValueList {
values: RetainedStyleValueDataList::from_retained_values(values),
separator: *separator,
collapsible: *collapsible,
@@ -2342,7 +2592,10 @@ fn compute_font_feature_tag_value_list(value: &StyleValueData) -> Arc<StyleValue
fn value_contains_percentage(value: &StyleValueData) -> bool {
match value {
StyleValueData::Percentage { .. } => true,
- StyleValueData::Calculated { rust_calculation, .. } => rust_calculation.node().contains_percentage(),
+ StyleValueData::Calculated(calculated_payload) => {
+ let CalculatedPayload { rust_calculation, .. } = &**calculated_payload;
+ rust_calculation.node().contains_percentage()
+ }
_ => false,
}
}
@@ -2467,7 +2720,7 @@ fn position_area_span_all_remap(block_keyword: u16, inline_keyword: u16) -> Opti
// https://drafts.csswg.org/css-anchor-position/#position-area-computed
#[allow(clippy::arc_with_non_send_sync)]
-fn compute_position_area(value: &StyleValueData) -> Option<Arc<StyleValueData>> {
+fn compute_position_area(value: &StyleValueData) -> Option<StyleValueArc> {
// The computed value of a <position-area> value is the two keywords indicating the selected tracks in each axis,
// with the long (block-start) and short (start) logical keywords treated as equivalent. It serializes in the order
// given in the grammar (above), with the logical keywords serialized in their short forms (e.g. start start
@@ -2494,7 +2747,7 @@ fn compute_position_area(value: &StyleValueData) -> Option<Arc<StyleValueData>>
};
if let Some(keyword) = position_area_span_all_remap(*block_keyword, *inline_keyword) {
- return Some(Arc::new(StyleValueData::Keyword { keyword }));
+ return Some(StyleValueArc::new(StyleValueData::Keyword { keyword }));
}
let short_block_keyword = position_area_short_keyword(*block_keyword);
let short_inline_keyword = position_area_short_keyword(*inline_keyword);
@@ -2502,8 +2755,9 @@ fn compute_position_area(value: &StyleValueData) -> Option<Arc<StyleValueData>>
return None;
}
- let retained_keyword = |keyword| RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Keyword { keyword }));
- Some(Arc::new(StyleValueData::ValueList {
+ let retained_keyword =
+ |keyword| RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Keyword { keyword }));
+ Some(StyleValueArc::new(StyleValueData::ValueList {
values: RetainedStyleValueDataList::from_retained_values(vec![
retained_keyword(short_block_keyword),
retained_keyword(short_inline_keyword),
@@ -2516,7 +2770,7 @@ fn compute_position_area(value: &StyleValueData) -> Option<Arc<StyleValueData>>
/// The computed dash list, with each number converted to the length it measures in user units.
/// None when the list holds no numbers, so an unchanged list keeps its identity.
#[allow(clippy::arc_with_non_send_sync)]
-fn stroke_dasharray_numbers_as_lengths(value: &StyleValueData) -> Option<Arc<StyleValueData>> {
+fn stroke_dasharray_numbers_as_lengths(value: &StyleValueData) -> Option<StyleValueArc> {
let StyleValueData::ValueList {
values,
separator,
@@ -2535,14 +2789,16 @@ fn stroke_dasharray_numbers_as_lengths(value: &StyleValueData) -> Option<Arc<Sty
let computed_dashes = dashes
.iter()
.map(|dash| match dash.data() {
- StyleValueData::Number { value } => RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Length {
- value: *value,
- unit: px_length_unit(),
- })),
+ StyleValueData::Number { value } => {
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Length {
+ value: *value,
+ unit: px_length_unit(),
+ }))
+ }
_ => dash.clone_retained(),
})
.collect();
- Some(Arc::new(StyleValueData::ValueList {
+ Some(StyleValueArc::new(StyleValueData::ValueList {
values: RetainedStyleValueDataList::from_retained_values(computed_dashes),
separator: *separator,
collapsible: *collapsible,
@@ -2551,9 +2807,9 @@ fn stroke_dasharray_numbers_as_lengths(value: &StyleValueData) -> Option<Arc<Sty
/// The computed two-value list for a `border-spacing` member used for both axes.
#[allow(clippy::arc_with_non_send_sync)]
-fn border_spacing_pair(single: StyleValueData) -> Arc<StyleValueData> {
- let single = RetainedStyleValueData::from_arc(Arc::new(single));
- Arc::new(StyleValueData::ValueList {
+fn border_spacing_pair(single: StyleValueData) -> StyleValueArc {
+ let single = RetainedStyleValueData::from_arc(StyleValueArc::new(single));
+ StyleValueArc::new(StyleValueData::ValueList {
values: RetainedStyleValueDataList::from_retained_values(vec![single.clone_retained(), single]),
separator: 0,
collapsible: true,
@@ -2564,7 +2820,7 @@ fn border_spacing_pair(single: StyleValueData) -> Arc<StyleValueData> {
/// The computed value of a border-shape leaves out the reference boxes that are the defaults, and keeps one of two
/// shapes that are the same against the same box. Returns `None` when the value is already canonical.
#[allow(clippy::arc_with_non_send_sync)]
-fn canonicalize_border_shape(value: &StyleValueData) -> Option<Arc<StyleValueData>> {
+fn canonicalize_border_shape(value: &StyleValueData) -> Option<StyleValueArc> {
let StyleValueData::ValueList { values, .. } = value else {
return None;
};
@@ -2601,9 +2857,9 @@ fn canonicalize_border_shape(value: &StyleValueData) -> Option<Arc<StyleValueDat
return None;
}
if let [only] = &canonical[..] {
- return Some(Arc::new(only.data().clone()));
+ return Some(StyleValueArc::new(only.data().clone()));
}
- Some(Arc::new(StyleValueData::ValueList {
+ Some(StyleValueArc::new(StyleValueData::ValueList {
values: RetainedStyleValueDataList::from_retained_values(canonical),
separator: 0,
collapsible: false,
@@ -2614,7 +2870,7 @@ fn canonicalize_border_shape(value: &StyleValueData) -> Option<Arc<StyleValueDat
/// A computed range edge leaves out the progress after a range name when it is the default for the edge: 0% for a
/// start, 100% for an end. Returns `None` when the value is already canonical.
#[allow(clippy::arc_with_non_send_sync)]
-fn canonicalize_animation_range(value: &StyleValueData, default_offset: f64) -> Option<Arc<StyleValueData>> {
+fn canonicalize_animation_range(value: &StyleValueData, default_offset: f64) -> Option<StyleValueArc> {
// A calculation that resolves to the default percentage, with no length part, is left out too.
let is_percentage_of = |offset: &StyleValueData, percentage: f64| match offset {
StyleValueData::Percentage { value } => *value == percentage,
@@ -2642,7 +2898,7 @@ fn canonicalize_animation_range(value: &StyleValueData, default_offset: f64) ->
};
// A list of edges is comma separated; a lone edge with a range name and an offset is a space separated pair.
if *separator == 0 {
- return canonical_edge(value).map(|edge| Arc::new(edge.data().clone()));
+ return canonical_edge(value).map(|edge| StyleValueArc::new(edge.data().clone()));
}
let mut changed = false;
let edges = values
@@ -2657,7 +2913,7 @@ fn canonicalize_animation_range(value: &StyleValueData, default_offset: f64) ->
})
.collect();
changed.then(|| {
- Arc::new(StyleValueData::ValueList {
+ StyleValueArc::new(StyleValueData::ValueList {
values: RetainedStyleValueDataList::from_retained_values(edges),
separator: *separator,
collapsible: *collapsible,
@@ -2669,7 +2925,7 @@ fn canonicalize_animation_range(value: &StyleValueData, default_offset: f64) ->
/// Computed value: computed <angle> value, optionally preceded by auto
/// Returns `None` when the value is already canonical.
#[allow(clippy::arc_with_non_send_sync)]
-fn canonicalize_offset_rotate(value: &StyleValueData) -> Option<Arc<StyleValueData>> {
+fn canonicalize_offset_rotate(value: &StyleValueData) -> Option<StyleValueArc> {
// NB: The C++ AngleUnit for degrees.
const DEGREES: u8 = 0;
let degrees = match value {
@@ -2695,7 +2951,7 @@ fn canonicalize_offset_rotate(value: &StyleValueData) -> Option<Arc<StyleValueDa
_ => return None,
};
// reverse <angle>?: Identical to auto, but adds an additional 180deg to the rotation.
- Some(Arc::new(StyleValueData::ValueList {
+ Some(StyleValueArc::new(StyleValueData::ValueList {
values: RetainedStyleValueDataList::from_retained_values(vec![
retained_new(StyleValueData::Keyword { keyword: keyword::AUTO }),
retained_new(StyleValueData::Angle {
@@ -2710,7 +2966,7 @@ fn canonicalize_offset_rotate(value: &StyleValueData) -> Option<Arc<StyleValueDa
// https://drafts.csswg.org/css-contain-2/#contain-property
#[allow(clippy::arc_with_non_send_sync)]
-fn collapse_containment_list(value: &StyleValueData) -> Option<Arc<StyleValueData>> {
+fn collapse_containment_list(value: &StyleValueData) -> Option<StyleValueArc> {
let StyleValueData::ValueList { values, .. } = value else {
return None;
};
@@ -2739,7 +2995,7 @@ fn collapse_containment_list(value: &StyleValueData) -> Option<Arc<StyleValueDat
} else {
keyword::CONTENT
};
- Some(Arc::new(StyleValueData::Keyword {
+ Some(StyleValueArc::new(StyleValueData::Keyword {
keyword: collapsed_keyword,
}))
}
@@ -2813,16 +3069,14 @@ pub(crate) fn keyword_is_color(keyword: u16) -> bool {
/// The inherit-or-initial decision for one longhand in the property
/// computation loop.
-#[repr(C)]
-pub struct FfiLonghandDecision {
+pub struct LonghandDecision {
pub should_inherit: bool,
- pub explicitly_inherits_non_inherited_property: bool,
/// True when, absent a successful inheritance fetch, the value falls back
/// to the property's initial value.
pub use_initial_without_inherit: bool,
}
-fn longhand_decision(value: Option<&StyleValueData>, property_id: u16) -> FfiLonghandDecision {
+fn longhand_decision(value: Option<&StyleValueData>, property_id: u16) -> LonghandDecision {
let keyword = match value {
Some(StyleValueData::Keyword { keyword }) => Some(*keyword),
_ => None,
@@ -2832,7 +3086,6 @@ fn longhand_decision(value: Option<&StyleValueData>, property_id: u16) -> FfiLon
let is_initial = keyword == Some(keyword::INITIAL);
let inherited_property = property_is_inherited(property_id);
- let explicitly_inherits_non_inherited_property = is_inherit && !inherited_property;
let mut should_inherit = value.is_none() && inherited_property;
// https://www.w3.org/TR/css-cascade-4/#inherit
@@ -2850,9 +3103,8 @@ fn longhand_decision(value: Option<&StyleValueData>, property_id: u16) -> FfiLon
should_inherit |=
property_id == crate::css::property_metadata::property_id::COLOR && keyword == Some(keyword::CURRENTCOLOR);
- FfiLonghandDecision {
+ LonghandDecision {
should_inherit,
- explicitly_inherits_non_inherited_property,
use_initial_without_inherit: value.is_none() || is_initial || is_unset || should_inherit,
}
}
@@ -2922,10 +3174,6 @@ struct ComputedStoreEntry<'a> {
/// The selected specified value; also the stored value when
/// `computed_kind` is `COMPUTED_KIND_UNCHANGED`.
data: &'a RetainedStyleValueData,
- /// The C++ declaration-source slot for a cascaded value, or -1.
- source_slot: i64,
- /// Whether the selected cascaded facade carried stylesheet context.
- has_style_sheet_context: bool,
inheritance_dependent: bool,
/// The replacement style value when `computed_kind` is
/// `COMPUTED_KIND_STYLE_VALUE`.
@@ -3130,7 +3378,10 @@ pub(crate) fn value_absolutization_is_identity(value: &StyleValueData) -> bool {
| StyleValueData::Percentage { .. }
| StyleValueData::Flex { .. }
| StyleValueData::UnicodeRange { .. } => true,
- StyleValueData::Url { url, .. } => url.is_empty() || url.is_fragment(),
+ StyleValueData::Url(url_payload) => {
+ let UrlPayload { url, .. } = &**url_payload;
+ url.is_empty() || url.is_fragment()
+ }
_ => false,
}
}
@@ -3180,7 +3431,7 @@ fn property_has_dedicated_compute_rule(property_id: u16) -> bool {
/// rejects non-list or empty values, while the inner option preserves the
/// original allocation when its length already matches.
#[allow(clippy::arc_with_non_send_sync)]
-fn repeat_style_value_list_to_n_elements(value: &StyleValueData, count: usize) -> Option<Option<Arc<StyleValueData>>> {
+fn repeat_style_value_list_to_n_elements(value: &StyleValueData, count: usize) -> Option<Option<StyleValueArc>> {
let StyleValueData::ValueList { values, separator, .. } = value else {
return None;
};
@@ -3194,7 +3445,7 @@ fn repeat_style_value_list_to_n_elements(value: &StyleValueData, count: usize) -
let repeated_values = (0..count)
.map(|index| values[index % values.len()].clone_retained())
.collect();
- Some(Some(Arc::new(StyleValueData::ValueList {
+ Some(Some(StyleValueArc::new(StyleValueData::ValueList {
values: RetainedStyleValueDataList::from_retained_values(repeated_values),
separator: *separator,
collapsible: true,
@@ -3204,7 +3455,7 @@ fn repeat_style_value_list_to_n_elements(value: &StyleValueData, count: usize) -
/// https://drafts.csswg.org/css-animations-1/#animation-name
/// list, each item either a case-sensitive css identifier or the keyword none
#[allow(clippy::arc_with_non_send_sync)]
-fn compute_animation_name(value: &StyleValueData) -> Option<Arc<StyleValueData>> {
+fn compute_animation_name(value: &StyleValueData) -> Option<StyleValueArc> {
let StyleValueData::ValueList { values, .. } = value else {
return None;
};
@@ -3221,7 +3472,7 @@ fn compute_animation_name(value: &StyleValueData) -> Option<Arc<StyleValueData>>
is_valid_animation_name_custom_ident,
..
} => Some(if *is_valid_animation_name_custom_ident {
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::CustomIdent {
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::CustomIdent {
custom_ident: string.clone(),
}))
} else {
@@ -3230,7 +3481,7 @@ fn compute_animation_name(value: &StyleValueData) -> Option<Arc<StyleValueData>>
_ => None,
})
.collect::<Option<Vec<_>>>()?;
- Some(Arc::new(StyleValueData::ValueList {
+ Some(StyleValueArc::new(StyleValueData::ValueList {
values: RetainedStyleValueDataList::from_retained_values(computed_entries),
separator: 1,
collapsible: true,
@@ -3241,7 +3492,7 @@ fn compute_animation_name(value: &StyleValueData) -> Option<Arc<StyleValueData>>
/// top and left compute to 0%, center computes to 50%, and bottom and right
/// compute to 100%. A None return means the value is already computed.
#[allow(clippy::arc_with_non_send_sync)]
-fn compute_transform_origin(value: &StyleValueData) -> Option<Arc<StyleValueData>> {
+fn compute_transform_origin(value: &StyleValueData) -> Option<StyleValueArc> {
let StyleValueData::ValueList {
values,
separator,
@@ -3267,12 +3518,12 @@ fn compute_transform_origin(value: &StyleValueData) -> Option<Arc<StyleValueData
.iter()
.map(|offset| match offset_percentage(offset) {
Some(percentage) => {
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Percentage { value: percentage }))
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Percentage { value: percentage }))
}
None => offset.clone_retained(),
})
.collect();
- Some(Arc::new(StyleValueData::ValueList {
+ Some(StyleValueArc::new(StyleValueData::ValueList {
values: RetainedStyleValueDataList::from_retained_values(computed_offsets),
separator: *separator,
collapsible: *collapsible,
@@ -3280,7 +3531,7 @@ fn compute_transform_origin(value: &StyleValueData) -> Option<Arc<StyleValueData
}
pub(crate) struct ParentSnapshot<'a> {
- table: &'a ComputedLonghandTable,
+ longhands: crate::css::style::ViewLonghands<'a>,
inherited_value_overlay: Option<&'a AnimatedOverlay>,
stored_animated_overlay: Option<&'a AnimatedOverlay>,
font_metrics_depend_on_viewport_metrics: bool,
@@ -3289,24 +3540,24 @@ pub(crate) struct ParentSnapshot<'a> {
}
impl<'a> ParentSnapshot<'a> {
- /// A snapshot over a record's parts, for a caller holding the record view itself. What the
- /// record's animations sampled is what a child inherits.
- pub(crate) fn new(
- table: &'a ComputedLonghandTable,
+ /// A snapshot over a record view's longhands, for a caller holding the record view itself.
+ /// What the record's animations sampled is what a child inherits.
+ pub(crate) fn from_view(
+ longhands: crate::css::style::ViewLonghands<'a>,
stored_animated_overlay: Option<&'a AnimatedOverlay>,
font_metrics_depend_on_viewport_metrics: bool,
) -> Self {
Self {
- table,
+ longhands,
inherited_value_overlay: stored_animated_overlay,
stored_animated_overlay,
font_metrics_depend_on_viewport_metrics,
- highlight_colors_authored: table.dependency_flags() & HIGHLIGHT_COLORS_AUTHORED != 0,
- highlight_color_is_current_color: table.dependency_flags() & HIGHLIGHT_COLOR_IS_CURRENT_COLOR != 0,
+ highlight_colors_authored: longhands.dependency_flags() & HIGHLIGHT_COLORS_AUTHORED != 0,
+ highlight_color_is_current_color: longhands.dependency_flags() & HIGHLIGHT_COLOR_IS_CURRENT_COLOR != 0,
}
}
fn is_important(&self, property_id: u16) -> bool {
- self.table.is_important(property_id)
+ self.longhands.is_important(property_id)
}
fn value(&self, property_id: u16) -> Option<&StyleValueData> {
@@ -3326,7 +3577,7 @@ impl<'a> ParentSnapshot<'a> {
// color, except in the color property, whose currentcolor is the inherited value and so resolved where
// it computes.
if property_id != crate::css::property_metadata::property_id::COLOR {
- for (property, value) in self.table.retained_inheritance_dependent_values() {
+ for (property, value) in self.longhands.inheritance_dependent_values() {
if property == property_id
&& crate::css::style_value::style_value_dependency_flags(value.data()) & 1 != 0
{
@@ -3334,23 +3585,19 @@ impl<'a> ParentSnapshot<'a> {
}
}
}
- self.table.get(property_id)
+ self.longhands.handle(property_id)
}
}
-pub(crate) fn parent_snapshot_for_style_record<'a>(
- style_engine: &'a crate::css::style::RetainedState,
- style_record: u64,
+/// What an element inheriting from the record `view` views reads of it, with `animated_overlay`
+/// the values it inherits beyond the record's.
+pub(crate) fn parent_snapshot_of_view<'a>(
+ view: crate::css::style::StyleRecordView<'a>,
animated_overlay: Option<&'a AnimatedOverlay>,
) -> ParentSnapshot<'a> {
- let view = style_engine
- .style_record_view(style_record)
- .expect("the inheritance parent style record must remain live during computation");
- let table = view
- .longhand_table
- .expect("the inheritance parent style record must carry a longhand table");
+ let longhands = view.longhands();
ParentSnapshot {
- table,
+ longhands,
inherited_value_overlay: animated_overlay,
stored_animated_overlay: view.animated_overlay,
font_metrics_depend_on_viewport_metrics: view.dependency_flags & (1 << 1) != 0,
@@ -3367,28 +3614,22 @@ pub(crate) struct HighlightInheritance<'a> {
pub(crate) snapshot: Option<ParentSnapshot<'a>>,
}
-fn keyframe_parent_snapshot_for_style_record(
- style_engine: &crate::css::style::StyleEngine,
- style_record: u64,
+fn keyframe_parent_snapshot_of_record(
+ record: &std::sync::Arc<crate::css::style::pipeline::Record>,
) -> ParentSnapshot<'_> {
- let mut snapshot = parent_snapshot_for_style_record(style_engine, style_record, None);
+ let mut snapshot = parent_snapshot_of_view(crate::css::style::StyleRecordView::of_host_record(record), None);
snapshot.inherited_value_overlay = snapshot.stored_animated_overlay;
snapshot
}
/// Results of one longhand drive that remain outside the Rust longhand table.
-#[repr(C)]
#[derive(Clone)]
-pub struct FfiLonghandDriverResults {
+pub struct LonghandDriverResults {
/// Longhands whose specified-to-computed evaluation ran in this drive.
pub longhand_evaluations: u32,
pub depends_on_viewport_metrics: bool,
pub font_metrics_depend_on_viewport_metrics: bool,
- /// Groups containing non-inherited properties explicitly inherited from
- /// the parent. `u32::MAX` means the owning group is unknown.
- pub explicitly_inherited_non_inherited_style_groups: u32,
pub uses_tree_counting_function: bool,
- pub post_adjusted_longhands: u8,
/// https://drafts.csswg.org/css-pseudo-4/#paired-defaults
pub highlight_colors_authored: bool,
/// https://drafts.csswg.org/css-pseudo-4/#highlight-text
@@ -3399,39 +3640,33 @@ pub struct FfiLonghandDriverResults {
struct PostComputeAdjustment {
display_before: FfiDisplay,
box_type_transformation: FfiBoxTypeTransformation,
- element_style_adjustment: FfiElementStyleAdjustment,
+ element_style_adjustment: ElementStyleAdjustment,
}
-pub(crate) fn empty_longhand_driver_results() -> FfiLonghandDriverResults {
- FfiLonghandDriverResults {
+pub(crate) fn empty_longhand_driver_results() -> LonghandDriverResults {
+ LonghandDriverResults {
longhand_evaluations: 0,
depends_on_viewport_metrics: false,
font_metrics_depend_on_viewport_metrics: false,
- explicitly_inherited_non_inherited_style_groups: 0,
uses_tree_counting_function: false,
- post_adjusted_longhands: 0,
highlight_colors_authored: false,
highlight_color_is_current_color: false,
}
}
-pub const POST_ADJUSTED_FLOAT: u8 = 1 << 0;
-pub const POST_ADJUSTED_DISPLAY: u8 = 1 << 1;
-pub const POST_ADJUSTED_LINE_HEIGHT: u8 = 1 << 2;
-pub const POST_ADJUSTED_POSITION: u8 = 1 << 3;
-pub const POST_ADJUSTED_TEXT_ALIGN: u8 = 1 << 4;
-
pub const LONGHAND_DRIVE_PHASE_FONT: u8 = 0;
pub const LONGHAND_DRIVE_PHASE_LINE_HEIGHT: u8 = 1;
pub const LONGHAND_DRIVE_PHASE_COLOR_SCHEME: u8 = 2;
pub const LONGHAND_DRIVE_PHASE_REMAINING: u8 = 3;
-pub(crate) fn property_computation_order_for_phase(phase: u8) -> &'static [u16] {
+/// The positions of line-height and color-scheme in the property computation order, which split it
+/// into the font, line-height, color-scheme and remaining phases.
+fn property_computation_phase_boundaries() -> (usize, usize) {
use crate::css::property_metadata::{property_computation_order, property_id as prop};
static PHASE_BOUNDARIES: OnceLock<(usize, usize)> = OnceLock::new();
let order = property_computation_order();
- let &(line_height, color_scheme) = PHASE_BOUNDARIES.get_or_init(|| {
+ *PHASE_BOUNDARIES.get_or_init(|| {
let line_height = order
.iter()
.position(|&property_id| property_id == prop::LINE_HEIGHT)
@@ -3442,7 +3677,14 @@ pub(crate) fn property_computation_order_for_phase(phase: u8) -> &'static [u16]
.expect("color-scheme must be in the property computation order");
assert_eq!(color_scheme, line_height + 1);
(line_height, color_scheme)
- });
+ })
+}
+
+pub(crate) fn property_computation_order_for_phase(phase: u8) -> &'static [u16] {
+ use crate::css::property_metadata::{property_computation_order, property_id as prop};
+
+ let order = property_computation_order();
+ let (line_height, color_scheme) = property_computation_phase_boundaries();
match phase {
LONGHAND_DRIVE_PHASE_FONT => {
// NB: Font sizes can use logical viewport units, so their subject's writing mode must be computed first.
@@ -3473,6 +3715,66 @@ pub(crate) fn property_computation_order_for_phase(phase: u8) -> &'static [u16]
}
}
+/// The longhands a partial drive evaluates in one phase: the selected ones, the inputs every drive
+/// evaluates, and the background layer longhands when background-image is selected, in computation
+/// order. A partial drive selects few longhands, so this is much shorter than the phase's order.
+fn partial_drive_phase_order(phase: u8, words: &[u64], background_image_is_selected: bool) -> SmallVec<[u16; 48]> {
+ use crate::css::property_metadata::{
+ FIRST_LONGHAND_PROPERTY_ID, NUMBER_OF_LONGHAND_PROPERTIES, property_id as prop,
+ };
+
+ static RANKS: OnceLock<Box<[u16]>> = OnceLock::new();
+ let ranks = RANKS.get_or_init(|| {
+ let mut ranks = vec![u16::MAX; NUMBER_OF_LONGHAND_PROPERTIES].into_boxed_slice();
+ for (rank, &property_id) in crate::css::property_metadata::property_computation_order()
+ .iter()
+ .enumerate()
+ {
+ ranks[usize::from(property_id - FIRST_LONGHAND_PROPERTY_ID)] = u16::try_from(rank).unwrap();
+ }
+ ranks
+ });
+ let rank_of = |property_id: u16| ranks[usize::from(property_id - FIRST_LONGHAND_PROPERTY_ID)];
+ // NB: The font and remaining phases compute writing-mode first (see
+ // property_computation_order_for_phase()), so it belongs to them in addition to its own rank.
+ let (line_height, color_scheme) = property_computation_phase_boundaries();
+ let (line_height, color_scheme) = (line_height as u16, color_scheme as u16);
+ let (phase_ranks, phase_computes_writing_mode_first) = match phase {
+ LONGHAND_DRIVE_PHASE_FONT => (0..line_height, true),
+ LONGHAND_DRIVE_PHASE_LINE_HEIGHT => (line_height..color_scheme, false),
+ LONGHAND_DRIVE_PHASE_COLOR_SCHEME => (color_scheme..color_scheme + 1, false),
+ LONGHAND_DRIVE_PHASE_REMAINING => (color_scheme + 1..u16::MAX, true),
+ _ => unreachable!("unknown longhand drive phase"),
+ };
+ let belongs_first = |property_id: u16| phase_computes_writing_mode_first && property_id == prop::WRITING_MODE;
+
+ let mut order: SmallVec<[u16; 48]> = SmallVec::new();
+ let mut offer = |property_id: u16| {
+ if belongs_first(property_id) || phase_ranks.contains(&rank_of(property_id)) {
+ order.push(property_id);
+ }
+ };
+ for (word_index, &word) in words.iter().enumerate() {
+ let mut bits = word;
+ while bits != 0 {
+ let bit = bits.trailing_zeros() as usize;
+ bits &= bits - 1;
+ offer(FIRST_LONGHAND_PROPERTY_ID + (word_index * 64 + bit) as u16);
+ }
+ }
+ for property_id in REQUIRED_DRIVER_INPUTS {
+ offer(property_id);
+ }
+ if background_image_is_selected {
+ for property_id in BACKGROUND_LAYER_LONGHANDS {
+ offer(property_id);
+ }
+ }
+ order.sort_unstable_by_key(|&property_id| (!belongs_first(property_id), rank_of(property_id)));
+ order.dedup();
+ order
+}
+
pub(crate) const LOGICAL_ALIAS_BIT: u8 = 1;
pub(crate) const PHYSICAL_TO_LOGICAL_BIT: u8 = 2;
@@ -3513,29 +3815,14 @@ fn clear_longhand_bit(words: &mut [u64], property_id: u16) {
#[allow(clippy::arc_with_non_send_sync)]
fn retained_new(value: StyleValueData) -> RetainedStyleValueData {
- RetainedStyleValueData::from_arc(Arc::new(value))
-}
-
-fn needs_computed_style_sheet_context(value: &RetainedStyleValueData) -> bool {
- // NB: Keep this traversal aligned with StyleValue::set_style_sheet(). Only image
- // wrappers consume the context; container wrappers forward it to their children.
- match value.optional_data() {
- Some(StyleValueData::Image { .. } | StyleValueData::ImageSet { .. }) => true,
- Some(StyleValueData::Content { content, alt_text }) => {
- needs_computed_style_sheet_context(content) || needs_computed_style_sheet_context(alt_text)
- }
- Some(StyleValueData::Shorthand { values, .. } | StyleValueData::ValueList { values, .. }) => {
- values.as_slice().iter().any(needs_computed_style_sheet_context)
- }
- _ => false,
- }
+ RetainedStyleValueData::from_arc(StyleValueArc::new(value))
}
/// Store what a drive found for one longhand: its computed value, and the value its inheritance depends on, if it
/// does. That's the specified value, except for a value that reads currentcolor: An inheriting element takes its
/// computed value, which keeps currentcolor to resolve against that element's own color, and whose lengths are
/// absolute (resolved against this element's font, as inheritance requires).
-fn store_driven_value(longhand_table: &mut ComputedLonghandTable, entry: ComputedStoreEntry) {
+fn store_driven_value(writer: &mut GroupValuesWriter<'_>, entry: ComputedStoreEntry) {
use crate::css::property_metadata::property_id as prop;
let inheritance_dependent_value = entry.inheritance_dependent.then(|| {
let inherits_computed_value = entry.computed_kind == COMPUTED_KIND_STYLE_VALUE
@@ -3547,29 +3834,21 @@ fn store_driven_value(longhand_table: &mut ComputedLonghandTable, entry: Compute
_ => entry.data.clone(),
}
});
- longhand_table.set_drive_inheritance_dependent_value(entry.property_id, inheritance_dependent_value);
- store_computed_value(longhand_table, entry);
+ writer.set_inheritance_dependent_value(entry.property_id, inheritance_dependent_value);
+ store_computed_value(writer, entry);
}
-fn store_computed_value(longhand_table: &mut ComputedLonghandTable, entry: ComputedStoreEntry) {
- let source_slot = if entry.has_style_sheet_context
- && entry.computed_kind == COMPUTED_KIND_UNCHANGED
- && needs_computed_style_sheet_context(entry.data)
- {
- entry.source_slot
- } else {
- -1
- };
+fn store_computed_value(writer: &mut GroupValuesWriter<'_>, entry: ComputedStoreEntry) {
let computed = match entry.computed_kind {
COMPUTED_KIND_UNCHANGED => {
- longhand_table.set_or_keep_equal(entry.property_id, entry.data.clone(), source_slot);
+ writer.set_or_keep_equal(entry.property_id, entry.data);
return;
}
COMPUTED_KIND_STYLE_VALUE => {
let computed = entry
.computed_data
.expect("a replaced computed value carries its replacement");
- longhand_table.set_or_keep_equal(entry.property_id, computed, source_slot);
+ writer.set_or_keep_equal(entry.property_id, &computed);
return;
}
COMPUTED_KIND_PX_LENGTH => StyleValueData::Length {
@@ -3596,11 +3875,11 @@ fn store_computed_value(longhand_table: &mut ComputedLonghandTable, entry: Compu
},
_ => unreachable!("unknown computed longhand store kind"),
};
- longhand_table.set_computed(entry.property_id, computed, source_slot);
+ writer.set_computed(entry.property_id, computed);
}
/// The background longhands whose lists are coordinated with the number of background-image layers when they compute.
-const BACKGROUND_LAYER_LONGHANDS: [u16; 7] = {
+pub(crate) const BACKGROUND_LAYER_LONGHANDS: [u16; 7] = {
use crate::css::property_metadata::property_id as prop;
[
prop::BACKGROUND_ATTACHMENT,
@@ -3759,7 +4038,9 @@ pub(crate) const PROPERTIES_DISABLING_NATIVE_APPEARANCE: &[u16] = {
// Specifically, if all the declarations of the Author Origin pertaining to such a widget are cascaded and a cascaded
// value exists--after having rolled back any number revert or revert-layer values--for any property that disables
// native appearance for widgets, then that widget is rendered as a devolved widget.
-fn has_author_value_disabling_native_appearance(store: &impl crate::css::cascaded_properties::CascadedValues) -> bool {
+pub(crate) fn has_author_value_disabling_native_appearance(
+ store: &impl crate::css::cascaded_properties::CascadedValues,
+) -> bool {
PROPERTIES_DISABLING_NATIVE_APPEARANCE.iter().any(|&property_id| {
matches!(
store.winning_origin(property_id),
@@ -3784,7 +4065,7 @@ fn has_author_value_disabling_native_appearance(store: &impl crate::css::cascade
/// The slices `environment` points at must be live.
#[allow(clippy::too_many_arguments)]
pub(crate) unsafe fn drive_property_computation(
- longhand_table: &mut ComputedLonghandTable,
+ writer: &mut GroupValuesWriter<'_>,
store: &impl crate::css::cascaded_properties::CascadedValues,
snapshot: Option<&ParentSnapshot<'_>>,
highlight: Option<&HighlightInheritance<'_>>,
@@ -3793,7 +4074,7 @@ pub(crate) unsafe fn drive_property_computation(
phase: u8,
length_resolution_context: Option<&FfiLengthResolutionContext>,
input_line_height_metrics: Option<&FfiInputLineHeightMetrics>,
- results: &mut FfiLonghandDriverResults,
+ results: &mut LonghandDriverResults,
effective_color_scheme: &mut i16,
coordinate_overflow_keywords: bool,
) {
@@ -3845,12 +4126,8 @@ pub(crate) unsafe fn drive_property_computation(
// computed values of zoom.
// NB: A drive that does not compute zoom reads what an earlier phase computed.
let mut zoom = DriveZoom {
- parent_effective_zoom: snapshot.map_or(1.0, |snapshot| f64::from(snapshot.table.effective_zoom())),
- zoom: used_zoom(
- longhand_table
- .get(prop::ZOOM)
- .and_then(RetainedStyleValueData::optional_data),
- ),
+ parent_effective_zoom: snapshot.map_or(1.0, |snapshot| f64::from(snapshot.longhands.effective_zoom())),
+ zoom: used_zoom(writer.get(prop::ZOOM).and_then(RetainedStyleValueData::optional_data)),
root_effective_zoom: if environment.root_effective_zoom > 0.0 {
environment.root_effective_zoom
} else {
@@ -3870,12 +4147,10 @@ pub(crate) unsafe fn drive_property_computation(
let mut background_image_list_length: Option<usize> = None;
// The computed writing-mode and direction, tracked for logical alias pairing;
// both properties only take keywords, whose computed value is the specified one.
- let mut computed_writing_mode = longhand_table
- .get(prop::WRITING_MODE)
- .and_then(|value| match value.data() {
- StyleValueData::Keyword { keyword } => keyword_to_writing_mode(*keyword),
- _ => None,
- });
+ let mut computed_writing_mode = writer.get(prop::WRITING_MODE).and_then(|value| match value.data() {
+ StyleValueData::Keyword { keyword } => keyword_to_writing_mode(*keyword),
+ _ => None,
+ });
let mut computed_direction: Option<u8> = None;
let mut computed_overflow_x: Option<u16> = None;
let mut computed_overflow_y: Option<u16> = None;
@@ -3891,6 +4166,9 @@ pub(crate) unsafe fn drive_property_computation(
// NB: The background layer longhands are coordinated with the number of background-image layers as they compute,
// so a drive that evaluates background-image again evaluates them again as well.
let background_image_is_selected = is_selected(prop::BACKGROUND_IMAGE);
+ let partial_order =
+ computed_property_words.map(|words| partial_drive_phase_order(phase, words, background_image_is_selected));
+ let computation_order = partial_order.as_deref().unwrap_or(computation_order);
for &property_id in computation_order {
let required_driver_input = is_required_driver_input(property_id);
@@ -3960,12 +4238,12 @@ pub(crate) unsafe fn drive_property_computation(
set_longhand_bit(&mut important_words, property_id);
}
if property_id == crate::css::property_metadata::property_id::FONT_SIZE {
- longhand_table.set_raw_cascaded_font_size(Some(value_data.clone()));
+ writer.flags_mut().set_raw_cascaded_font_size(Some(value_data.clone()));
}
} else if property_id == crate::css::property_metadata::property_id::FONT_SIZE && has_new_font_size {
// NB: The recascade walks the ancestors. The inherited result still takes this element's own zoom.
if zoom.length_zoom() != 1.0 {
- let recascaded = longhand_table.get(property_id).and_then(|value| {
+ let recascaded = writer.get(property_id).and_then(|value| {
if let StyleValueData::Length { value, unit } = value.data() {
Some((
CssPixels::nearest_value_for(value * zoom.length_zoom()).to_double(),
@@ -3976,12 +4254,12 @@ pub(crate) unsafe fn drive_property_computation(
}
});
if let Some((value, unit)) = recascaded {
- longhand_table.set_computed(property_id, StyleValueData::Length { value, unit }, -1);
+ writer.set_computed(property_id, StyleValueData::Length { value, unit });
}
}
continue;
} else if property_id == crate::css::property_metadata::property_id::FONT_SIZE {
- longhand_table.set_raw_cascaded_font_size(None);
+ writer.flags_mut().set_raw_cascaded_font_size(None);
}
let cascaded_value = value.map(RetainedStyleValueData::data);
@@ -4036,10 +4314,6 @@ pub(crate) unsafe fn drive_property_computation(
external_dependencies = None;
let snapshot = highlight_parent_snapshot.or(snapshot).unwrap();
set_longhand_bit(&mut inherited_words, property_id);
- if decision.explicitly_inherits_non_inherited_property {
- results.explicitly_inherited_non_inherited_style_groups |=
- crate::css::computed_values::computed_group_output_mask(inherited_property_id).unwrap_or(u32::MAX);
- }
// Both the inherited-by-default read and an explicit `inherit` of a
// non-inherited property take the parent's stored computed value for
// `inherited_property_id` straight from the snapshot's table span.
@@ -4168,7 +4442,7 @@ pub(crate) unsafe fn drive_property_computation(
let absolutize_value = |value: &StyleValueData,
length: &FfiLengthResolutionContext,
scheme: Option<u8>,
- results: &mut FfiLonghandDriverResults| {
+ results: &mut LonghandDriverResults| {
let context = crate::css::absolutize::AbsolutizationContext {
length,
scheme,
@@ -4277,7 +4551,7 @@ pub(crate) unsafe fn drive_property_computation(
Number(f64),
Percentage(f64),
FontStyle(u8),
- StyleValue(Arc<StyleValueData>),
+ StyleValue(StyleValueArc),
}
use crate::css::property_metadata::property_id as prop;
let synthesized_px_length = |absolutized: Option<f64>| {
@@ -4431,12 +4705,10 @@ pub(crate) unsafe fn drive_property_computation(
{
let absolutized = native_absolutized.flatten();
let computed_math_depth = computed_math_depth.or_else(|| {
- longhand_table
- .get(prop::MATH_DEPTH)
- .and_then(|value| match value.data() {
- StyleValueData::Integer { value } => Some(*value),
- _ => None,
- })
+ writer.get(prop::MATH_DEPTH).and_then(|value| match value.data() {
+ StyleValueData::Integer { value } => Some(*value),
+ _ => None,
+ })
});
if let Some(computed_math_depth) = computed_math_depth {
// A font-size relative to the inherited size also inherits the
@@ -4641,12 +4913,10 @@ pub(crate) unsafe fn drive_property_computation(
// than use time, unlike other coordinating list property groups.
let layer_count = background_image_list_length
.or_else(|| {
- longhand_table
- .get(prop::BACKGROUND_IMAGE)
- .and_then(|value| match value.data() {
- StyleValueData::ValueList { values, .. } => Some(values.as_slice().len()),
- _ => None,
- })
+ writer.get(prop::BACKGROUND_IMAGE).and_then(|value| match value.data() {
+ StyleValueData::ValueList { values, .. } => Some(values.as_slice().len()),
+ _ => None,
+ })
})
.expect("background-image must be a computed value list");
let resolution_context =
@@ -4712,7 +4982,7 @@ pub(crate) unsafe fn drive_property_computation(
&& let [horizontal, vertical] = values.as_slice()
&& matches!(vertical.data(), StyleValueData::Keyword { keyword: code } if *code == keyword::RIGHT)
{
- NativeValue::StyleValue(Arc::new(horizontal.data().clone()))
+ NativeValue::StyleValue(StyleValueArc::new(horizontal.data().clone()))
} else {
NativeValue::Unchanged
}
@@ -4933,8 +5203,6 @@ pub(crate) unsafe fn drive_property_computation(
ComputedStoreEntry {
property_id,
data: value,
- source_slot,
- has_style_sheet_context,
inheritance_dependent,
computed_data,
computed_kind,
@@ -4944,8 +5212,6 @@ pub(crate) unsafe fn drive_property_computation(
ComputedStoreEntry {
property_id,
data: value,
- source_slot,
- has_style_sheet_context,
inheritance_dependent,
computed_data: None,
computed_kind: COMPUTED_KIND_UNCHANGED,
@@ -5028,8 +5294,9 @@ pub(crate) unsafe fn drive_property_computation(
});
}
} else if property_id == prop::COLOR_SCHEME
- && let StyleValueData::ColorScheme { scheme_codes, .. } = value_data
+ && let StyleValueData::ColorScheme(color_scheme_payload) = value_data
{
+ let ColorSchemePayload { scheme_codes, .. } = &**color_scheme_payload;
let color_scheme = resolve_effective_color_scheme(
scheme_codes.as_slice(),
color_scheme_input.preferred_color_scheme,
@@ -5053,7 +5320,7 @@ pub(crate) unsafe fn drive_property_computation(
}
let mut store = |entry: ComputedStoreEntry| {
- store_driven_value(longhand_table, entry);
+ store_driven_value(writer, entry);
};
if property_id == prop::OVERFLOW_X {
pending_overflow_x_store = Some(entry);
@@ -5068,226 +5335,892 @@ pub(crate) unsafe fn drive_property_computation(
store(entry);
}
if property_id == prop::ZOOM {
- zoom.zoom = used_zoom(
- longhand_table
- .get(prop::ZOOM)
- .and_then(RetainedStyleValueData::optional_data),
- );
+ zoom.zoom = used_zoom(writer.get(prop::ZOOM).and_then(RetainedStyleValueData::optional_data));
}
}
- longhand_table.set_effective_zoom(zoom.effective_zoom() as f32);
+ writer.set_effective_zoom(zoom.effective_zoom() as f32);
assert!(
pending_overflow_x_store.is_none(),
"overflow-y must follow overflow-x in computation order"
);
- longhand_table.finish_drive_inheritance_dependent_values();
- longhand_table.merge_driver_flags(&important_words, &inherited_words, &evaluated_words);
- longhand_table.merge_dependency_flags(
- results.depends_on_viewport_metrics,
- results.font_metrics_depend_on_viewport_metrics,
- results.highlight_colors_authored,
- results.highlight_color_is_current_color,
+ writer
+ .flags_mut()
+ .merge_driver_flags(&important_words, &inherited_words, &evaluated_words);
+ writer.merge_dependency_flags(
+ (u8::from(results.depends_on_viewport_metrics)
+ * crate::css::computed_longhand_table::DEPENDS_ON_VIEWPORT_METRICS)
+ | (u8::from(results.font_metrics_depend_on_viewport_metrics)
+ * crate::css::computed_longhand_table::FONT_METRICS_DEPEND_ON_VIEWPORT_METRICS)
+ | (u8::from(results.highlight_colors_authored)
+ * crate::css::computed_longhand_table::HIGHLIGHT_COLORS_AUTHORED)
+ | (u8::from(results.highlight_color_is_current_color)
+ * crate::css::computed_longhand_table::HIGHLIGHT_COLOR_IS_CURRENT_COLOR),
);
- if phase == LONGHAND_DRIVE_PHASE_REMAINING {
- // 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!(
- longhand_table.get(prop::APPEARANCE).map(RetainedStyleValueData::data),
- Some(StyleValueData::Keyword { keyword }) if *keyword == keyword::NONE
- );
- longhand_table
- .set_native_appearance_disabled(!appearance_is_none && has_author_value_disabling_native_appearance(store));
- }
if pending_effective_color_scheme >= 0 {
- longhand_table.set_effective_color_scheme(pending_effective_color_scheme);
+ writer.set_effective_color_scheme(pending_effective_color_scheme);
}
if phase != LONGHAND_DRIVE_PHASE_REMAINING {
return;
}
- let display_before = computed_display.expect("display must be computed by the longhand driver");
- longhand_table.set_display_before_box_type_transformation(display_before.encoded());
- let overflow_before = [
- computed_overflow_x.expect("overflow-x must be computed by the longhand driver"),
- computed_overflow_y.expect("overflow-y must be computed by the longhand driver"),
- ];
- longhand_table.set_overflow_before_adjustment(overflow_before);
+ adjust_computed_box(
+ writer,
+ box_type_input,
+ ComputedBoxInputs {
+ display: computed_display.expect("display must be computed by the longhand driver"),
+ overflow: [
+ computed_overflow_x.expect("overflow-x must be computed by the longhand driver"),
+ computed_overflow_y.expect("overflow-y must be computed by the longhand driver"),
+ ],
+ float_value: computed_float.expect("float must be computed by the longhand driver"),
+ position: computed_position.expect("position must be computed by the longhand driver"),
+ text_align: computed_text_align.expect("text-align must be computed by the longhand driver"),
+ },
+ input_line_height_metrics,
+ );
+}
+
+/// The computed values the box-type transformation and the element style adjustments read.
+struct ComputedBoxInputs {
+ display: FfiDisplay,
+ overflow: [u16; 2],
+ float_value: u16,
+ position: u16,
+ text_align: u16,
+}
+
+/// Record the box inputs a computation settled in `writer`, and adjust its computed values as the
+/// box-type transformation and the element style adjustments require. The adjustments apply only
+/// where the caller passes the input line-height metrics, which only the last phase of a
+/// computation knows.
+fn adjust_computed_box(
+ writer: &mut GroupValuesWriter<'_>,
+ box_type_input: &FfiBoxTypeTransformationInput,
+ inputs: ComputedBoxInputs,
+ input_line_height_metrics: Option<&FfiInputLineHeightMetrics>,
+) {
+ use crate::css::property_metadata::property_id as prop;
+
+ let display_before = inputs.display;
+ writer.set_display_before_box_type_transformation(display_before.encoded());
+ writer.set_overflow_before_adjustment(inputs.overflow);
+ let keyword_of = |property_id: u16| keyword_from_style_value(writer.value(property_id).data());
let mut box_type_input = *box_type_input;
box_type_input.display = display_before;
- box_type_input.float_value = computed_float.expect("float must be computed by the longhand driver");
- box_type_input.writing_mode = computed_writing_mode_and_direction(longhand_table).0;
- box_type_input.position = computed_position.expect("position must be computed by the longhand driver");
+ box_type_input.float_value = inputs.float_value;
+ box_type_input.writing_mode = writing_mode_and_direction_of(
+ Some(writer.value(prop::WRITING_MODE)),
+ Some(writer.value(prop::DIRECTION)),
+ )
+ .0;
+ box_type_input.position = inputs.position;
box_type_input.webkit_box_layout_transformation_applies =
- webkit_box_layout_transformation_applies(longhand_table, None);
- let text_align = computed_text_align.expect("text-align must be computed by the longhand driver");
- let adjustments = compute_element_style_adjustments(&box_type_input, text_align);
- let transformation = adjustments.box_type;
- let element_adjustment = adjustments.element_style;
- let post_compute_adjustment = PostComputeAdjustment {
- display_before,
- box_type_transformation: transformation,
- element_style_adjustment: element_adjustment,
+ keyword_of(prop::_WEBKIT_BOX_ORIENT) == keyword::VERTICAL && keyword_of(prop::CONTINUE) != keyword::AUTO;
+ let adjustments = compute_element_style_adjustments(&box_type_input, inputs.text_align);
+ let Some(input_line_height_metrics) = input_line_height_metrics else {
+ return;
};
- if let Some(input_line_height_metrics) = input_line_height_metrics {
- results.post_adjusted_longhands =
- apply_post_compute_adjustments(longhand_table, &post_compute_adjustment, input_line_height_metrics);
+ let adjusted = post_compute_adjusted_values(
+ &PostComputeAdjustment {
+ display_before,
+ box_type_transformation: adjustments.box_type,
+ element_style_adjustment: adjustments.element_style,
+ },
+ input_line_height_metrics,
+ );
+ // An adjustment moves only a computed value. Whether the value depends on the parent stays
+ // what the drive recorded for the specified value, as for a match-parent text-align it adjusts.
+ for (property_id, value) in adjusted.values {
+ writer.set_computed(property_id, value);
+ }
+ for property_id in adjusted.cleared_flags {
+ writer.clear_flags(property_id);
}
}
-pub(crate) fn is_required_driver_input(property_id: u16) -> bool {
+/// Whether the engine computes a declared longhand's value directly: the longhand computes directly,
+/// and the value reads nothing beyond the element's own font and the document's metrics.
+pub(crate) fn value_computes_directly(
+ property_id: u16,
+ data: &StyleValueData,
+ prepared_dependencies: Option<ExternalValueDependencies>,
+) -> bool {
use crate::css::property_metadata::property_id as prop;
- matches!(
- property_id,
- prop::COLOR_SCHEME
- | prop::DIRECTION
- | prop::DISPLAY
- | prop::FLOAT
- | prop::MATH_DEPTH
- | prop::OVERFLOW_X
- | prop::OVERFLOW_Y
- | prop::POSITION
- | prop::TEXT_ALIGN
- | prop::WRITING_MODE
- )
-}
-
-fn computed_value_list(table: &ComputedLonghandTable, property_id: u16) -> &[RetainedStyleValueData] {
- let StyleValueData::ValueList { values, .. } = table
- .get(property_id)
- .expect("computed transition longhand must be present")
- .data()
- else {
- unreachable!("computed transition longhand must be a value list")
+ if !computes_directly(property_id) || computes_in_font_phases(property_id) {
+ return false;
+ }
+ // The background layer longhands coordinate with the number of background-image layers,
+ // which is the identity only where every one of them holds a single layer.
+ if (property_id == prop::BACKGROUND_IMAGE || BACKGROUND_LAYER_LONGHANDS.contains(&property_id))
+ && matches!(data, StyleValueData::ValueList { values, .. } if values.as_slice().len() != 1)
+ {
+ return false;
+ }
+ let Some(dependencies) = prepared_dependencies.or_else(|| try_external_value_dependencies(data)) else {
+ return false;
};
- values.as_slice()
-}
-
-fn property_id_from_custom_ident(custom_ident: &crate::css::css_string::CssString) -> Option<u16> {
- crate::css::property_metadata::property_id_from_name(custom_ident.units())
+ // A value that is not computationally independent, such as a font-relative length or one
+ // reading `currentcolor`, still computes directly: the context it absolutizes against is the
+ // element's own, with the font of its drive or, for an element declaring no font longhand, its
+ // parent's, and the table keeps its specified value for the groups as a drive's does.
+ // The color property's own `currentcolor` is the inherited color, which the drive resolves.
+ !((property_id == prop::COLOR && crate::css::style_value::value_depends_on_current_color(data))
+ || dependencies.uses_tree_counting_function
+ || dependencies.uses_random_function
+ || dependencies.needs_document_base_url
+ || dependencies.may_need_style_sheet_resource_context
+ || dependencies.container_relative_length_unit_mask != 0)
+}
+
+/// Whether a longhand computes in the font or line-height phase of a drive.
+pub(crate) fn computes_in_font_phases(property_id: u16) -> bool {
+ use crate::css::property_metadata::FIRST_LONGHAND_PROPERTY_ID;
+ static FONT_PHASES: OnceLock<Box<[bool]>> = OnceLock::new();
+ let font_phases = FONT_PHASES.get_or_init(|| {
+ let mut font_phases =
+ vec![false; crate::css::property_metadata::NUMBER_OF_LONGHAND_PROPERTIES].into_boxed_slice();
+ // NB: The font phase also computes writing-mode first, but writing-mode belongs to the remaining
+ // phase, so this reads the unmodified computation order up to color-scheme.
+ let (_, color_scheme) = property_computation_phase_boundaries();
+ for &property in &crate::css::property_metadata::property_computation_order()[..color_scheme] {
+ font_phases[usize::from(property - FIRST_LONGHAND_PROPERTY_ID)] = true;
+ }
+ font_phases
+ });
+ font_phases[usize::from(property_id - FIRST_LONGHAND_PROPERTY_ID)]
}
-fn time_value_to_milliseconds(value: &StyleValueData) -> f64 {
- let StyleValueData::Time { value, unit } = value else {
- unreachable!("computed transition time must be a time value")
- };
- crate::css::calc::time_to_milliseconds(*value, *unit)
+/// Whether the engine computes a declared longhand directly: its computed value is its specified
+/// value absolutized against the element's context, with nothing the longhand drive special-cases.
+pub(crate) fn computes_directly(property_id: u16) -> bool {
+ use crate::css::property_metadata::FIRST_LONGHAND_PROPERTY_ID;
+ static DIRECT: OnceLock<Box<[bool]>> = OnceLock::new();
+ let direct = DIRECT.get_or_init(|| {
+ (0..crate::css::property_metadata::NUMBER_OF_LONGHAND_PROPERTIES)
+ .map(|index| longhand_computes_directly(FIRST_LONGHAND_PROPERTY_ID + index as u16))
+ .collect()
+ });
+ property_id
+ .checked_sub(FIRST_LONGHAND_PROPERTY_ID)
+ .and_then(|index| direct.get(usize::from(index)))
+ .copied()
+ .unwrap_or(false)
}
-/// The axes are read only when a logical alias needs mapping.
-fn append_transition_longhands(
- properties: &mut Vec<u16>,
- property: u16,
- writing_mode_and_direction: &mut impl FnMut() -> (u8, u8),
-) {
- use crate::css::property_metadata::{longhand_is_logical_alias, property_id as prop};
-
- if property == prop::ALL {
- let (writing_mode, direction) = writing_mode_and_direction();
- properties.extend_from_slice(all_transition_longhands(writing_mode, direction));
- } else if property_is_shorthand(property) {
- for &longhand in longhands_for_shorthand(property) {
- append_transition_longhands(properties, longhand, writing_mode_and_direction);
- }
- } else if property != prop::CUSTOM {
- properties.push(if longhand_is_logical_alias(property) {
- let (writing_mode, direction) = writing_mode_and_direction();
- map_logical_alias_to_physical(property, writing_mode, direction)
- } else {
- property
- });
+fn longhand_computes_directly(property_id: u16) -> bool {
+ use crate::css::property_metadata::property_id as prop;
+ // The background layer longhands coordinate with the number of background-image layers, which
+ // the direct computation checks for itself.
+ if property_id == prop::BACKGROUND_IMAGE || BACKGROUND_LAYER_LONGHANDS.contains(&property_id) {
+ return true;
+ }
+ // A line's width computes to its length snapped as a border width, which the direct
+ // computation does as the drive does; what its style makes of it is the groups' to say.
+ if is_line_width(property_id) {
+ return true;
+ }
+ if property_has_dedicated_compute_rule(property_id) || computes_in_font_phases(property_id) {
+ return false;
}
+ !matches!(
+ property_id,
+ // The drive computes these with rules of their own.
+ prop::TEXT_EMPHASIS_POSITION
+ | prop::STROKE_DASHOFFSET
+ | prop::STROKE_WIDTH
+ | prop::STROKE_DASHARRAY
+ | prop::BORDER_SPACING
+ | prop::BORDER_SHAPE
+ | prop::OFFSET_ROTATE
+ | prop::ANIMATION_RANGE_START
+ | prop::ANIMATION_RANGE_END
+ | prop::TEXT_ALIGN_LAST
+ | prop::COLOR_SCHEME
+ | prop::MATH_STYLE
+ // The logical mapping of the element's own declarations reads these.
+ | prop::DIRECTION
+ | prop::WRITING_MODE
+ )
}
-/// The physical longhands `transition-property: all` names under one writing mode and direction,
-/// expanded once per pair: `all` is the initial value, so nearly every table carries it.
-fn all_transition_longhands(writing_mode: u8, direction: u8) -> &'static [u16] {
- const WRITING_MODE_COUNT: usize = 5;
- const DIRECTION_COUNT: usize = 2;
- static LONGHANDS: [OnceLock<Box<[u16]>>; WRITING_MODE_COUNT * DIRECTION_COUNT] =
- [const { OnceLock::new() }; WRITING_MODE_COUNT * DIRECTION_COUNT];
-
- let index = usize::from(writing_mode) * DIRECTION_COUNT + usize::from(direction);
- LONGHANDS[index].get_or_init(|| {
- let mut properties = Vec::new();
- for &longhand in longhands_for_shorthand(crate::css::property_metadata::property_id::ALL) {
- append_transition_longhands(&mut properties, longhand, &mut || (writing_mode, direction));
- }
- properties.into_boxed_slice()
- })
+/// Whether `property_id` computes as a width snapped as a border width, which the device pixel
+/// ratio decides: a border, outline or column rule width, or a logical alias of one.
+pub(crate) fn property_snaps_as_border_width(property_id: u16) -> bool {
+ is_line_width(property_id)
+ || (table_row_bits(property_id) & LOGICAL_ALIAS_BIT != 0
+ && is_line_width(map_logical_alias_to_physical(property_id, 0, 0)))
}
-fn computed_writing_mode_and_direction(table: &ComputedLonghandTable) -> (u8, u8) {
+fn is_line_width(property_id: u16) -> bool {
use crate::css::property_metadata::property_id as prop;
-
- let writing_mode = match table.get(prop::WRITING_MODE).unwrap().data() {
- StyleValueData::Keyword { keyword } => keyword_to_writing_mode(*keyword).unwrap(),
- _ => unreachable!("computed writing-mode must be a keyword"),
- };
- let direction = match table.get(prop::DIRECTION).unwrap().data() {
- StyleValueData::Keyword { keyword } => keyword_to_direction(*keyword).unwrap(),
- _ => unreachable!("computed direction must be a keyword"),
- };
- (writing_mode, direction)
+ matches!(
+ property_id,
+ prop::BORDER_TOP_WIDTH
+ | prop::BORDER_RIGHT_WIDTH
+ | prop::BORDER_BOTTOM_WIDTH
+ | prop::BORDER_LEFT_WIDTH
+ | prop::OUTLINE_WIDTH
+ | prop::COLUMN_RULE_WIDTH
+ )
}
-fn active_transition_property_ids(table: &ComputedLonghandTable) -> impl Iterator<Item = u16> {
+/// The engine: what a thread absolutized each computationally independent value to, and whether that
+/// resolved a viewport-relative length, by the value's identity and the color scheme it absolutized
+/// under, or none for a value that is not independent. Elements declaring the same value then hold
+/// the same computed value.
+pub(crate) type AbsolutizedValues = crate::fast_hash::FastMap<
+ crate::css::style::pointer_key::PointerKey<RetainedStyleValueData, u8>,
+ Option<(RetainedStyleValueData, bool)>,
+>;
+
+/// The engine's direct computation of an element none of whose declarations needs anything the
+/// longhand drive special-cases: each winning value absolutizes against the element's context into
+/// `values`, which hold the element's inherited and initial values, and the box adjustments the
+/// drive ends its last phase with run over the result. The winners are ones classified as
+/// computing directly; answers false, leaving `values` to be discarded, where one does not
+/// absolutize.
+#[allow(clippy::too_many_arguments)]
+pub(crate) fn compute_declared_values<'a>(
+ values: &mut GroupValuesWriter<'_>,
+ winners: impl Iterator<Item = (u16, &'a RetainedStyleValueData, Option<ExternalValueDependencies>)>,
+ length: &FfiLengthResolutionContext,
+ scheme: Option<u8>,
+ box_type_input: &FfiBoxTypeTransformationInput,
+ is_th_element: bool,
+ adjust_box: bool,
+ driven: Option<&[u64]>,
+ absolutized: &mut AbsolutizedValues,
+ device_pixels_per_css_pixel: f64,
+) -> bool {
use crate::css::property_metadata::property_id as prop;
- let property_values = computed_value_list(table, prop::TRANSITION_PROPERTY);
- let duration_values = computed_value_list(table, prop::TRANSITION_DURATION);
- let delay_values = computed_value_list(table, prop::TRANSITION_DELAY);
- property_values
- .iter()
- .enumerate()
- .filter_map(move |(index, property_value)| {
- let duration = time_value_to_milliseconds(duration_values[index % duration_values.len()].data());
- let delay = time_value_to_milliseconds(delay_values[index % delay_values.len()].data());
- if duration.max(0.0) + delay <= 0.0 {
- return None;
+ // https://www.w3.org/TR/css-color-4/#resolving-other-colors
+ // In the color property, the used value of currentcolor is the resolved inherited value.
+ let inherited_color = values.get(prop::COLOR).cloned();
+ let inherited_text_align = match values
+ .get(prop::TEXT_ALIGN)
+ .and_then(RetainedStyleValueData::optional_data)
+ {
+ Some(StyleValueData::Keyword { keyword }) => *keyword,
+ _ => return false,
+ };
+ let (writing_mode, direction) =
+ writing_mode_and_direction_of(values.get(prop::WRITING_MODE), values.get(prop::DIRECTION));
+ // The longhands decided so far: a lower-priority member of a logical pair decides nothing the
+ // higher-priority member decided.
+ let mut decided: SmallVec<[u16; 32]> = SmallVec::new();
+ // What a drive over the table computed is decided too.
+ let was_driven = |property_id: u16| {
+ let index = usize::from(property_id - crate::css::property_metadata::FIRST_LONGHAND_PROPERTY_ID);
+ driven.is_some_and(|words| words[index / 64] & (1 << (index % 64)) != 0)
+ };
+ let parent_direction_is_ltr = match values
+ .get(prop::DIRECTION)
+ .and_then(RetainedStyleValueData::optional_data)
+ {
+ Some(StyleValueData::Keyword { keyword }) => *keyword == keyword::LTR,
+ _ => return false,
+ };
+ let context = crate::css::absolutize::AbsolutizationContext {
+ length,
+ scheme,
+ resolved_viewport_relative_length: std::cell::Cell::new(false),
+ tree_counting: None,
+ random_base_values: &[],
+ document_base_url: &[],
+ style_sheet_resource_context: None,
+ current_color: None,
+ };
+ for (property_id, value, prepared_dependencies) in winners {
+ let Some(data) = value.optional_data() else {
+ return false;
+ };
+ // The caller passes only winners it classified as computing directly.
+ debug_assert!(value_computes_directly(property_id, data, prepared_dependencies));
+ let color_context;
+ let context = if property_id == prop::COLOR {
+ color_context = crate::css::absolutize::AbsolutizationContext {
+ current_color: inherited_color.as_ref().and_then(RetainedStyleValueData::optional_data),
+ resolved_viewport_relative_length: std::cell::Cell::new(false),
+ ..context
+ };
+ &color_context
+ } else {
+ &context
+ };
+ let mut computed = if value_absolutization_is_identity(data) {
+ std::borrow::Cow::Borrowed(value)
+ } else {
+ // The color property absolutizes against the inherited color, which no key holds.
+ let scheme = scheme.unwrap_or(u8::MAX);
+ let memoized = (property_id != prop::COLOR)
+ .then(|| absolutized.get(&crate::css::style::pointer_key::PointerLookup::new(value, scheme)))
+ .flatten();
+ match memoized {
+ Some(Some((computed, resolved_viewport_relative_length))) => {
+ // NB: The element depends on the viewport as the one this was absolutized for did.
+ if *resolved_viewport_relative_length {
+ context.resolved_viewport_relative_length.set(true);
+ }
+ std::borrow::Cow::Owned(computed.clone())
+ }
+ _ => {
+ // Whether this value alone resolves a viewport-relative length, for the memo.
+ let resolved_before = context.resolved_viewport_relative_length.replace(false);
+ let computed = match crate::css::absolutize::absolutize(data, context) {
+ Some(crate::css::absolutize::Absolutized::Unchanged) => value.clone(),
+ Some(crate::css::absolutize::Absolutized::Changed(computed)) => computed,
+ None => return false,
+ };
+ let resolved_viewport_relative_length = context.resolved_viewport_relative_length.get();
+ context
+ .resolved_viewport_relative_length
+ .set(resolved_before || resolved_viewport_relative_length);
+ if property_id != prop::COLOR && memoized.is_none() {
+ let independent = value_is_computationally_independent(data) == Some(true);
+ absolutized.insert(
+ crate::css::style::pointer_key::PointerKey::new(value, scheme),
+ independent.then(|| (computed.clone(), resolved_viewport_relative_length)),
+ );
+ }
+ std::borrow::Cow::Owned(computed)
+ }
}
- let StyleValueData::CustomIdent { custom_ident } = property_value.data() else {
- return None;
+ };
+ // The physical longhand a logical alias's value computes as.
+ let physical = match table_row_bits(property_id) & LOGICAL_ALIAS_BIT != 0 {
+ true => Some(map_logical_alias_to_physical(property_id, writing_mode, direction)),
+ false => None,
+ };
+ // https://drafts.csswg.org/css-backgrounds/#border-width
+ // Computed value: absolute length, snapped as a border width
+ if is_line_width(physical.unwrap_or(property_id)) {
+ let Some(data) = computed.optional_data() else {
+ return false;
};
- property_id_from_custom_ident(custom_ident)
- })
-}
-
-pub(crate) fn has_active_transition_properties(table: &ComputedLonghandTable) -> bool {
- !active_transition_longhands(table).is_empty()
-}
-
-/// The physical longhands the table's `transition-*` values make transitionable: every
-/// `transition-property` entry with a positive combined duration and delay, expanded from
-/// shorthands and mapped from logical aliases.
-pub(crate) fn active_transition_longhands(table: &ComputedLonghandTable) -> Cow<'_, [u16]> {
- fn resolve(table: &ComputedLonghandTable) -> Vec<u16> {
- let mut writing_mode_and_direction = None;
- let mut writing_mode_and_direction =
- || *writing_mode_and_direction.get_or_insert_with(|| computed_writing_mode_and_direction(table));
- let mut properties = Vec::new();
- for property in active_transition_property_ids(table) {
- append_transition_longhands(&mut properties, property, &mut writing_mode_and_direction);
+ let result = compute_border_or_outline_width(data, device_pixels_per_css_pixel, length.zoom, None);
+ if !result.handled {
+ return false;
+ }
+ computed = std::borrow::Cow::Owned(retained_new(StyleValueData::Length {
+ value: result.value,
+ unit: px_length_unit(),
+ }));
}
- properties
- }
-
- match table.frozen_transition_longhands(|table| resolve(table).into_boxed_slice()) {
- Some(longhands) => Cow::Borrowed(longhands),
- None => Cow::Owned(resolve(table)),
- }
-}
-
-/// The table's `transition-*` values, per physical longhand they name: shorthands expanded,
-/// logical aliases mapped, and a longhand named more than once taking its last entry.
-pub(crate) fn transition_entries(table: &ComputedLonghandTable) -> Vec<crate::css::transition::TransitionEntry> {
- use crate::css::property_metadata::property_id as prop;
+ if property_id == prop::TEXT_ALIGN {
+ let Some(StyleValueData::Keyword { keyword }) = computed.optional_data() else {
+ return false;
+ };
+ let adjustment = compute_text_align_adjustment(
+ *keyword,
+ is_th_element,
+ true,
+ inherited_text_align,
+ parent_direction_is_ltr,
+ );
+ if adjustment.changed {
+ computed = std::borrow::Cow::Owned(RetainedStyleValueData::from_arc(StyleValueArc::new(
+ StyleValueData::Keyword {
+ keyword: adjustment.keyword,
+ },
+ )));
+ }
+ }
+ // https://drafts.csswg.org/css-logical/#box
+ // The computed value of both properties of a logical pair derives from the specified value
+ // of the one declared with higher priority, and the winners arrive highest priority first.
+ // https://drafts.csswg.org/css-color-4/#resolving-other-colors
+ // As a drive does, the table keeps the specified value of a longhand whose computed value
+ // depends on what the element inherits, which the groups resolve `currentcolor` from.
+ let inheritance_dependent = prepared_dependencies
+ .or_else(|| try_external_value_dependencies(data))
+ .is_none_or(|dependencies| dependencies.inheritance_dependent);
+ if let Some(physical) = physical {
+ if decided.contains(&physical) || was_driven(physical) {
+ // The physical longhand won, and its value is the alias's too.
+ if let Some(winning) = values.get(physical).cloned() {
+ computed = std::borrow::Cow::Owned(winning);
+ }
+ } else {
+ values.set_borrowed(physical, &computed);
+ // NB: The physical longhand is what its children inherit, so it keeps the specified
+ // value as well, replacing the one the table it started from held.
+ values.set_inheritance_dependent_value(physical, inheritance_dependent.then(|| value.clone()));
+ decided.push(physical);
+ }
+ } else if decided.contains(&property_id) || was_driven(property_id) {
+ continue;
+ }
+ decided.push(property_id);
+ values.set_borrowed(property_id, &computed);
+ values.set_inheritance_dependent_value(property_id, inheritance_dependent.then(|| value.clone()));
+ }
+ // The overflow keywords as declared, which the box adjustments read.
+ let overflow_keyword = |values: &GroupValuesWriter<'_>, property_id: u16| match values
+ .get(property_id)
+ .and_then(RetainedStyleValueData::optional_data)
+ {
+ Some(StyleValueData::Keyword { keyword }) => Some(*keyword),
+ _ => None,
+ };
+ let overflow = [
+ overflow_keyword(values, prop::OVERFLOW_X),
+ overflow_keyword(values, prop::OVERFLOW_Y),
+ ];
+ // https://drafts.csswg.org/css-overflow-3/#overflow-control
+ // NB: The two overflow longhands compute together, as in a drive.
+ if decided
+ .iter()
+ .any(|&property_id| property_id == prop::OVERFLOW_X || property_id == prop::OVERFLOW_Y)
+ {
+ let [Some(overflow_x), Some(overflow_y)] = overflow else {
+ return false;
+ };
+ let effective = resolve_effective_overflow_keywords(overflow_x, overflow_y);
+ for (changed, property_id, keyword) in [
+ (effective.changed_x, prop::OVERFLOW_X, effective.x_keyword),
+ (effective.changed_y, prop::OVERFLOW_Y, effective.y_keyword),
+ ] {
+ if !changed {
+ continue;
+ }
+ values.set_computed(property_id, StyleValueData::Keyword { keyword });
+ }
+ }
+ if context.resolved_viewport_relative_length.get() {
+ values.note_viewport_dependency();
+ }
+ if !adjust_box {
+ return true;
+ }
+ let computed = |property_id: u16| values.get(property_id).and_then(RetainedStyleValueData::optional_data);
+ let keyword = |property_id: u16| match computed(property_id) {
+ Some(StyleValueData::Keyword { keyword }) => Some(*keyword),
+ _ => None,
+ };
+ let Some(StyleValueData::Display { raw }) = computed(prop::DISPLAY) else {
+ return false;
+ };
+ let display = FfiDisplay::from_raw(*raw);
+ let ([Some(overflow_x), Some(overflow_y)], Some(float_value), Some(position), Some(text_align)) = (
+ overflow,
+ keyword(prop::FLOAT),
+ keyword(prop::POSITION),
+ keyword(prop::TEXT_ALIGN),
+ ) else {
+ return false;
+ };
+ let inputs = ComputedBoxInputs {
+ display,
+ overflow: [overflow_x, overflow_y],
+ float_value,
+ position,
+ text_align,
+ };
+ let metrics = FfiInputLineHeightMetrics {
+ current_line_height: 0.0,
+ minimum_line_height: 0.0,
+ };
+ adjust_computed_box(values, box_type_input, inputs, Some(&metrics));
+ true
+}
+
+/// The font longhands the engine computes natively, where the font group is all an element's
+/// declarations move beyond what computes directly: the ones the font resolution reads, the
+/// keyword-valued font features and line-height.
+pub(crate) fn font_value_computes_natively(property_id: u16, data: &StyleValueData) -> bool {
+ use crate::css::property_metadata::property_id as prop;
+ match property_id {
+ // A size relative to the viewport or a query container, or a math size, reads what only a
+ // drive resolves.
+ prop::FONT_SIZE => match data {
+ StyleValueData::Length { unit, .. } => matches!(
+ length_unit_kinds().get(usize::from(*unit)),
+ Some(LengthUnitKind::Px | LengthUnitKind::Absolute { .. } | LengthUnitKind::FontRelative { .. })
+ ),
+ StyleValueData::Percentage { .. } => true,
+ StyleValueData::Keyword { keyword } => *keyword != keyword::MATH,
+ _ => false,
+ },
+ prop::FONT_WEIGHT => matches!(data, StyleValueData::Number { .. } | StyleValueData::Keyword { .. }),
+ prop::FONT_WIDTH => matches!(data, StyleValueData::Percentage { .. } | StyleValueData::Keyword { .. }),
+ // NB: A calculated oblique angle may read lengths, such as query container units, that
+ // only a drive resolves.
+ prop::FONT_STYLE => match data {
+ StyleValueData::Keyword { .. } => true,
+ StyleValueData::FontStyle { angle_value, .. } => {
+ !matches!(angle_value.optional_data(), Some(StyleValueData::Calculated { .. }))
+ }
+ _ => false,
+ },
+ // NB: A cascade ending in `font-family: monospace` recascades the font size, which only a
+ // drive does.
+ prop::FONT_FAMILY => !font_family_is_monospace(data),
+ prop::LINE_HEIGHT => match data {
+ StyleValueData::Length { unit, .. } => matches!(
+ length_unit_kinds().get(usize::from(*unit)),
+ Some(LengthUnitKind::Px | LengthUnitKind::Absolute { .. } | LengthUnitKind::FontRelative { .. })
+ ),
+ StyleValueData::Keyword { keyword } => *keyword == keyword::NORMAL,
+ StyleValueData::Number { .. } | StyleValueData::Percentage { .. } => true,
+ _ => false,
+ },
+ // NB: The `font` shorthand resets these to keywords.
+ prop::FONT_SIZE_ADJUST => matches!(data, StyleValueData::Keyword { keyword } if *keyword == keyword::NONE),
+ prop::FONT_FEATURE_SETTINGS
+ | prop::FONT_KERNING
+ | prop::FONT_LANGUAGE_OVERRIDE
+ | prop::FONT_OPTICAL_SIZING
+ | 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::TEXT_RENDERING => {
+ matches!(data, StyleValueData::Keyword { .. }) && value_absolutization_is_identity(data)
+ }
+ _ => false,
+ }
+}
+
+/// The engine's native computation of the font longhands an element declares, each classified by
+/// [`font_value_computes_natively`], by the rules the font and line-height phases of a drive
+/// apply: into `values`, which hold the element's inherited values, against `length`, the length
+/// context of its parent's font for the font longhands, and of its own font with its parent's line
+/// height for line-height. An element with no parent inherits `parentless_font_size`, the
+/// document's initial font size, as its font size. Answers false where a value does not compute.
+pub(crate) fn compute_font_values<'a>(
+ values: &mut GroupValuesWriter<'_>,
+ winners: impl Iterator<Item = (u16, &'a RetainedStyleValueData)>,
+ length: &FfiLengthResolutionContext,
+ default_font_size_raw: i32,
+ parentless_font_size: Option<CssPixels>,
+) -> bool {
+ use crate::css::property_metadata::property_id as prop;
+ let context = crate::css::absolutize::AbsolutizationContext {
+ length,
+ scheme: None,
+ resolved_viewport_relative_length: std::cell::Cell::new(false),
+ tree_counting: None,
+ random_base_values: &[],
+ document_base_url: &[],
+ style_sheet_resource_context: None,
+ current_color: None,
+ };
+ for (property_id, value) in winners {
+ let Some(data) = value.optional_data() else {
+ return false;
+ };
+ debug_assert!(font_value_computes_natively(property_id, data));
+ // What the element inherits, which the winner has not replaced yet.
+ let inherited = |property_id: u16| values.get(property_id).and_then(RetainedStyleValueData::optional_data);
+ let computed = match property_id {
+ prop::FONT_SIZE => {
+ let absolutized = match data {
+ StyleValueData::Length { value, unit } => {
+ let result = absolutize_length(*value, usize::from(*unit), length);
+ if !result.handled {
+ return false;
+ }
+ result.changed.then_some(result.px)
+ }
+ _ => None,
+ };
+ let inherited_size = match (parentless_font_size, inherited(prop::FONT_SIZE)) {
+ (Some(size), _) => size,
+ (None, Some(StyleValueData::Length { value, unit })) if *unit == px_length_unit() => {
+ CssPixels::nearest_value_for(*value)
+ }
+ _ => return false,
+ };
+ // NB: The element declares no math-depth of its own, so its computed one is the
+ // one it inherits.
+ let math_depth = match inherited(prop::MATH_DEPTH) {
+ Some(StyleValueData::Integer { value }) => *value,
+ _ => 0,
+ };
+ let synthesized = absolutized.map(|px| StyleValueData::Length {
+ value: px,
+ unit: px_length_unit(),
+ });
+ let result = compute_font_size(
+ synthesized.as_ref().unwrap_or(data),
+ math_depth,
+ inherited_size,
+ math_depth,
+ CssPixels::from_raw(default_font_size_raw),
+ 1.0,
+ );
+ match (result.handled, result.unchanged, synthesized) {
+ (false, ..) => return false,
+ (true, true, Some(synthesized)) => RetainedStyleValueData::from_owned(synthesized),
+ (true, true, None) => value.clone(),
+ (true, false, _) => RetainedStyleValueData::from_owned(StyleValueData::Length {
+ value: result.value,
+ unit: px_length_unit(),
+ }),
+ }
+ }
+ prop::FONT_WEIGHT => {
+ let Some(StyleValueData::Number {
+ value: inherited_weight,
+ }) = inherited(prop::FONT_WEIGHT)
+ else {
+ return false;
+ };
+ let result = compute_font_weight(data, *inherited_weight);
+ match (result.handled, result.unchanged) {
+ (false, _) => return false,
+ (true, true) => value.clone(),
+ (true, false) => RetainedStyleValueData::from_owned(StyleValueData::Number { value: result.value }),
+ }
+ }
+ prop::LINE_HEIGHT => match data {
+ StyleValueData::Length {
+ value: length_value,
+ unit,
+ } => {
+ let result = absolutize_length(*length_value, usize::from(*unit), length);
+ match (result.handled, result.changed) {
+ (false, _) => return false,
+ (true, true) => RetainedStyleValueData::from_owned(StyleValueData::Length {
+ value: result.px,
+ unit: px_length_unit(),
+ }),
+ (true, false) => value.clone(),
+ }
+ }
+ _ => {
+ let result = compute_line_height(data, CssPixels::nearest_value_for(length.font_metrics.font_size));
+ match (result.handled, result.unchanged, result.is_number) {
+ (false, ..) => return false,
+ (true, true, _) => value.clone(),
+ (true, false, true) => {
+ RetainedStyleValueData::from_owned(StyleValueData::Number { value: result.value })
+ }
+ (true, false, false) => RetainedStyleValueData::from_owned(StyleValueData::Length {
+ value: result.value,
+ unit: px_length_unit(),
+ }),
+ }
+ }
+ },
+ prop::FONT_WIDTH => {
+ let result = compute_font_width(data);
+ match (result.handled, result.unchanged) {
+ (false, _) => return false,
+ (true, true) => value.clone(),
+ (true, false) => {
+ RetainedStyleValueData::from_owned(StyleValueData::Percentage { value: result.value })
+ }
+ }
+ }
+ _ => match (property_id, data) {
+ (prop::FONT_STYLE, StyleValueData::Keyword { keyword }) => {
+ match keyword_to_font_style_keyword(*keyword) {
+ Some(font_style) => RetainedStyleValueData::from_owned(StyleValueData::FontStyle {
+ font_style,
+ angle_value: RetainedStyleValueData::none(),
+ }),
+ None => value.clone(),
+ }
+ }
+ _ if value_absolutization_is_identity(data) => value.clone(),
+ _ => match crate::css::absolutize::absolutize(data, &context) {
+ Some(crate::css::absolutize::Absolutized::Unchanged) => value.clone(),
+ Some(crate::css::absolutize::Absolutized::Changed(computed)) => computed,
+ None => return false,
+ },
+ },
+ };
+ if context.resolved_viewport_relative_length.get() {
+ return false;
+ }
+ // As a drive does, the element keeps the specified value of a longhand whose computed
+ // value depends on what it inherits.
+ let inheritance_dependent = try_external_value_dependencies(data)
+ .is_none_or(|dependencies| dependencies.inheritance_dependent)
+ || value_depends_on_inherited_info_for_property(data, property_id);
+ let specified = inheritance_dependent.then(|| value.clone());
+ values.set(property_id, computed);
+ values.set_inheritance_dependent_value(property_id, specified);
+ }
+ true
+}
+
+/// The inputs every drive evaluates, selected or not.
+pub(crate) const REQUIRED_DRIVER_INPUTS: [u16; 10] = {
+ use crate::css::property_metadata::property_id as prop;
+ [
+ prop::COLOR_SCHEME,
+ prop::DIRECTION,
+ prop::DISPLAY,
+ prop::FLOAT,
+ prop::MATH_DEPTH,
+ prop::OVERFLOW_X,
+ prop::OVERFLOW_Y,
+ prop::POSITION,
+ prop::TEXT_ALIGN,
+ prop::WRITING_MODE,
+ ]
+};
+
+pub(crate) fn is_required_driver_input(property_id: u16) -> bool {
+ use crate::css::property_metadata::property_id as prop;
+ matches!(
+ property_id,
+ prop::COLOR_SCHEME
+ | prop::DIRECTION
+ | prop::DISPLAY
+ | prop::FLOAT
+ | prop::MATH_DEPTH
+ | prop::OVERFLOW_X
+ | prop::OVERFLOW_Y
+ | prop::POSITION
+ | prop::TEXT_ALIGN
+ | prop::WRITING_MODE
+ )
+}
+
+fn computed_value_list(longhands: crate::css::style::ViewLonghands<'_>, property_id: u16) -> &[RetainedStyleValueData] {
+ let StyleValueData::ValueList { values, .. } = longhands
+ .handle(property_id)
+ .expect("computed transition longhand must be present")
+ .data()
+ else {
+ unreachable!("computed transition longhand must be a value list")
+ };
+ values.as_slice()
+}
+
+fn property_id_from_custom_ident(custom_ident: &crate::css::css_string::CssString) -> Option<u16> {
+ crate::css::property_metadata::property_id_from_name(custom_ident.units())
+}
+
+fn time_value_to_milliseconds(value: &StyleValueData) -> f64 {
+ let StyleValueData::Time { value, unit } = value else {
+ unreachable!("computed transition time must be a time value")
+ };
+ crate::css::calc::time_to_milliseconds(*value, *unit)
+}
+
+/// The axes are read only when a logical alias needs mapping.
+fn append_transition_longhands(
+ properties: &mut Vec<u16>,
+ property: u16,
+ writing_mode_and_direction: &mut impl FnMut() -> (u8, u8),
+) {
+ use crate::css::property_metadata::{longhand_is_logical_alias, property_id as prop};
+
+ if property == prop::ALL {
+ let (writing_mode, direction) = writing_mode_and_direction();
+ properties.extend_from_slice(crate::css::computed_values::all_transition_longhands(
+ writing_mode,
+ direction,
+ ));
+ } else if property_is_shorthand(property) {
+ for &longhand in longhands_for_shorthand(property) {
+ append_transition_longhands(properties, longhand, writing_mode_and_direction);
+ }
+ } else if property != prop::CUSTOM {
+ properties.push(if longhand_is_logical_alias(property) {
+ let (writing_mode, direction) = writing_mode_and_direction();
+ map_logical_alias_to_physical(property, writing_mode, direction)
+ } else {
+ property
+ });
+ }
+}
+
+fn computed_writing_mode_and_direction(longhands: crate::css::style::ViewLonghands<'_>) -> (u8, u8) {
+ use crate::css::property_metadata::property_id as prop;
+
+ writing_mode_and_direction_of(longhands.handle(prop::WRITING_MODE), longhands.handle(prop::DIRECTION))
+}
+
+/// The writing mode and direction the computed `writing-mode` and `direction` values hold.
+pub(crate) fn writing_mode_and_direction_of(
+ writing_mode: Option<&RetainedStyleValueData>,
+ direction: Option<&RetainedStyleValueData>,
+) -> (u8, u8) {
+ let writing_mode = match writing_mode.unwrap().data() {
+ StyleValueData::Keyword { keyword } => keyword_to_writing_mode(*keyword).unwrap(),
+ _ => unreachable!("computed writing-mode must be a keyword"),
+ };
+ let direction = match direction.unwrap().data() {
+ StyleValueData::Keyword { keyword } => keyword_to_direction(*keyword).unwrap(),
+ _ => unreachable!("computed direction must be a keyword"),
+ };
+ (writing_mode, direction)
+}
+
+/// The properties a `transition-property` list names with a positive combined duration and delay.
+fn active_transition_property_ids_of<'a>(
+ property_values: &'a [RetainedStyleValueData],
+ duration_values: &'a [RetainedStyleValueData],
+ delay_values: &'a [RetainedStyleValueData],
+) -> impl Iterator<Item = u16> + 'a {
+ property_values
+ .iter()
+ .enumerate()
+ .filter_map(move |(index, property_value)| {
+ let duration = time_value_to_milliseconds(duration_values[index % duration_values.len()].data());
+ let delay = time_value_to_milliseconds(delay_values[index % delay_values.len()].data());
+ if duration.max(0.0) + delay <= 0.0 {
+ return None;
+ }
+ let StyleValueData::CustomIdent { custom_ident } = property_value.data() else {
+ return None;
+ };
+ property_id_from_custom_ident(custom_ident)
+ })
+}
+
+/// Whether computed `transition-property`, `transition-duration` and `transition-delay` values
+/// make any longhand transitionable.
+pub(crate) fn transition_values_declare_transitions(
+ properties: &RetainedStyleValueData,
+ durations: &RetainedStyleValueData,
+ delays: &RetainedStyleValueData,
+) -> bool {
+ fn value_list(value: &RetainedStyleValueData) -> &[RetainedStyleValueData] {
+ let StyleValueData::ValueList { values, .. } = value.data() else {
+ unreachable!("computed transition longhand must be a value list")
+ };
+ values.as_slice()
+ }
+ fn names_a_longhand(property: u16) -> bool {
+ use crate::css::property_metadata::property_id as prop;
+ property == prop::ALL
+ || if property_is_shorthand(property) {
+ longhands_for_shorthand(property)
+ .iter()
+ .any(|&longhand| names_a_longhand(longhand))
+ } else {
+ property != prop::CUSTOM
+ }
+ }
+ active_transition_property_ids_of(value_list(properties), value_list(durations), value_list(delays))
+ .any(names_a_longhand)
+}
- let property_values = computed_value_list(table, prop::TRANSITION_PROPERTY);
- let duration_values = computed_value_list(table, prop::TRANSITION_DURATION);
- let timing_function_values = computed_value_list(table, prop::TRANSITION_TIMING_FUNCTION);
- let delay_values = computed_value_list(table, prop::TRANSITION_DELAY);
- let behavior_values = computed_value_list(table, prop::TRANSITION_BEHAVIOR);
- let (writing_mode, direction) = computed_writing_mode_and_direction(table);
+/// The `transition-*` values of `longhands`, per physical longhand they name: shorthands expanded,
+/// logical aliases mapped, and a longhand named more than once taking its last entry.
+pub(crate) fn transition_entries(
+ longhands: crate::css::style::ViewLonghands<'_>,
+) -> Vec<crate::css::transition::TransitionEntry> {
+ use crate::css::property_metadata::property_id as prop;
+
+ let property_values = computed_value_list(longhands, prop::TRANSITION_PROPERTY);
+ let duration_values = computed_value_list(longhands, prop::TRANSITION_DURATION);
+ let timing_function_values = computed_value_list(longhands, prop::TRANSITION_TIMING_FUNCTION);
+ let delay_values = computed_value_list(longhands, prop::TRANSITION_DELAY);
+ let behavior_values = computed_value_list(longhands, prop::TRANSITION_BEHAVIOR);
+ let (writing_mode, direction) =
+ writing_mode_and_direction_of(longhands.handle(prop::WRITING_MODE), longhands.handle(prop::DIRECTION));
let mut entries: Vec<crate::css::transition::TransitionEntry> = Vec::new();
// Where each longhand's entry is in `entries`, so a longhand named again takes the later entry's place.
@@ -5333,8 +6266,8 @@ pub(crate) fn transition_entries(table: &ComputedLonghandTable) -> Vec<crate::cs
entries
}
-/// Whether `transition_entries` answers any entry for the table, without expanding them.
-pub(crate) fn has_transition_entries(table: &ComputedLonghandTable) -> bool {
+/// Whether `transition_entries` answers any entry for `longhands`, without expanding them.
+pub(crate) fn has_transition_entries(longhands: crate::css::style::ViewLonghands<'_>) -> bool {
use crate::css::property_metadata::property_id as prop;
// Whether an entry for `property` names a longhand, as `append_transition_longhands` would.
@@ -5350,7 +6283,7 @@ pub(crate) fn has_transition_entries(table: &ComputedLonghandTable) -> bool {
property != prop::CUSTOM
}
- computed_value_list(table, prop::TRANSITION_PROPERTY)
+ computed_value_list(longhands, prop::TRANSITION_PROPERTY)
.iter()
.any(|value| match value.data() {
StyleValueData::CustomIdent { custom_ident } => {
@@ -5360,12 +6293,35 @@ pub(crate) fn has_transition_entries(table: &ComputedLonghandTable) -> bool {
})
}
-/// Whether the table's `transition-delay` and `transition-duration` are each the single value `0s`.
-pub(crate) fn transition_delay_and_duration_are_single_zero(table: &ComputedLonghandTable) -> bool {
+/// Whether the `transition-delay` and `transition-duration` of `longhands` are each the single
+/// value `0s`.
+pub(crate) fn transition_delay_and_duration_are_single_zero(longhands: crate::css::style::ViewLonghands<'_>) -> bool {
use crate::css::property_metadata::property_id as prop;
- let duration_values = computed_value_list(table, prop::TRANSITION_DURATION);
- let delay_values = computed_value_list(table, prop::TRANSITION_DELAY);
+ transition_delay_and_duration_values_are_single_zero(
+ longhands
+ .handle(prop::TRANSITION_DELAY)
+ .expect("computed transition longhand must be present"),
+ longhands
+ .handle(prop::TRANSITION_DURATION)
+ .expect("computed transition longhand must be present"),
+ )
+}
+
+/// Whether computed `transition-delay` and `transition-duration` values are each the single value
+/// `0s`, as `transition_delay_and_duration_are_single_zero` answers for a table.
+pub(crate) fn transition_delay_and_duration_values_are_single_zero(
+ delays: &RetainedStyleValueData,
+ durations: &RetainedStyleValueData,
+) -> bool {
+ fn value_list(value: &RetainedStyleValueData) -> &[RetainedStyleValueData] {
+ let StyleValueData::ValueList { values, .. } = value.data() else {
+ unreachable!("computed transition longhand must be a value list")
+ };
+ values.as_slice()
+ }
+ let duration_values = value_list(durations);
+ let delay_values = value_list(delays);
delay_values.len() == 1
&& duration_values.len() == 1
&& time_value_to_milliseconds(delay_values[0].data()) == 0.0
@@ -5612,9 +6568,12 @@ pub extern "C" fn rust_view_timeline_inset_has_relative_length(value: &StyleValu
fn has_relative_length(value: &StyleValueData, is_absolute: &dyn Fn(u8) -> bool) -> bool {
match value {
StyleValueData::Length { unit, .. } => !is_absolute(*unit),
- StyleValueData::Calculated { rust_calculation, .. } => !rust_calculation
- .node()
- .is_computationally_independent(&|unit| is_absolute(unit), &|_| false),
+ StyleValueData::Calculated(calculated_payload) => {
+ let CalculatedPayload { rust_calculation, .. } = &**calculated_payload;
+ !rust_calculation
+ .node()
+ .is_computationally_independent(&|unit| is_absolute(unit), &|_| false)
+ }
StyleValueData::ValueList { values, .. } => values
.as_slice()
.iter()
@@ -5658,7 +6617,8 @@ fn animation_timeline_descriptor(value: &StyleValueData) -> AnimationTimelineDes
StyleValueData::Keyword { keyword } if *keyword == keyword::NONE => {
descriptor(FfiAnimationTimelineKind::None, scroller::NEAREST, axis::BLOCK)
}
- StyleValueData::Function { name, value } if fly_string_is_ascii(name, b"scroll") => {
+ StyleValueData::Function(function) if fly_string_is_ascii(&function.name, b"scroll") => {
+ let value = &function.value;
let StyleValueData::Tuple { values } = value.data() else {
unreachable!("computed scroll() timeline must contain a tuple")
};
@@ -5673,7 +6633,8 @@ fn animation_timeline_descriptor(value: &StyleValueData) -> AnimationTimelineDes
descriptor(FfiAnimationTimelineKind::Scroll, scroller, optional_axis(&arguments[1]))
}
// https://drafts.csswg.org/scroll-animations-1/#view-notation
- StyleValueData::Function { name, value } if fly_string_is_ascii(name, b"view") => {
+ StyleValueData::Function(function) if fly_string_is_ascii(&function.name, b"view") => {
+ let value = &function.value;
let StyleValueData::Tuple { values } = value.data() else {
unreachable!("computed view() timeline must contain a tuple")
};
@@ -5785,10 +6746,9 @@ fn animation_slot(pseudo_kind: u8) -> crate::css::style::animations::AnimationSl
/// <https://drafts.csswg.org/css-animations-1/#animations>
fn in_display_none_subtree_for_animations(
style_engine: &crate::css::style::StyleEngine,
- node: Option<crate::css::style::tree::StyleNodeID>,
+ node: crate::css::style::tree::StyleNodeID,
pseudo_kind: u8,
- table: &ComputedLonghandTable,
- overlay: Option<&AnimatedOverlay>,
+ longhands: crate::css::style::ViewLonghands<'_>,
definitions: &[FfiComputedAnimation],
) -> bool {
if !definitions
@@ -5797,16 +6757,13 @@ fn in_display_none_subtree_for_animations(
{
return false;
}
- if effective_display(table, overlay).is_none() {
+ if longhands.effective_display(None).is_none() {
return true;
}
- let Some(node) = node else {
- return false;
- };
// The element's own display is answered above, so an element's walk starts at its parent; a
// pseudo-element's starts at its originating element.
let start = match pseudo_kind == crate::css::cascaded_properties::NO_PSEUDO_ELEMENT {
- true => style_engine.tree().parent_or_shadow_host(node),
+ true => style_engine.parent_or_shadow_host(node),
false => Some(node),
};
start.is_some_and(|start| style_engine.has_inclusive_ancestor_with_display_none_ignoring_animations(start))
@@ -5820,16 +6777,15 @@ fn settled_animation_plan(
style_engine: &crate::css::style::StyleEngine,
node: crate::css::style::tree::StyleNodeID,
pseudo_kind: u8,
- record: u64,
+ record: &std::sync::Arc<crate::css::style::pipeline::Record>,
) -> Option<(smallvec::SmallVec<[FfiComputedAnimation; 1]>, bool)> {
- let view = style_engine.style_record_view(record)?;
- let table = view.longhand_table?;
- let declaration_scope = style_engine.animation_name_declaration_scope_of(node, pseudo_kind)?;
+ let longhands = crate::css::style::StyleRecordView::of_host_record(record).longhands();
+ let declaration_scope = style_engine.animation_name_declaration_scope_of(node, pseudo_kind, record)?;
let existing_animations = style_engine.element_css_defined_animations(node, animation_slot(pseudo_kind));
- let element_tree_scope = style_engine.tree().tree_scope(node);
+ let element_tree_scope = style_engine.element_tree_scope(node);
let mut definitions = smallvec::SmallVec::new();
build_computed_animation_list(
- table,
+ longhands,
existing_animations,
|name| {
style_engine
@@ -5842,7 +6798,7 @@ fn settled_animation_plan(
return None;
}
let in_display_none_subtree =
- in_display_none_subtree_for_animations(style_engine, Some(node), pseudo_kind, table, None, &definitions);
+ in_display_none_subtree_for_animations(style_engine, node, pseudo_kind, longhands, &definitions);
Some((definitions, in_display_none_subtree))
}
@@ -5860,23 +6816,26 @@ pub unsafe extern "C" fn rust_settled_animation_plan(
host: &crate::render_state::DocumentHost,
read: &crate::render_state::BegunRead,
node: u32,
- pseudo_kind: u8,
- record: u64,
+ pseudo_kind: u32,
+ record: *const c_void,
has_animations: bool,
context: *mut c_void,
apply: unsafe extern "C" fn(*mut c_void, *const FfiComputedAnimation, usize, bool),
) {
+ let pseudo_kind = pseudo_kind as u8;
let Some(node) = crate::css::style::tree::StyleNodeID::from_raw(node) else {
return;
};
// SAFETY: Guaranteed by the caller.
- // A record that names no animation plans none for an element that holds none, which the host reads off a record it
- // has the view of without asking.
+ let Some(record) = (unsafe { crate::css::style::bridge::retain_host_record(record) }) else {
+ return;
+ };
+ // A record that names no animation plans none for an element that holds none, which the host reads off the
+ // record without asking.
if !has_animations
- && let Some(view) = crate::css::style::engine_calls::known_style_record_view(host, record)
- // SAFETY: A published record's table lives as long as the record.
- && let Some(table) = unsafe { view.longhand_table.cast::<ComputedLonghandTable>().as_ref() }
- && !table_declares_css_animations(table)
+ && !crate::css::style::StyleRecordView::of_host_record(&record)
+ .longhands()
+ .declares_css_animations()
{
return;
}
@@ -5884,7 +6843,7 @@ pub unsafe extern "C" fn rust_settled_animation_plan(
// engine is borrowed while the host applies it: the definitions only point into the record.
let Some((definitions, in_display_none_subtree)) =
crate::css::style::engine_calls::with_engine(read, host, |engine| {
- settled_animation_plan(engine, node, pseudo_kind, record)
+ settled_animation_plan(engine, node, pseudo_kind, &record)
})
else {
return;
@@ -5899,10 +6858,13 @@ pub unsafe extern "C" fn rust_settled_animation_plan(
}
}
-/// Whether a computed `animation-name` names any animation, so that a first record computed with it
-/// decides an animation plan.
-pub(crate) fn table_declares_css_animations(table: &ComputedLonghandTable) -> bool {
- computed_value_list(table, property_id::ANIMATION_NAME)
+/// Whether a computed `animation-name` value names any animation.
+pub(crate) fn animation_names_declare_css_animations(names: &RetainedStyleValueData) -> bool {
+ let StyleValueData::ValueList { values, .. } = names.data() else {
+ unreachable!("computed animation-name must be a value list")
+ };
+ values
+ .as_slice()
.iter()
.any(|name| !matches!(name.data(), StyleValueData::Keyword { keyword } if *keyword == keyword::NONE))
}
@@ -5910,25 +6872,25 @@ pub(crate) fn table_declares_css_animations(table: &ComputedLonghandTable) -> bo
// https://drafts.csswg.org/css-values-4/#linked-properties
// https://drafts.csswg.org/css-animations-1/#animations
fn build_computed_animation_list(
- table: &ComputedLonghandTable,
+ longhands: crate::css::style::ViewLonghands<'_>,
existing_animations: &[crate::css::style::animations::CssDefinedAnimation],
resolve_keyframes: impl Fn(&[u16]) -> Option<usize>,
animations: &mut smallvec::SmallVec<[FfiComputedAnimation; 1]>,
) {
use crate::css::property_metadata::property_id as prop;
- let name_values = computed_value_list(table, prop::ANIMATION_NAME);
- let duration_values = computed_value_list(table, prop::ANIMATION_DURATION);
- let timing_function_values = computed_value_list(table, prop::ANIMATION_TIMING_FUNCTION);
- let iteration_count_values = computed_value_list(table, prop::ANIMATION_ITERATION_COUNT);
- let direction_values = computed_value_list(table, prop::ANIMATION_DIRECTION);
- let play_state_values = computed_value_list(table, prop::ANIMATION_PLAY_STATE);
- let delay_values = computed_value_list(table, prop::ANIMATION_DELAY);
- let fill_mode_values = computed_value_list(table, prop::ANIMATION_FILL_MODE);
- let composition_values = computed_value_list(table, prop::ANIMATION_COMPOSITION);
- let timeline_values = computed_value_list(table, prop::ANIMATION_TIMELINE);
- let range_start_values = computed_value_list(table, prop::ANIMATION_RANGE_START);
- let range_end_values = computed_value_list(table, prop::ANIMATION_RANGE_END);
+ let name_values = computed_value_list(longhands, prop::ANIMATION_NAME);
+ let duration_values = computed_value_list(longhands, prop::ANIMATION_DURATION);
+ let timing_function_values = computed_value_list(longhands, prop::ANIMATION_TIMING_FUNCTION);
+ let iteration_count_values = computed_value_list(longhands, prop::ANIMATION_ITERATION_COUNT);
+ let direction_values = computed_value_list(longhands, prop::ANIMATION_DIRECTION);
+ let play_state_values = computed_value_list(longhands, prop::ANIMATION_PLAY_STATE);
+ let delay_values = computed_value_list(longhands, prop::ANIMATION_DELAY);
+ let fill_mode_values = computed_value_list(longhands, prop::ANIMATION_FILL_MODE);
+ let composition_values = computed_value_list(longhands, prop::ANIMATION_COMPOSITION);
+ let timeline_values = computed_value_list(longhands, prop::ANIMATION_TIMELINE);
+ let range_start_values = computed_value_list(longhands, prop::ANIMATION_RANGE_START);
+ let range_end_values = computed_value_list(longhands, prop::ANIMATION_RANGE_END);
// The name of each definition, for matching against the animations the host holds.
let mut definition_names = smallvec::SmallVec::<[&crate::css::css_string::CssString; 1]>::new();
@@ -6005,20 +6967,20 @@ fn build_computed_animation_list(
);
}
-fn effective_longhand_data<'a>(
- table: &'a ComputedLonghandTable,
- overlay: Option<&'a AnimatedOverlay>,
+fn effective_keyword(
+ longhands: crate::css::style::ViewLonghands<'_>,
+ overlay: Option<&AnimatedOverlay>,
property_id: u16,
-) -> &'a StyleValueData {
- table.effective_value_handle(overlay, property_id, true).0.data()
+) -> u16 {
+ keyword_from_style_value(longhands.effective_value(overlay, property_id).data())
}
-fn effective_keyword(table: &ComputedLonghandTable, overlay: Option<&AnimatedOverlay>, property_id: u16) -> u16 {
- keyword_from_style_value(effective_longhand_data(table, overlay, property_id))
-}
-fn webkit_box_layout_transformation_applies(table: &ComputedLonghandTable, overlay: Option<&AnimatedOverlay>) -> bool {
- effective_keyword(table, overlay, property_id::_WEBKIT_BOX_ORIENT) == keyword::VERTICAL
- && effective_keyword(table, overlay, property_id::CONTINUE) != keyword::AUTO
+fn webkit_box_layout_transformation_applies(
+ longhands: crate::css::style::ViewLonghands<'_>,
+ overlay: Option<&AnimatedOverlay>,
+) -> bool {
+ effective_keyword(longhands, overlay, property_id::_WEBKIT_BOX_ORIENT) == keyword::VERTICAL
+ && effective_keyword(longhands, overlay, property_id::CONTINUE) != keyword::AUTO
}
fn keyword_from_style_value(value: &StyleValueData) -> u16 {
@@ -6028,30 +6990,50 @@ fn keyword_from_style_value(value: &StyleValueData) -> u16 {
*keyword
}
-pub(crate) fn effective_writing_mode(table: &ComputedLonghandTable, overlay: Option<&AnimatedOverlay>) -> u8 {
- keyword_to_writing_mode(effective_keyword(table, overlay, property_id::WRITING_MODE))
+/// The writing mode a computed `writing-mode` value holds.
+pub(crate) fn writing_mode_of(value: &RetainedStyleValueData) -> u8 {
+ value
+ .optional_data()
+ .and_then(|data| keyword_to_writing_mode(keyword_from_style_value(data)))
.unwrap_or(crate::css::css_enums::writing_mode::HORIZONTAL_TB)
}
-pub(crate) fn effective_display(table: &ComputedLonghandTable, overlay: Option<&AnimatedOverlay>) -> FfiDisplay {
- let StyleValueData::Display { raw } = effective_longhand_data(table, overlay, property_id::DISPLAY) else {
+/// The display a computed `display` value holds.
+pub(crate) fn display_of(value: &RetainedStyleValueData) -> FfiDisplay {
+ let Some(StyleValueData::Display { raw }) = value.optional_data() else {
unreachable!("display must have a display value")
};
FfiDisplay::from_raw(*raw)
}
-/// Creates the complete initial document longhand table. Unlike a normal
-/// element drive, no cascade, inheritance, or element-specific adjustment
-/// participates.
+/// Computes the document's own style into a record no element holds, which holds the default
+/// groups until `rust_intern_document_style` builds its own. Unlike a normal element drive, no
+/// cascade, inheritance, or element-specific adjustment participates. Answers one reference to the
+/// record, which the caller releases with `style_engine_record_release`.
///
/// # Safety
-/// `input` must point at a valid input block for the duration of this call. The
-/// returned pointer transfers one strong reference to the caller.
+/// `host` must be a live document host, on its document's thread, and `input` must point at a valid
+/// input block for the duration of this call.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_create_document_longhand_table(
+pub unsafe extern "C" fn rust_create_document_style_record(
+ host: &crate::render_state::DocumentHost,
+ read: &crate::render_state::BegunRead,
+ input: &FfiDocumentLonghandInput,
+) -> *const c_void {
+ crate::css::style::engine_calls::with_engine(read, host, |engine| {
+ // SAFETY: Guaranteed by the caller.
+ unsafe { create_document_style_record(engine.default_groups(), input) }
+ })
+}
+
+/// The record `rust_create_document_style_record` answers, computed from `defaults`.
+///
+/// # Safety
+/// As for `rust_create_document_style_record`.
+unsafe fn create_document_style_record(
+ defaults: &crate::css::computed_values::DefaultGroups,
input: &FfiDocumentLonghandInput,
-) -> *mut ComputedLonghandTable {
- let mut longhand_table = ComputedLonghandTable::new();
+) -> *const c_void {
let store = CascadedPropertyStore::new();
let environment = FfiStyleComputationEnvironment {
box_type_input: FfiBoxTypeTransformationInput {
@@ -6098,85 +7080,86 @@ pub unsafe extern "C" fn rust_create_document_longhand_table(
default_font_size_raw: input.default_font_size_raw,
root_effective_zoom: 1.0,
};
- let mut results = empty_longhand_driver_results();
- let mut effective_color_scheme = -1;
- for phase in [
- LONGHAND_DRIVE_PHASE_FONT,
- LONGHAND_DRIVE_PHASE_LINE_HEIGHT,
- LONGHAND_DRIVE_PHASE_COLOR_SCHEME,
- LONGHAND_DRIVE_PHASE_REMAINING,
- ] {
- let length_resolution_context =
- (phase != LONGHAND_DRIVE_PHASE_COLOR_SCHEME).then_some(&input.length_resolution_context);
- unsafe {
- drive_property_computation(
- &mut longhand_table,
- &store,
- None,
- None,
- &environment,
- None,
- phase,
- length_resolution_context,
- None,
- &mut results,
- &mut effective_color_scheme,
- true,
- );
- }
- }
- longhand_table.merge_dependency_flags(
- results.depends_on_viewport_metrics,
- results.font_metrics_depend_on_viewport_metrics,
- results.highlight_colors_authored,
- results.highlight_color_is_current_color,
- );
- longhand_table.set(
- property_id::WIDTH,
- retained_new(StyleValueData::Length {
- value: input.viewport_width,
- unit: px_length_unit(),
- }),
- -1,
- );
- longhand_table.set(
- property_id::HEIGHT,
- retained_new(StyleValueData::Length {
- value: input.viewport_height,
- unit: px_length_unit(),
- }),
- -1,
- );
- longhand_table.set(
- property_id::DISPLAY,
- retained_new(StyleValueData::Display {
- raw: FfiDisplay::block().encoded(),
- }),
- -1,
- );
- longhand_table.freeze();
- longhand_table.into_raw_shared().cast_mut()
+ // The document's values compute from nothing: from the default groups, which hold no values.
+ 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(),
+ LonghandTableFlags::empty(),
+ 0,
+ );
+ let mut results = empty_longhand_driver_results();
+ let mut effective_color_scheme = -1;
+ for phase in [
+ LONGHAND_DRIVE_PHASE_FONT,
+ LONGHAND_DRIVE_PHASE_LINE_HEIGHT,
+ LONGHAND_DRIVE_PHASE_COLOR_SCHEME,
+ LONGHAND_DRIVE_PHASE_REMAINING,
+ ] {
+ let length_resolution_context =
+ (phase != LONGHAND_DRIVE_PHASE_COLOR_SCHEME).then_some(&input.length_resolution_context);
+ unsafe {
+ drive_property_computation(
+ &mut writer,
+ &store,
+ None,
+ None,
+ &environment,
+ None,
+ phase,
+ length_resolution_context,
+ None,
+ &mut results,
+ &mut effective_color_scheme,
+ true,
+ );
+ }
+ }
+ writer.set(
+ property_id::WIDTH,
+ retained_new(StyleValueData::Length {
+ value: input.viewport_width,
+ unit: px_length_unit(),
+ }),
+ );
+ writer.set(
+ property_id::HEIGHT,
+ retained_new(StyleValueData::Length {
+ value: input.viewport_height,
+ unit: px_length_unit(),
+ }),
+ );
+ writer.set(
+ property_id::DISPLAY,
+ retained_new(StyleValueData::Display {
+ raw: FfiDisplay::block().encoded(),
+ }),
+ );
+ let (values, flags, dependency_flags) = writer.finish(&[]);
+ crate::css::style::bridge::document_style_record(values, flags, dependency_flags, defaults)
+ })
}
-/// Builds the document's own style from the longhand table `rust_create_document_longhand_table` created and interns
-/// its record, which the caller pins. Answers the record.
+/// Builds the groups of the document's own style from the record `rust_create_document_style_record` made and
+/// interns the record holding them, which the caller pins. Answers the record.
///
/// # Safety
-/// `host` must be a live document host, on its document's thread. `table` must point at a frozen table, `font` at
-/// the platform font inputs of its font group and `length` at the context its lengths resolve against, each live for
-/// the call.
+/// `host` must be a live document host, on its document's thread. `record` must be a record
+/// `rust_create_document_style_record` made, which the caller holds, `font` the platform font inputs of its font
+/// group and `length` the context its lengths resolve against, each live for the call.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_intern_document_style(
host: &crate::render_state::DocumentHost,
read: &crate::render_state::BegunRead,
- table: *const ComputedLonghandTable,
+ record: *const c_void,
font: *const crate::css::table_group_builder::FfiFontGroupBuildInputs,
length: *const FfiLengthResolutionContext,
) -> u64 {
// SAFETY: Guaranteed by the caller.
- let (table, font, length) = unsafe { (&*table, &*font, &*length) };
+ let (font, length) = unsafe { (&*font, &*length) };
crate::css::style::engine_calls::with_engine(read, host, |engine| unsafe {
- crate::css::style::bridge::intern_document_style(engine, table, font, length)
+ crate::css::style::bridge::intern_document_style(engine, record, font, length)
})
}
@@ -6193,9 +7176,9 @@ pub(crate) struct AnimationKeyframeLonghands {
/// cascaded together before its selected properties are evaluated. A custom
/// property's value is the one `custom_property_values` holds at its index.
pub(crate) fn compute_animation_keyframe_longhands(
- underlying_longhand_table: &ComputedLonghandTable,
+ underlying_longhands: crate::css::style::ViewLonghands<'_>,
style_engine: &crate::css::style::StyleEngine,
- inheritance_parent_style_record: u64,
+ inheritance_parent_record: Option<&std::sync::Arc<crate::css::style::pipeline::Record>>,
properties: &[crate::css::animation::ResolvedAnimationProperty],
environment: &FfiStyleComputationEnvironment,
length_contexts: &FfiAnimationLengthContexts,
@@ -6213,8 +7196,7 @@ pub(crate) fn compute_animation_keyframe_longhands(
font_metrics_depend_on_viewport_metrics: false,
};
}
- let parent_snapshot = (inheritance_parent_style_record != 0)
- .then(|| keyframe_parent_snapshot_for_style_record(style_engine, inheritance_parent_style_record));
+ let parent_snapshot = inheritance_parent_record.map(keyframe_parent_snapshot_of_record);
let mut longhands_by_keyframe = std::collections::BTreeMap::<usize, Vec<usize>>::new();
for (index, property) in properties.iter().enumerate() {
if property.custom_name_id != 0 {
@@ -6246,25 +7228,23 @@ pub(crate) fn compute_animation_keyframe_longhands(
// The keyframe drive reads only the selected longhands and the coordination inputs
// seeded below. Starting from the underlying table would retain and release every
// unrelated longhand for every keyframe on every animation sample.
- let mut table = ComputedLonghandTable::new();
- for property_id in [
+ let seeded: SmallVec<[(u16, RetainedStyleValueData); 4]> = [
property_id::_WEBKIT_BOX_ORIENT,
property_id::CONTINUE,
property_id::BACKGROUND_IMAGE,
// https://drafts.csswg.org/css-viewport/#zoom-property
// NB: The keyframe lengths are zoomed by the element's zoom, as its own lengths are.
property_id::ZOOM,
- ] {
- if let Some(value) = underlying_longhand_table.get(property_id) {
- table.set(property_id, value.clone_retained(), -1);
- }
- }
+ ]
+ .into_iter()
+ .filter_map(|property_id| Some((property_id, underlying_longhands.handle(property_id)?.clone_retained())))
+ .collect();
let mut store = CascadedPropertyStore::new();
for property_id in FIRST_LONGHAND_PROPERTY_ID..=LAST_LONGHAND_PROPERTY_ID {
if !is_required_driver_input(property_id) {
continue;
}
- if let Some(value) = underlying_longhand_table.get(property_id) {
+ if let Some(value) = underlying_longhands.handle(property_id) {
store.seed_retained_property(property_id, value.clone_retained(), false, false);
}
}
@@ -6277,8 +7257,8 @@ pub(crate) fn compute_animation_keyframe_longhands(
let value = match property.value_source {
FfiAnimationSpecifiedValueSource::Value => property.value.clone(),
FfiAnimationSpecifiedValueSource::Initial => initial_value_handle(property.source_longhand_id).clone(),
- FfiAnimationSpecifiedValueSource::Underlying => underlying_longhand_table
- .get(property.source_longhand_id)
+ FfiAnimationSpecifiedValueSource::Underlying => underlying_longhands
+ .handle(property.source_longhand_id)
.expect("an animated longhand must have an underlying value")
.clone_retained(),
FfiAnimationSpecifiedValueSource::Inherited => parent_snapshot
@@ -6321,49 +7301,58 @@ pub(crate) fn compute_animation_keyframe_longhands(
environment.style_sheet_resource_contexts = style_sheet_resource_contexts.as_ptr();
environment.style_sheet_resource_context_count = style_sheet_resource_contexts.len();
- let mut results = empty_longhand_driver_results();
- let mut effective_color_scheme = -1;
- for phase in [
- LONGHAND_DRIVE_PHASE_FONT,
- LONGHAND_DRIVE_PHASE_LINE_HEIGHT,
- LONGHAND_DRIVE_PHASE_COLOR_SCHEME,
- LONGHAND_DRIVE_PHASE_REMAINING,
- ] {
- let length_resolution_context = match phase {
- LONGHAND_DRIVE_PHASE_FONT => Some(&length_contexts.font),
- LONGHAND_DRIVE_PHASE_LINE_HEIGHT => Some(&length_contexts.line_height),
- LONGHAND_DRIVE_PHASE_COLOR_SCHEME => None,
- LONGHAND_DRIVE_PHASE_REMAINING => Some(&length_contexts.remaining),
- _ => unreachable!(),
- };
- unsafe {
- drive_property_computation(
- &mut table,
- &store,
- parent_snapshot.as_ref(),
- None,
- &environment,
- Some(&selected_longhands),
- phase,
- length_resolution_context,
- None,
- &mut results,
- &mut effective_color_scheme,
- false,
- );
+ crate::css::computed_values::with_default_seed(style_engine.default_groups(), |seed| {
+ let mut writer = crate::css::computed_values::GroupValuesWriter::seeded_for_child(
+ seed,
+ seed,
+ seeded.into_iter(),
+ LonghandTableFlags::empty(),
+ 0,
+ );
+ let mut results = empty_longhand_driver_results();
+ let mut effective_color_scheme = -1;
+ for phase in [
+ LONGHAND_DRIVE_PHASE_FONT,
+ LONGHAND_DRIVE_PHASE_LINE_HEIGHT,
+ LONGHAND_DRIVE_PHASE_COLOR_SCHEME,
+ LONGHAND_DRIVE_PHASE_REMAINING,
+ ] {
+ let length_resolution_context = match phase {
+ LONGHAND_DRIVE_PHASE_FONT => Some(&length_contexts.font),
+ LONGHAND_DRIVE_PHASE_LINE_HEIGHT => Some(&length_contexts.line_height),
+ LONGHAND_DRIVE_PHASE_COLOR_SCHEME => None,
+ LONGHAND_DRIVE_PHASE_REMAINING => Some(&length_contexts.remaining),
+ _ => unreachable!(),
+ };
+ unsafe {
+ drive_property_computation(
+ &mut writer,
+ &store,
+ parent_snapshot.as_ref(),
+ None,
+ &environment,
+ Some(&selected_longhands),
+ phase,
+ length_resolution_context,
+ None,
+ &mut results,
+ &mut effective_color_scheme,
+ false,
+ );
+ }
}
- }
- depends_on_viewport_metrics |= results.depends_on_viewport_metrics;
- font_metrics_depend_on_viewport_metrics |= results.font_metrics_depend_on_viewport_metrics;
- for &index in indices {
- if properties[index].is_transition {
- continue;
+ depends_on_viewport_metrics |= results.depends_on_viewport_metrics;
+ font_metrics_depend_on_viewport_metrics |= results.font_metrics_depend_on_viewport_metrics;
+ for &index in indices {
+ if properties[index].is_transition {
+ continue;
+ }
+ let value = writer
+ .get(properties[index].physical_property_id)
+ .expect("the keyframe longhand drive must store every selected property");
+ values[index] = Some(value.clone_retained());
}
- let value = table
- .get(properties[index].physical_property_id)
- .expect("the keyframe longhand drive must store every selected property");
- values[index] = Some(value.clone_retained());
- }
+ });
}
AnimationKeyframeLonghands {
@@ -6393,6 +7382,19 @@ pub const SUBSTITUTION_MARK_CUSTOM_FUNCTION: u8 = 1 << 4;
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct FfiEffectTiming {
+ pub timeline_scroller: i64,
+ pub minimum_timeline_time: f64,
+ pub maximum_timeline_time: f64,
+ pub timeline_time: f64,
+ pub timeline_origin_time: f64,
+ pub start_time: f64,
+ pub hold_time: f64,
+ pub playback_rate: f64,
+ pub start_delay: f64,
+ pub end_delay: f64,
+ pub iteration_duration: f64,
+ pub iteration_count: f64,
+ pub iteration_start: f64,
pub decidable: bool,
pub is_relevant: bool,
pub is_removed: bool,
@@ -6401,15 +7403,13 @@ pub struct FfiEffectTiming {
/// time.
pub has_timeline_origin_time: bool,
/// The effect's animation runs on a scroll timeline, whose time is the scroll progress, in percent, of
- /// the scroll node of this unique node id (an element's, or a document's for its viewport) along the
- /// vertical or the horizontal axis.
+ /// the scroll node `timeline_scroller` names, a unique node id (an element's, or a document's for its
+ /// viewport), along the vertical or the horizontal axis.
pub has_timeline_scroller: bool,
pub timeline_scroller_is_vertical: bool,
- pub timeline_scroller: i64,
- /// The effect's animation runs on a progress-based timeline, whose minimum and maximum timeline times these are.
+ /// The effect's animation runs on a progress-based timeline, whose minimum and maximum timeline times
+ /// `minimum_timeline_time` and `maximum_timeline_time` are.
pub has_timeline_boundaries: bool,
- pub minimum_timeline_time: f64,
- pub maximum_timeline_time: f64,
pub has_start_time: bool,
pub has_hold_time: bool,
/// The effect's animation is paused, which holds its time, as one whose play is pending does too.
@@ -6418,18 +7418,10 @@ pub struct FfiEffectTiming {
pub fill_mode: u8,
/// `Bindings::PlaybackDirection`, in IDL order.
pub playback_direction: u8,
- pub timeline_time: f64,
- pub timeline_origin_time: f64,
- pub start_time: f64,
- pub hold_time: f64,
- pub playback_rate: f64,
- pub start_delay: f64,
- pub end_delay: f64,
- pub iteration_duration: f64,
- pub iteration_count: f64,
- pub iteration_start: f64,
}
+const _: () = assert!(size_of::<FfiEffectTiming>() == 120);
+
/// ABI mirror of `AK::Optional<double>`.
#[repr(C)]
#[derive(Clone, Copy)]
@@ -6478,13 +7470,13 @@ pub struct FfiHostAnimationSample {
pub pseudo_kind: u8,
pub effects: *const FfiSampledAnimationEffect,
pub effect_count: usize,
- /// The working set's longhand table, which the animations compose over.
- pub longhand_table: *const c_void,
+ /// The style record whose longhands the working set reads, which the animations compose over.
+ pub record: *const c_void,
/// The working set's overlay before this sample, or null.
pub animated_overlay: *const c_void,
/// The record the host holds for the element where the working set was reconstructed from it,
- /// which the engine builds the length contexts over, or zero where the host builds them.
- pub style_record: u64,
+ /// which the engine builds the length contexts over, or null where the host builds them.
+ pub style_record: *const c_void,
/// The custom-property store the element holds now, which keyframes substitute against.
pub custom_property_store: *const c_void,
/// The same beneath the overlay of the sample before, which animations compose over.
@@ -6497,7 +7489,8 @@ pub struct FfiHostAnimationSample {
pub custom_property_environments: [u64; 2],
/// The host's current registrations, which the engine may not have consumed yet.
pub custom_property_registration_generation: u64,
- pub inheritance_parent_style_record: u64,
+ /// The record the host holds for the element the sampled one inherits from, or null.
+ pub inheritance_parent_record: *const c_void,
/// The document's side of the environment keyframes compute in. The engine fills in the
/// element's own: its place among its siblings and its random bases.
pub environment: *const FfiStyleComputationEnvironment,
@@ -6543,8 +7536,6 @@ pub struct FfiHostAnimationSampleResult {
/// The `SUBSTITUTION_MARK_*` bits of what the values and easings substituted against the
/// element held.
pub substitution_marks: u8,
- /// The custom properties a substituted `style()` query read, transferred to the caller, or null.
- pub style_query_dependencies: *mut c_void,
pub animated_custom_properties: *const FfiAnimatedCustomPropertyResult,
pub animated_custom_property_count: usize,
/// Released with `rust_release_animated_custom_property_results`.
@@ -6561,7 +7552,6 @@ impl FfiHostAnimationSampleResult {
font_metrics_depend_on_viewport_metrics: false,
uses_tree_counting_function: false,
substitution_marks: 0,
- style_query_dependencies: std::ptr::null_mut(),
animated_custom_properties: std::ptr::null(),
animated_custom_property_count: 0,
animated_custom_properties_storage: std::ptr::null_mut(),
@@ -6627,35 +7617,35 @@ pub(crate) struct AnimationSampleInput<'a> {
/// The pseudo-element sampled, or `NO_PSEUDO_ELEMENT` for the element itself.
pub(crate) pseudo_kind: u8,
pub(crate) effects: HostSampledEffects<'a>,
- /// The working set's longhand table, which the animations compose over.
- pub(crate) longhand_table: &'a ComputedLonghandTable,
+ /// The working set's longhands, which the animations compose over.
+ pub(crate) longhands: crate::css::style::ViewLonghands<'a>,
/// Whether the working set held an overlay before this sample.
pub(crate) has_animated_overlay: bool,
/// The working set's color before this sample, which `currentcolor` interpolates as.
pub(crate) current_color: RetainedStyleValueData,
/// The record the host holds for the element where the working set was reconstructed from it,
- /// which the engine builds the length contexts over, or zero where the host builds them.
- pub(crate) style_record: u64,
+ /// which the engine builds the length contexts over, or none where the host builds them.
+ pub(crate) style_record: Option<std::sync::Arc<crate::css::style::pipeline::Record>>,
pub(crate) stores: crate::css::animation::KeyframeStores,
/// The identities of the element's custom-property environment and the one it inherits, under
/// which values substituted against the element hold.
pub(crate) custom_property_environments: [u64; 2],
pub(crate) custom_property_registration_generation: u64,
- pub(crate) inheritance_parent_style_record: u64,
+ /// The record the host holds for the element the sampled one inherits from.
+ pub(crate) inheritance_parent_record: Option<std::sync::Arc<crate::css::style::pipeline::Record>>,
/// The document's side of the environment keyframes compute in.
pub(crate) environment: &'a FfiStyleComputationEnvironment,
/// The slot of the row of the box of the sampled element, invalid where it has none.
pub(crate) element_box_slot: u32,
}
-/// The color of a working set, as its longhand table and its overlay hold it.
+/// The color of a working set, as its record and its overlay hold it.
pub(crate) fn working_set_current_color(
- table: &ComputedLonghandTable,
+ longhands: crate::css::style::ViewLonghands<'_>,
overlay: Option<&AnimatedOverlay>,
) -> RetainedStyleValueData {
- table
- .effective_value_handle(overlay, crate::css::property_metadata::property_id::COLOR, true)
- .0
+ longhands
+ .effective_value(overlay, crate::css::property_metadata::property_id::COLOR)
.clone()
}
@@ -6670,7 +7660,7 @@ impl AnimationSampleInput<'_> {
let mut context = crate::css::animation::FfiAnimationContext {
allow_discrete: length_resolution_context.is_some(),
allow_keyword_size_interpolation: crate::css::animation::allows_keyword_size_interpolation(
- self.longhand_table,
+ self.longhands,
None,
),
current_color: Some(&self.current_color),
@@ -6732,22 +7722,24 @@ impl FfiHostAnimationSample {
/// sample may write the working set's overlay while it runs.
unsafe fn adopt(&self) -> (AnimationSampleInput<'_>, HostSampleCallbacks) {
// SAFETY: Guaranteed by the caller.
- let (longhand_table, animated_overlay, effects, environment) = unsafe {
+ let (longhands, animated_overlay, effects, environment, style_record, inheritance_parent_record) = unsafe {
(
- &*self.longhand_table.cast::<ComputedLonghandTable>(),
+ crate::css::style::ViewLonghands::of_raw_record(self.record),
self.animated_overlay.cast::<AnimatedOverlay>().as_ref(),
HostSampledEffects::new(ak::slice_from_raw_parts(self.effects, self.effect_count)),
&*self.environment,
+ crate::css::style::bridge::retain_host_record(self.style_record),
+ crate::css::style::bridge::retain_host_record(self.inheritance_parent_record),
)
};
let input = AnimationSampleInput {
style_node: self.style_node,
pseudo_kind: self.pseudo_kind,
effects,
- longhand_table,
+ longhands,
has_animated_overlay: animated_overlay.is_some(),
- current_color: working_set_current_color(longhand_table, animated_overlay),
- style_record: self.style_record,
+ current_color: working_set_current_color(longhands, animated_overlay),
+ style_record,
stores: crate::css::animation::KeyframeStores {
substitution: self.custom_property_store,
base: self.base_custom_property_store,
@@ -6756,7 +7748,7 @@ impl FfiHostAnimationSample {
},
custom_property_environments: self.custom_property_environments,
custom_property_registration_generation: self.custom_property_registration_generation,
- inheritance_parent_style_record: self.inheritance_parent_style_record,
+ inheritance_parent_record,
environment,
element_box_slot: self.element_box_slot,
};
@@ -6920,10 +7912,11 @@ fn engine_length_contexts(
engine: &crate::css::style::StyleEngine,
sample: &ResolvedAnimationSample,
) -> Option<FfiAnimationLengthContexts> {
- if input.style_record == 0 || sample.resolved.container_relative_length_unit_mask != 0 {
+ let record = input.style_record.as_ref()?;
+ if sample.resolved.container_relative_length_unit_mask != 0 {
return None;
}
- engine.animation_sample_length_contexts(sample.node, input.pseudo(), input.style_record)
+ Some(engine.animation_sample_length_contexts(sample.node, input.pseudo(), record))
}
/// A sample whose declarations are resolved, which computes its keyframe values over the element's
@@ -6968,7 +7961,7 @@ fn host_sampled_effects(input: &AnimationSampleInput, engine: &mut crate::css::s
debug_assert!(description.is_some(), "the host describes every effect it samples");
description
.is_some_and(|description| {
- description.generation == effect.generation && description.keyframes.len() >= 2
+ description.generation == effect.generation && description.keyframes().len() >= 2
})
.then_some(anim::FfiSampledAnimationEffect {
effect: anim::FfiAnimationPreparationEffect {
@@ -7010,7 +8003,7 @@ fn implicit_will_change_properties(
});
for effect in applicable_effects {
- for &property in &effect.target_properties {
+ for &property in effect.target_properties() {
properties.push(map_logical_alias_to_physical(property, writing_mode, direction));
}
}
@@ -7039,8 +8032,7 @@ fn begin_animation_sample(
return finished(Cleared);
};
let pseudo = input.pseudo();
- let table = input.longhand_table;
- let (writing_mode, direction) = computed_writing_mode_and_direction(table);
+ let (writing_mode, direction) = computed_writing_mode_and_direction(input.longhands);
let description = |identity| descriptions.iter().find(|description| description.identity == identity);
let new_implicit_will_change_properties =
implicit_will_change_properties(descriptions, timeline_samples, writing_mode, direction);
@@ -7074,7 +8066,7 @@ fn begin_animation_sample(
cache_preparation: true,
preparation_reads_custom_property_environments: false,
preparation_inputs: None,
- underlying_longhand_table: input.longhand_table,
+ underlying_longhands: input.longhands,
overlay: mutated_overlay,
custom_underlying_values: &[],
custom_initial_values: &[],
@@ -7096,18 +8088,35 @@ fn begin_animation_sample(
resolved,
custom_properties,
substitution_marks,
- style_query_dependencies,
- } = anim::resolve_published_animation_declarations(
- engine,
- node,
- pseudo,
- &selected,
- table,
- stores,
- writing_mode,
- direction,
- table.importance_bits(),
- );
+ ..
+ } = {
+ // A keyframe value substitutes to what it did at the last sample while the stores and registrations it read
+ // stand, so that sample's conversions are reused.
+ let conversions = std::cell::RefCell::new(anim::KeyframeConversionCache::new(
+ host.overlay_for_mutation().keyframe_conversions.as_ref(),
+ stores,
+ input.custom_property_registration_generation,
+ ));
+ let declarations = anim::resolve_published_animation_declarations(
+ engine,
+ node,
+ pseudo,
+ &selected,
+ input.longhands,
+ stores,
+ writing_mode,
+ direction,
+ input.longhands.importance_bits(),
+ &conversions,
+ );
+ // SAFETY: The stores are null or live for the sample.
+ host.overlay_for_mutation().keyframe_conversions = unsafe {
+ conversions
+ .into_inner()
+ .finish(stores, input.custom_property_registration_generation)
+ };
+ declarations
+ };
drop(selected);
let mut result = FfiHostAnimationSampleResult::with_outcome(if implicit_will_change_entries_changed {
Evaluated
@@ -7115,8 +8124,6 @@ fn begin_animation_sample(
Unchanged
});
result.substitution_marks = substitution_marks;
- result.style_query_dependencies =
- style_query_dependencies.map_or(std::ptr::null_mut(), |dependencies| Box::into_raw(dependencies).cast());
// Effects whose keyframes declare nothing the element animates compose nothing at all, and
// leave the overlay as it was.
if resolved.properties.is_empty() {
@@ -7164,7 +8171,11 @@ fn finish_animation_sample(
custom_properties,
mut result,
} = sample;
- let table = input.longhand_table;
+ let table = input.longhands;
+ if input.pseudo_kind == crate::css::cascaded_properties::NO_PSEUDO_ELEMENT {
+ engine
+ .note_keyframes_read_parent_reset_values(node, result.keyframes_inherited_non_inherited_style_groups != 0);
+ }
// The element's own side of the environment: its place among its siblings, and the random base
// value each random function a keyframe holds draws.
@@ -7206,9 +8217,9 @@ fn finish_animation_sample(
let (underlying_values, initial_values) = custom_properties.underlying_and_initial_values(registry);
let computed_keyframes = compute_animation_keyframe_longhands(
- input.longhand_table,
+ input.longhands,
engine,
- input.inheritance_parent_style_record,
+ input.inheritance_parent_record.as_ref(),
&resolved.properties,
&environment,
length_contexts,
@@ -7222,8 +8233,8 @@ fn finish_animation_sample(
|| resolved.properties.iter().any(|property| {
property.custom_name_id != 0
&& property.value_source == anim::FfiAnimationSpecifiedValueSource::Value
- && matches!(property.value.data(), StyleValueData::Unresolved { components, .. }
- if crate::css::parser::value_parser::contains_tree_counting_function(components.as_slice()))
+ && matches!(property.value.data(), StyleValueData::Unresolved(unresolved)
+ if unresolved.facts().calls_tree_counting_function())
});
// A preparation cached under these effects must hold for as long as they stand, so one that
@@ -7248,7 +8259,7 @@ fn finish_animation_sample(
resolved,
computed_keyframe_values: computed_keyframes.values,
}),
- underlying_longhand_table: input.longhand_table,
+ underlying_longhands: input.longhands,
overlay: host.overlay_for_mutation(),
custom_underlying_values: &underlying_values,
custom_initial_values: &initial_values,
@@ -7259,6 +8270,27 @@ fn finish_animation_sample(
.into_iter()
.map(|(custom_name_id, value)| (custom_properties.name(custom_name_id).clone(), value))
.collect::<Vec<_>>();
+ // https://drafts.csswg.org/css-values-5/#cyclic-substitution-contexts
+ // NB: The substitution contexts of a cycle through an animation are marked cyclic like those of any other,
+ // where a property holding a value of its keyframes substitutes what it reads. What they read has to be
+ // looked at here, since each pass only substitutes the values the last one left.
+ let cycle_pseudo =
+ (input.pseudo_kind != crate::css::cascaded_properties::NO_PSEUDO_ELEMENT).then_some(input.pseudo_kind);
+ for name in engine.custom_properties_in_an_animated_cycle(node, cycle_pseudo) {
+ // SAFETY: The stores are null or live for the sample.
+ let inherited = unsafe {
+ input
+ .stores
+ .inheritance
+ .cast::<crate::css::custom_properties::CustomPropertyStore>()
+ .as_ref()
+ };
+ let value = registry.invalid_at_computed_value_time(&name, inherited);
+ match retained.iter_mut().find(|(animated, _)| *animated == name) {
+ Some((_, animated)) => *animated = value,
+ None => retained.push((name, value)),
+ }
+ }
// The element's own custom properties that read an animated one move with it, whether or
// not they resolved to what it inherits.
let pseudo =
@@ -7282,6 +8314,7 @@ fn finish_animation_sample(
result.custom_properties_trigger_restyle = engine.animated_custom_properties_trigger_restyle(
node,
pseudo,
+ &retained,
has_non_custom_property_animation,
uncached_interval_values_may_need_substitution,
input.custom_property_registration_generation,
@@ -7336,18 +8369,6 @@ pub(crate) fn sample_without_host(
AnimationSampleStep::Sampled(result) => return Ok(result),
AnimationSampleStep::Resolved(sample) => sample,
};
- if !sample.result.style_query_dependencies.is_null() {
- // SAFETY: The sample transferred the dependencies it resolved to its result.
- drop(unsafe {
- Box::from_raw(
- sample
- .result
- .style_query_dependencies
- .cast::<crate::css::custom_properties::StyleQueryDependencies>(),
- )
- });
- return Err(NeedsHost);
- }
let resolved = &sample.resolved;
let Some(length_contexts) = engine_length_contexts(input, engine, &sample) else {
return Err(NeedsHost);
@@ -7377,11 +8398,18 @@ impl AnimationSampleHost for EngineSampleHost<'_> {
}
}
-fn apply_post_compute_adjustments(
- longhand_table: &mut ComputedLonghandTable,
+/// What the post-compute adjustments of an element change.
+struct PostComputeAdjustedValues {
+ /// The adjusted longhands' computed values.
+ values: SmallVec<[(u16, StyleValueData); 5]>,
+ /// The longhands whose computed values are no longer important or inherited.
+ cleared_flags: SmallVec<[u16; 5]>,
+}
+
+fn post_compute_adjusted_values(
adjustment: &PostComputeAdjustment,
input_line_height_metrics: &FfiInputLineHeightMetrics,
-) -> u8 {
+) -> PostComputeAdjustedValues {
use crate::css::property_metadata::property_id as prop;
let transformation = adjustment.box_type_transformation;
@@ -7397,74 +8425,64 @@ fn apply_post_compute_adjustments(
} else {
display_after_box_type_transformation
};
- let adjusted_entry = |property_id, computed_kind, value| ComputedStoreEntry {
- property_id,
- data: initial_value_handle(property_id),
- source_slot: -1,
- has_style_sheet_context: false,
- inheritance_dependent: false,
- computed_data: None,
- computed_kind,
- value,
+ let mut adjusted = PostComputeAdjustedValues {
+ values: SmallVec::new(),
+ cleared_flags: SmallVec::new(),
};
- // An adjustment moves only a computed value. Whether the value depends on the parent stays
- // what the drive recorded for the specified value, as for a match-parent text-align a table
- // adjusts.
- let mut store = |entry: ComputedStoreEntry| store_computed_value(longhand_table, entry);
- let mut post_adjusted_longhands = 0;
- if transformation.set_float_none {
- post_adjusted_longhands |= POST_ADJUSTED_FLOAT;
- store(adjusted_entry(prop::FLOAT, COMPUTED_KIND_KEYWORD, keyword::NONE as f64));
- }
- if adjusted_display != adjustment.display_before {
- post_adjusted_longhands |= POST_ADJUSTED_DISPLAY;
- store(adjusted_entry(
- prop::DISPLAY,
- COMPUTED_KIND_DISPLAY,
- adjusted_display.encoded() as f64,
- ));
- }
- let line_height_changed = element_adjustment.set_line_height_normal || clamp_input_line_height;
- if line_height_changed {
- post_adjusted_longhands |= POST_ADJUSTED_LINE_HEIGHT;
- store(adjusted_entry(
- prop::LINE_HEIGHT,
- COMPUTED_KIND_KEYWORD,
- keyword::NORMAL as f64,
- ));
- }
- if element_adjustment.set_position_static {
- post_adjusted_longhands |= POST_ADJUSTED_POSITION;
- store(adjusted_entry(
- prop::POSITION,
- COMPUTED_KIND_KEYWORD,
- keyword::STATIC as f64,
- ));
- }
- if element_adjustment.changed_text_align {
- post_adjusted_longhands |= POST_ADJUSTED_TEXT_ALIGN;
- store(adjusted_entry(
- prop::TEXT_ALIGN,
- COMPUTED_KIND_KEYWORD,
- element_adjustment.text_align as f64,
- ));
- }
-
- let mut clear_adjusted_flags = |changed, property_id| {
+ let mut adjust = |changed: bool, property_id: u16, value: StyleValueData| {
if changed {
- longhand_table.set_important(property_id, false);
- longhand_table.set_inherited(property_id, false);
+ adjusted.values.push((property_id, value));
}
};
- clear_adjusted_flags(transformation.set_float_none, prop::FLOAT);
- clear_adjusted_flags(
- transformation.changed_display || element_adjustment.changed_display,
+ adjust(
+ transformation.set_float_none,
+ prop::FLOAT,
+ StyleValueData::Keyword { keyword: keyword::NONE },
+ );
+ adjust(
+ adjusted_display != adjustment.display_before,
prop::DISPLAY,
+ StyleValueData::Display {
+ raw: adjusted_display.encoded(),
+ },
+ );
+ let line_height_changed = element_adjustment.set_line_height_normal || clamp_input_line_height;
+ adjust(
+ line_height_changed,
+ prop::LINE_HEIGHT,
+ StyleValueData::Keyword {
+ keyword: keyword::NORMAL,
+ },
);
- clear_adjusted_flags(line_height_changed, prop::LINE_HEIGHT);
- clear_adjusted_flags(element_adjustment.set_position_static, prop::POSITION);
- clear_adjusted_flags(element_adjustment.changed_text_align, prop::TEXT_ALIGN);
- post_adjusted_longhands
+ adjust(
+ element_adjustment.set_position_static,
+ prop::POSITION,
+ StyleValueData::Keyword {
+ keyword: keyword::STATIC,
+ },
+ );
+ adjust(
+ element_adjustment.changed_text_align,
+ prop::TEXT_ALIGN,
+ StyleValueData::Keyword {
+ keyword: element_adjustment.text_align,
+ },
+ );
+ for (changed, property_id) in [
+ (transformation.set_float_none, prop::FLOAT),
+ (
+ transformation.changed_display || element_adjustment.changed_display,
+ prop::DISPLAY,
+ ),
+ (line_height_changed, prop::LINE_HEIGHT),
+ (element_adjustment.set_position_static, prop::POSITION),
+ (element_adjustment.changed_text_align, prop::TEXT_ALIGN),
+ ] {
+ if changed {
+ adjusted.cleared_flags.push(property_id);
+ }
+ }
+ adjusted
}
fn property_affects_font_metrics(property_id: u16) -> bool {
@@ -7523,7 +8541,8 @@ pub(crate) fn expand_shorthands_with<Sink>(
// https://drafts.csswg.org/css-values-5/#pending-substitution-value
// Ensure we keep the longhand around until it can be resolved.
sink(property_id, data, has_style_sheet_context);
- let pending = RetainedStyleValueData::from_arc(std::sync::Arc::new(StyleValueData::PendingSubstitution {
+ let pending = RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::PendingSubstitution {
+ original_shorthand: property_id,
original_shorthand_value: data.clone(),
}));
for &longhand in longhands_for_shorthand(property_id) {
@@ -7532,10 +8551,10 @@ pub(crate) fn expand_shorthands_with<Sink>(
return;
}
- if let StyleValueData::Shorthand {
- sub_properties, values, ..
- } = value
- {
+ if let StyleValueData::Shorthand(shorthand_payload) = value {
+ let ShorthandPayload {
+ sub_properties, values, ..
+ } = &**shorthand_payload;
for (&sub_property, sub_value) in sub_properties.as_slice().iter().zip(values.as_slice()) {
expand_shorthands_with(sub_property, sub_value, false, sink);
}
@@ -7584,7 +8603,7 @@ fn expand_shorthands(property_id: u16, data: &RetainedStyleValueData) -> Shortha
#[unsafe(no_mangle)]
pub extern "C" fn rust_expand_property_shorthands(
property_id: u16,
- data: crate::css::ffi_support::ArcRef<'_, StyleValueData>,
+ data: crate::css::style_value_arc::StyleValueRef<'_>,
) -> FfiShorthandExpansion {
let data = RetainedStyleValueData::from_arc(data.to_arc());
let expansion = Box::new(expand_shorthands(property_id, &data));
@@ -7602,1948 +8621,84 @@ pub extern "C" fn rust_shorthand_expansion_destroy(storage: OwnedBox<ShorthandEx
drop(storage);
}
-pub(crate) fn display_is_none(raw: u32) -> bool {
- FfiDisplay::from_raw(raw).is_none()
-}
+mod adjustments;
+pub(crate) use adjustments::*;
-/// The element facts the box type transformation needs, marshalled by the C++
-/// side. The parent display is the first non-`display: contents` ancestor's.
-#[repr(C)]
-#[derive(Clone, Copy)]
-pub struct FfiBoxTypeTransformationInput {
- pub display: FfiDisplay,
- /// Computed position and float keywords.
- pub position: u16,
- pub float_value: u16,
- pub is_br_element: bool,
- pub is_document_element: bool,
- pub is_mathml_element: bool,
- pub is_mathml_mtable: bool,
- pub is_mathml_mtr: bool,
- pub is_mathml_mtd: bool,
- pub has_parent_display: bool,
- pub parent_display: FfiDisplay,
- /// The computed writing-mode of the element and of the box it would be the child of.
- pub writing_mode: u8,
- pub parent_writing_mode: u8,
- /// Whether the element is an SVG element, whose boxes are not laid out by the CSS display types.
- pub is_svg_element: bool,
- pub is_wbr_element: bool,
- pub disallow_display_contents: bool,
- pub rewrite_inline_flow: bool,
- pub is_button_element: bool,
- pub force_line_height_normal: bool,
- pub check_input_line_height: bool,
- pub hide_audio_without_controls: bool,
- pub is_table_element: bool,
- pub force_position_static: bool,
- pub force_symbol_display_inline: bool,
- pub webkit_box_layout_transformation_applies: bool,
-}
-
-/// Whether element-specific adjustments apply to the subject being computed.
-#[repr(C)]
-#[derive(Clone, Copy, PartialEq, Eq)]
-pub enum FfiStyleAdjustmentTarget {
- Element,
- PseudoElement,
-}
-
-/// Build the shared adjustment inputs from element facts. The caller supplies the first
-/// non-`display: contents` ancestor's display, using live styles on the C++ path.
-pub(crate) fn rust_box_type_transformation_input(
- facts: u32,
- target: FfiStyleAdjustmentTarget,
- has_parent_display: bool,
- parent_display: FfiDisplay,
- parent_writing_mode: u8,
-) -> FfiBoxTypeTransformationInput {
- use crate::css::style::bridge::element_adjustment_fact as fact;
-
- let has = |bit| facts & bit != 0;
- let adjust_element = target == FfiStyleAdjustmentTarget::Element;
- FfiBoxTypeTransformationInput {
- display: crate::css::display::FfiDisplay::inline(),
- position: keyword::STATIC,
- float_value: keyword::NONE,
- is_br_element: adjust_element && has(fact::IS_BR),
- is_document_element: adjust_element && has(fact::IS_DOCUMENT_ELEMENT),
- is_mathml_element: has(fact::IS_MATHML),
- is_mathml_mtable: has(fact::IS_MATHML_MTABLE),
- is_mathml_mtr: has(fact::IS_MATHML_MTR),
- is_mathml_mtd: has(fact::IS_MATHML_MTD),
- has_parent_display,
- parent_display,
- writing_mode: crate::css::css_enums::writing_mode::HORIZONTAL_TB,
- parent_writing_mode,
- is_svg_element: has(fact::IS_SVG_ELEMENT),
- is_wbr_element: adjust_element && has(fact::IS_WBR),
- disallow_display_contents: adjust_element && has(fact::DISALLOW_DISPLAY_CONTENTS),
- rewrite_inline_flow: adjust_element && has(fact::REWRITE_INLINE_FLOW),
- is_button_element: adjust_element && has(fact::IS_BUTTON),
- force_line_height_normal: adjust_element && has(fact::FORCE_LINE_HEIGHT_NORMAL),
- check_input_line_height: adjust_element && has(fact::CHECK_INPUT_LINE_HEIGHT),
- hide_audio_without_controls: adjust_element && has(fact::HIDE_AUDIO_WITHOUT_CONTROLS),
- is_table_element: adjust_element && has(fact::IS_TABLE),
- force_position_static: adjust_element && has(fact::FORCE_POSITION_STATIC),
- force_symbol_display_inline: adjust_element && has(fact::FORCE_SYMBOL_DISPLAY_INLINE),
- webkit_box_layout_transformation_applies: false,
- }
-}
-
-/// The box-type transformation input of a style target's animated composition, which the host
-/// samples over the record the engine holds for it: the same input the engine drives the record
-/// against, read from the element's published facts and its parent's record. A target the engine
-/// does not know is transformed with no facts and no parent display.
+/// The value of `property` the element whose style is `record` reads, with what `overlay` composes over it where
+/// `with_animations` asks for that, and which source it is.
+///
+/// # Safety
+/// `record` must be a style record the caller holds a reference to, and `overlay` null or live.
#[unsafe(no_mangle)]
-pub extern "C" fn rust_animated_box_type_transformation_input(
- host: &crate::render_state::DocumentHost,
- read: &crate::render_state::BegunRead,
- node: u32,
- pseudo_kind: u8,
-) -> FfiBoxTypeTransformationInput {
- match crate::css::style::tree::StyleNodeID::from_raw(node) {
- Some(node) => crate::css::style::engine_calls::with_engine(read, host, |engine| {
- engine.composition_box_type_transformation_input(node, pseudo_kind)
- }),
- None => rust_box_type_transformation_input(
- 0,
- FfiStyleAdjustmentTarget::Element,
- false,
- FfiDisplay::block(),
- crate::css::css_enums::writing_mode::HORIZONTAL_TB,
- ),
- }
-}
-
-/// Result of the box type transformation: whether float must be reset to none,
-/// and the possibly replaced display.
-#[repr(C)]
-#[derive(Clone, Copy)]
-pub struct FfiBoxTypeTransformation {
- pub set_float_none: bool,
- pub changed_display: bool,
- pub display: FfiDisplay,
-}
-
-#[repr(C)]
-#[derive(Clone, Copy)]
-pub struct FfiElementStyleAdjustment {
- pub changed_display: bool,
- pub display: FfiDisplay,
- pub set_line_height_normal: bool,
- pub check_input_line_height: bool,
- pub set_position_static: bool,
- pub changed_text_align: bool,
- pub text_align: u16,
-}
-
-/// The automatic box type transformation and element-specific adjustment,
-/// sequenced as they are in the normal property computation path.
-#[repr(C)]
-#[derive(Clone, Copy)]
-pub struct FfiElementStyleAdjustments {
- pub box_type: FfiBoxTypeTransformation,
- pub element_style: FfiElementStyleAdjustment,
-}
-
-#[repr(C)]
-#[derive(Clone, Copy)]
-pub struct FfiInputLineHeightMetrics {
- pub current_line_height: f64,
- pub minimum_line_height: f64,
-}
-
-fn should_clamp_input_line_height(adjustment: &FfiElementStyleAdjustment, metrics: &FfiInputLineHeightMetrics) -> bool {
- adjustment.check_input_line_height && metrics.current_line_height < metrics.minimum_line_height
-}
-
-fn adjust_element_style(
- input: &FfiBoxTypeTransformationInput,
- display: FfiDisplay,
- text_align: u16,
-) -> FfiElementStyleAdjustment {
- let mut new_display = display;
- if input.is_wbr_element && display.is_contents() {
- new_display = FfiDisplay::none();
- }
- if input.disallow_display_contents && new_display.is_contents() {
- new_display = FfiDisplay::none();
- }
- if input.rewrite_inline_flow && new_display.is_inline_outside() && new_display.inside == display_inside::FLOW {
- new_display = FfiDisplay::inline_block();
- }
- if input.is_button_element
- && !(new_display.is_flex_inside()
- || new_display.is_grid_inside()
- || new_display.is_none()
- || new_display.is_contents())
- {
- new_display = if new_display.is_inline_outside() {
- FfiDisplay::inline_block()
- } else {
- FfiDisplay::flow_root()
- };
- }
- if input.is_br_element {
- new_display = if new_display.is_contents() {
- FfiDisplay::none()
- } else if new_display.is_none() {
- new_display
- } else {
- FfiDisplay::inline()
- };
- }
- if input.hide_audio_without_controls {
- new_display = FfiDisplay::none();
- }
- if input.force_symbol_display_inline {
- new_display = FfiDisplay::inline();
- }
-
- let new_text_align = if input.is_table_element
- && matches!(
- text_align,
- keyword::_LIBWEB_LEFT | keyword::_LIBWEB_CENTER | keyword::_LIBWEB_RIGHT
- ) {
- keyword::START
- } else {
- text_align
+pub unsafe extern "C" fn rust_style_record_effective_value(
+ record: *const c_void,
+ overlay: *const c_void,
+ property: u16,
+ with_animations: bool,
+) -> crate::css::computed_longhand_table::FfiEffectiveLonghandValue {
+ // SAFETY: Guaranteed by the caller.
+ let (longhands, overlay) = unsafe {
+ (
+ crate::css::style::ViewLonghands::of_raw_record(record),
+ overlay.cast::<AnimatedOverlay>().as_ref(),
+ )
};
-
- FfiElementStyleAdjustment {
- changed_display: new_display != display,
- display: new_display,
- set_line_height_normal: input.force_line_height_normal,
- check_input_line_height: input.check_input_line_height,
- set_position_static: input.force_position_static,
- changed_text_align: new_text_align != text_align,
- text_align: new_text_align,
+ let (value, source) = longhands.effective_value_and_source(overlay, property, with_animations);
+ crate::css::computed_longhand_table::FfiEffectiveLonghandValue {
+ value: value.pointer().cast(),
+ source,
}
}
-fn compute_element_style_adjustments(
- input: &FfiBoxTypeTransformationInput,
- text_align: u16,
-) -> FfiElementStyleAdjustments {
- let box_type = transform_box_type(input);
- let display = if box_type.changed_display {
- box_type.display
- } else {
- input.display
- };
- let element_style = adjust_element_style(input, display, text_align);
- FfiElementStyleAdjustments {
- box_type,
- element_style,
- }
+/// The computed value of `property` that the style `record` holds, or null, borrowed while the
+/// record lives.
+///
+/// # Safety
+/// `record` must be a style record the caller holds a reference to.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_style_record_longhand(record: *const c_void, property: u16) -> *const c_void {
+ // SAFETY: Guaranteed by the caller.
+ unsafe { crate::css::style::ViewLonghands::of_raw_record(record) }
+ .handle(property)
+ .map_or(std::ptr::null(), |value| value.pointer().cast())
}
-// NB: css-display-3 also defines inlinification, but nothing triggers it yet (the only
-// candidate is the ruby containment FIXME below), so only blockification is modelled.
-enum BoxTypeTransformation {
- None,
- Blockify,
+/// One bit per longhand of the style `record`: whether its value is important.
+///
+/// # Safety
+/// `record` must be a style record the caller holds a reference to.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_style_record_importance_bits(record: *const c_void) -> *const u8 {
+ // SAFETY: Guaranteed by the caller.
+ unsafe { crate::css::style::ViewLonghands::of_raw_record(record) }
+ .importance_bits()
+ .as_ptr()
}
-fn required_box_type_transformation(input: &FfiBoxTypeTransformationInput) -> BoxTypeTransformation {
- // NOTE: We never blockify <br> elements. They are always inline.
- // There is currently no way to express in CSS how a <br> element really behaves.
- // Spec issue: https://github.com/whatwg/html/issues/2291
- if input.is_br_element {
- return BoxTypeTransformation::None;
- }
-
- // Absolute positioning or floating an element blockifies the box's display type. [CSS2]
- if input.position == keyword::ABSOLUTE || input.position == keyword::FIXED || input.float_value != keyword::NONE {
- return BoxTypeTransformation::Blockify;
- }
-
- // FIXME: Containment in a ruby container inlinifies the box's display type, as described in [CSS-RUBY-1].
-
- // A parent with a grid or flex display value blockifies the box's display type. [CSS-GRID-1] [CSS-FLEXBOX-1]
- // NB: The C++ side supplies the first ancestor that is not `display: contents`; for a
- // pseudo-element that climb starts at the originating element itself.
- if input.has_parent_display && (input.parent_display.is_grid_inside() || input.parent_display.is_flex_inside()) {
- return BoxTypeTransformation::Blockify;
- }
-
- BoxTypeTransformation::None
+/// What the computation of the style `record` settled beside its values, which the host starts an update of the
+/// element's style from.
+///
+/// # Safety
+/// `record` must be a style record the caller holds a reference to.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_style_record_metadata(
+ record: *const c_void,
+) -> crate::css::computed_longhand_table::FfiComputedStyleMetadata {
+ // SAFETY: Guaranteed by the caller.
+ unsafe { crate::css::style::ViewLonghands::of_raw_record(record) }.metadata()
}
-/// https://drafts.csswg.org/css-display/#transformations
-/// 2.7. Automatic Box Type Transformations
-fn transform_box_type(input: &FfiBoxTypeTransformationInput) -> FfiBoxTypeTransformation {
- let display_before_transformation = input.display;
- let mut display = display_before_transformation;
+/// Computes the font-weight property from its absolutized value.
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_compute_font_weight(
+ absolutized_value: &StyleValueData,
+ inherited_font_weight: f64,
+) -> FfiComputedNumber {
+ compute_font_weight(absolutized_value, inherited_font_weight)
+}
- // https://drafts.csswg.org/css-overflow-4/#webkit-line-clamp
- // If the specified value of the 'display' property is '-webkit-box', the computed value becomes 'flow-root'
- // and the box establishes a BFC.
- if input.webkit_box_layout_transformation_applies && display.is_webkit_box_inside() {
- display = if display.is_inline_outside() {
- FfiDisplay::inline_block()
- } else {
- FfiDisplay::flow_root()
- };
- }
- let unchanged = |set_float_none: bool| FfiBoxTypeTransformation {
- set_float_none,
- changed_display: display != display_before_transformation,
- display,
- };
+#[cfg(test)]
+pub(crate) mod ffi_test_stubs;
- // Some layout effects require blockification or inlinification of the box type,
- // which sets the box's computed outer display type to block or inline (respectively).
- // (This has no effect on display types that generate no box at all, such as none or contents.)
- if display.is_none() || (display.is_contents() && !input.is_document_element) {
- return unchanged(false);
- }
-
- // https://drafts.csswg.org/css-display/#root
- // The root element's display type is always blockified, and its principal box always establishes an independent formatting context.
- if input.is_document_element && !display.is_block_outside() {
- return FfiBoxTypeTransformation {
- set_float_none: false,
- changed_display: true,
- display: FfiDisplay::block(),
- };
- }
-
- let mut new_display = display;
-
- if display.is_math_inside() {
- // https://w3c.github.io/mathml-core/#new-display-math-value
- // For elements that are not MathML elements, if the specified value of display is inline math or block math
- // then the computed value is block flow and inline flow respectively.
- if !input.is_mathml_element {
- new_display = FfiDisplay::outside_and_inside(display.outside, display_inside::FLOW, display.list_item);
- }
- // For the mtable element the computed value is block table and inline table respectively.
- else if input.is_mathml_mtable {
- new_display = FfiDisplay::outside_and_inside(display.outside, display_inside::TABLE, display.list_item);
- }
- // For the mtr element, the computed value is table-row.
- else if input.is_mathml_mtr {
- new_display = FfiDisplay::internal(display_internal::TABLE_ROW);
- }
- // For the mtd element, the computed value is table-cell.
- else if input.is_mathml_mtd {
- new_display = FfiDisplay::internal(display_internal::TABLE_CELL);
- }
- }
-
- // https://www.w3.org/TR/CSS2/visuren.html#dis-pos-flo
- // If 'position' has the value 'absolute' or 'fixed', [...] 'float' is set to 'none'
- let set_float_none = input.position == keyword::ABSOLUTE || input.position == keyword::FIXED;
-
- match required_box_type_transformation(input) {
- BoxTypeTransformation::None => {}
- BoxTypeTransformation::Blockify => {
- if display.is_block_outside() {
- return unchanged(set_float_none);
- }
- // If a layout-internal box is blockified, its inner display type converts to flow so that it becomes a block container.
- if display.is_internal() {
- new_display = FfiDisplay::block();
- } else {
- assert!(display.is_outside_and_inside());
-
- // For legacy reasons, if an inline block box (inline flow-root) is blockified, it becomes a block box (losing its flow-root nature).
- // For consistency, a run-in flow-root box also blockifies to a block box.
- if display.is_inline_block() {
- new_display =
- FfiDisplay::outside_and_inside(display_outside::BLOCK, display_inside::FLOW, display.list_item);
- } else {
- new_display =
- FfiDisplay::outside_and_inside(display_outside::BLOCK, display.inside, display.list_item);
- }
- }
- }
- }
-
- // https://drafts.csswg.org/css-writing-modes-4/#block-flow
- // If a box has a different 'writing-mode' value than its parent box (i.e. nearest ancestor without
- // 'display: contents'):
- if input.has_parent_display
- && input.writing_mode != input.parent_writing_mode
- && !input.is_svg_element
- && new_display.is_outside_and_inside()
- {
- // - If the box would otherwise become an in-flow box with a computed 'display' of 'inline', its 'display'
- // computes instead to 'inline-block'.
- // - If the box is a block container, then it establishes an independent block formatting context.
- // - More generally, if its specified inner display type is 'flow', then its computed inner display type
- // becomes 'flow-root'.
- // NB: Layout makes a block container with another writing mode than its parent box establish an
- // independent formatting context, so only the inline box's display changes here.
- if new_display.is_flow_inside() && new_display.is_inline_outside() {
- new_display = FfiDisplay::outside_and_inside(
- new_display.outside,
- crate::css::css_enums::display_inside::FLOW_ROOT,
- new_display.list_item,
- );
- }
- }
-
- FfiBoxTypeTransformation {
- set_float_none,
- changed_display: new_display != display_before_transformation,
- display: new_display,
- }
-}
-
-/// Result of resolving the effective overflow pair: each axis' possibly
-/// replaced computed keyword.
-#[repr(C)]
-pub struct FfiEffectiveOverflow {
- pub changed_x: bool,
- pub x_keyword: u16,
- pub changed_y: bool,
- pub y_keyword: u16,
-}
-
-/// https://www.w3.org/TR/css-overflow-3/#overflow-control
-/// The visible/clip values of overflow compute to auto/hidden (respectively) if one of overflow-x or
-/// overflow-y is neither visible nor clip.
-fn resolve_effective_overflow_keywords(overflow_x: u16, overflow_y: u16) -> FfiEffectiveOverflow {
- let is_visible_or_clip = |keyword: u16| keyword == keyword::VISIBLE || keyword == keyword::CLIP;
- let mut result = FfiEffectiveOverflow {
- changed_x: false,
- x_keyword: overflow_x,
- changed_y: false,
- y_keyword: overflow_y,
- };
- if !is_visible_or_clip(overflow_x) || !is_visible_or_clip(overflow_y) {
- if overflow_x == keyword::VISIBLE {
- result.changed_x = true;
- result.x_keyword = keyword::AUTO;
- }
- if overflow_x == keyword::CLIP {
- result.changed_x = true;
- result.x_keyword = keyword::HIDDEN;
- }
- if overflow_y == keyword::VISIBLE {
- result.changed_y = true;
- result.y_keyword = keyword::AUTO;
- }
- if overflow_y == keyword::CLIP {
- result.changed_y = true;
- result.y_keyword = keyword::HIDDEN;
- }
- }
- result
-}
-
-// https://drafts.csswg.org/css-color-adjust-1/#determine-the-used-color-scheme
-fn resolve_effective_color_scheme(
- schemes: &[u8],
- preferred_scheme: u8,
- document_supported_schemes: Option<&[u8]>,
-) -> u8 {
- const AUTO: u8 = 0;
- const LIGHT: u8 = 2;
-
- // To determine the used color scheme of an element:
-
- // 1. If the user’s preferred color scheme, as indicated by the prefers-color-scheme media feature,
- // is present among the listed color schemes, and is supported by the user agent,
- // that’s the element’s used color scheme.
- if preferred_scheme != AUTO && schemes.contains(&preferred_scheme) {
- return preferred_scheme;
- }
-
- // 2. Otherwise, if the user has indicated an overriding preference for their chosen color scheme,
- // and the only keyword is not present in color-scheme for the element,
- // the user agent must override the color scheme with the user’s preferred color scheme.
- // See § 2.3 Overriding the Color Scheme.
- // FIXME: We don't currently support setting an "overriding preference" for color schemes.
-
- // 3. Otherwise, if the user agent supports at least one of the listed color schemes,
- // the used color scheme is the first supported color scheme in the list.
- if let Some(first_supported) = schemes.iter().find(|scheme| **scheme != AUTO) {
- return *first_supported;
- }
-
- // 4. Otherwise, the used color scheme is the browser default. (Same as normal.)
- // `normal` indicates that the element supports the page’s supported color schemes, if they are set
- if let Some(document_supported_schemes) = document_supported_schemes {
- if preferred_scheme != AUTO && document_supported_schemes.contains(&preferred_scheme) {
- return preferred_scheme;
- }
- if let Some(first_supported) = document_supported_schemes.iter().find(|scheme| **scheme != AUTO) {
- return *first_supported;
- }
- }
-
- LIGHT
-}
-
-/// Resolves the used color scheme for a value that required C++ computation.
-///
-/// # Safety
-/// `input` must point at valid document inputs for the duration of the call.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_resolve_effective_color_scheme(
- value: &StyleValueData,
- input: &FfiEffectiveColorSchemeInput,
-) -> u8 {
- let StyleValueData::ColorScheme { scheme_codes, .. } = value else {
- unreachable!("computed color-scheme must have color-scheme data");
- };
- resolve_effective_color_scheme(scheme_codes.as_slice(), input.preferred_color_scheme, unsafe {
- input.document_supported_schemes()
- })
-}
-
-/// Result of the text-align adjustment: the replacement keyword and whether it
-/// counts as inherited.
-#[repr(C)]
-pub struct FfiTextAlignAdjustment {
- pub changed: bool,
- pub keyword: u16,
- pub inherited: bool,
-}
-
-/// Decides the text-align adjustments applied after computation. The parent
-/// arguments are only read when `has_parent_with_computed_values` is set.
-fn compute_text_align_adjustment(
- text_align: u16,
- is_th_element: bool,
- has_parent_with_computed_values: bool,
- parent_text_align: u16,
- parent_direction_is_ltr: bool,
-) -> FfiTextAlignAdjustment {
- let unchanged = FfiTextAlignAdjustment {
- changed: false,
- keyword: text_align,
- inherited: false,
- };
- let replace = |keyword: u16| FfiTextAlignAdjustment {
- changed: true,
- keyword,
- inherited: false,
- };
-
- // https://drafts.csswg.org/css-text-4/#valdef-text-align-match-parent
- // This value behaves the same as inherit (computes to its parent's computed value) except that an inherited
- // value of start or end is interpreted against the parent's direction value and results in a computed value of
- // either left or right. Computes to start when specified on the root element.
- if text_align == keyword::MATCH_PARENT {
- if !has_parent_with_computed_values {
- return replace(keyword::START);
- }
- return match parent_text_align {
- keyword::START if parent_direction_is_ltr => replace(keyword::LEFT),
- keyword::START => replace(keyword::RIGHT),
- keyword::END if parent_direction_is_ltr => replace(keyword::RIGHT),
- keyword::END => replace(keyword::LEFT),
- _ => replace(parent_text_align),
- };
- }
-
- // AD-HOC: The -libweb-inherit-or-center style defaults to centering, unless the parent element has a
- // non-initial computed text-align value. This is used to support the ad-hoc default <th>
- // text-align behavior.
- if text_align == keyword::_LIBWEB_INHERIT_OR_CENTER && is_th_element {
- if has_parent_with_computed_values && parent_text_align != keyword::START {
- return FfiTextAlignAdjustment {
- changed: true,
- keyword: parent_text_align,
- inherited: true,
- };
- }
- return replace(keyword::CENTER);
- }
-
- unchanged
-}
-
-/// Applies the box type transformation and element adjustments to an animated composition, in its overlay, over a base
-/// that stays as computed: what the transformation changes about the animated display, position, float, line-height and
-/// overflow is what the overlay holds.
-fn finalize_animated_box_type(
- mut box_type: FfiBoxTypeTransformationInput,
- longhand_table: &ComputedLonghandTable,
- overlay: &mut AnimatedOverlay,
- input_line_height_metrics: Option<&FfiInputLineHeightMetrics>,
-) {
- use crate::css::property_metadata::property_id as prop;
-
- let view = Some(&*overlay);
- let text_align = effective_keyword(longhand_table, view, prop::TEXT_ALIGN);
- let animated_display_missing = overlay.get(prop::DISPLAY).is_none();
- box_type.display = if animated_display_missing {
- FfiDisplay::from_raw(longhand_table.display_before_box_type_transformation())
- } else {
- effective_display(longhand_table, view)
- };
- box_type.position = effective_keyword(longhand_table, view, prop::POSITION);
- box_type.float_value = effective_keyword(longhand_table, view, prop::FLOAT);
- box_type.writing_mode = effective_writing_mode(longhand_table, view);
- box_type.webkit_box_layout_transformation_applies = webkit_box_layout_transformation_applies(longhand_table, view);
- // An axis the overlay does not animate is adjusted from its keyword before the base adjusted it against the other
- // axis, which the overlay may animate out of that adjustment.
- let before = longhand_table.overflow_before_adjustment();
- let unadjusted = |property: u16, axis: usize| match before {
- Some(before) if overlay.get(property).is_none() => before[axis],
- _ => effective_keyword(longhand_table, view, property),
- };
- let overflow =
- resolve_effective_overflow_keywords(unadjusted(prop::OVERFLOW_X, 0), unadjusted(prop::OVERFLOW_Y, 1));
- let adjustments = compute_element_style_adjustments(&box_type, text_align);
-
- // A value the overlay animates keeps its animation's place; one it does not is adjusted over the base value.
- let mut adjust = |property_id: u16, keyword_or_display: StyleValueData| {
- let value = retained_new(keyword_or_display);
- let (effective, _) = longhand_table.effective_value_handle(Some(&*overlay), property_id, true);
- if effective.data() == value.data() {
- return;
- }
- match overlay
- .get(property_id)
- .map(|entry| (entry.inherited, entry.result_of_transition))
- {
- Some((inherited, result_of_transition)) => {
- overlay.set_owned(property_id, value, inherited, result_of_transition);
- }
- None if property_id == prop::OVERFLOW_X || property_id == prop::OVERFLOW_Y => {
- overlay.set_adjusted(property_id, value);
- }
- None => overlay.set_owned(property_id, value, false, false),
- }
- };
- let display = |display: FfiDisplay| StyleValueData::Display { raw: display.encoded() };
- let keyword = |keyword: u16| StyleValueData::Keyword { keyword };
- if animated_display_missing {
- adjust(prop::DISPLAY, display(box_type.display));
- }
- if adjustments.box_type.set_float_none {
- adjust(prop::FLOAT, keyword(keyword::NONE));
- }
- if adjustments.box_type.changed_display {
- adjust(prop::DISPLAY, display(adjustments.box_type.display));
- }
- let element_style = adjustments.element_style;
- if element_style.changed_display {
- adjust(prop::DISPLAY, display(element_style.display));
- }
- if element_style.set_position_static {
- adjust(prop::POSITION, keyword(keyword::STATIC));
- }
- if element_style.changed_text_align {
- adjust(prop::TEXT_ALIGN, keyword(element_style.text_align));
- }
- if element_style.set_line_height_normal
- || (element_style.check_input_line_height
- && should_clamp_input_line_height(
- &element_style,
- input_line_height_metrics.expect("input line-height adjustment requires font metrics"),
- ))
- {
- adjust(prop::LINE_HEIGHT, keyword(keyword::NORMAL));
- }
- adjust(prop::OVERFLOW_X, keyword(overflow.x_keyword));
- adjust(prop::OVERFLOW_Y, keyword(overflow.y_keyword));
-}
-
-/// Applies the box type transformation and element adjustments to the animated composition `animated_overlay` holds
-/// over `longhand_table`.
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_finalize_animated_box_type(
- box_type: FfiBoxTypeTransformationInput,
- longhand_table: &ComputedLonghandTable,
- animated_overlay: &mut AnimatedOverlay,
- input_line_height_metrics: Option<&FfiInputLineHeightMetrics>,
-) {
- finalize_animated_box_type(box_type, longhand_table, animated_overlay, input_line_height_metrics);
-}
-
-/// Computes the font-weight property from its absolutized value.
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_compute_font_weight(
- absolutized_value: &StyleValueData,
- inherited_font_weight: f64,
-) -> FfiComputedNumber {
- compute_font_weight(absolutized_value, inherited_font_weight)
-}
-
-// The standalone cargo test binary has no C++ side, so release callbacks are
-// stubbed out here.
#[cfg(test)]
-pub(crate) mod ffi_test_stubs {
- use std::cell::Cell;
- use std::ffi::c_void;
-
- use crate::css::style::reaction_application::{HostElement, HostStyleReactionApplication};
-
- thread_local! {
- static FONT_CASCADE_LIST_UNREFS: Cell<usize> = const { Cell::new(0) };
- }
-
- pub(crate) fn font_cascade_list_unref_count() -> usize {
- FONT_CASCADE_LIST_UNREFS.get()
- }
-
- #[unsafe(no_mangle)]
- extern "C" fn ladybird_utf16_fly_string_unref(_raw: usize) {}
- #[unsafe(no_mangle)]
- extern "C" fn web_css_custom_property_data_reference(_data: *const c_void) {}
- #[unsafe(no_mangle)]
- extern "C" fn web_css_font_face_snapshot_reference(_snapshot: *const c_void) {}
- #[unsafe(no_mangle)]
- extern "C" fn web_css_font_cascade_memo_reference(_memo: *const c_void) {}
- #[unsafe(no_mangle)]
- extern "C" fn web_css_font_face_snapshot_unreference(_snapshot: *const c_void) {}
- #[unsafe(no_mangle)]
- extern "C" fn web_css_font_cascade_memo_unreference(_memo: *const c_void) {}
- #[unsafe(no_mangle)]
- extern "C" fn web_css_resolve_font(
- _memo: *const c_void,
- _snapshot: *const c_void,
- _request: crate::css::style::bridge::FfiFontResolutionRequest,
- ) -> crate::css::style::bridge::FfiResolvedFont {
- crate::css::style::bridge::FfiResolvedFont::default()
- }
- #[unsafe(no_mangle)]
- extern "C" fn web_css_resolve_font_for_fork(
- _memo: *const c_void,
- _snapshot: *const c_void,
- _request: crate::css::style::bridge::FfiFontResolutionRequest,
- ) -> crate::css::style::bridge::FfiResolvedFont {
- crate::css::style::bridge::FfiResolvedFont::default()
- }
- #[unsafe(no_mangle)]
- extern "C" fn web_css_custom_property_data_unreference(_data: *const c_void) {}
- #[unsafe(no_mangle)]
- extern "C" fn web_css_style_reaction_element(
- _application: *mut HostStyleReactionApplication,
- _node: u32,
- ) -> crate::css::style::reaction_application::FfiReactionElement {
- unreachable!("no unit test applies style reactions");
- }
- #[unsafe(no_mangle)]
- extern "C" fn web_css_parent_style_has_animated_values(_element: *mut HostElement) -> bool {
- unreachable!("no unit test applies style reactions");
- }
- #[unsafe(no_mangle)]
- extern "C" fn web_css_engine_record_environment(
- _application: *mut HostStyleReactionApplication,
- _element: *mut HostElement,
- _style_record: u64,
- ) -> crate::css::style::reaction_application::FfiRecordEnvironment {
- unreachable!("no unit test applies style reactions");
- }
- #[unsafe(no_mangle)]
- extern "C" fn web_css_record_derived_element_style_input(
- _application: *mut HostStyleReactionApplication,
- _node: u32,
- _reaction: u8,
- _groups: u8,
- ) {
- unreachable!("no unit test applies style reactions");
- }
- #[unsafe(no_mangle)]
- extern "C" fn web_css_take_style_transaction(
- _application: *mut HostStyleReactionApplication,
- _flown: bool,
- ) -> crate::css::style::reaction_application::FfiTakenStyleTransaction {
- unreachable!("no unit test applies style reactions");
- }
- #[unsafe(no_mangle)]
- extern "C" fn web_css_has_pending_style_transaction(_application: *mut HostStyleReactionApplication) -> bool {
- unreachable!("no unit test applies style reactions");
- }
- #[unsafe(no_mangle)]
- extern "C" fn web_css_note_style_update_has_reactions(_application: *mut HostStyleReactionApplication) {
- unreachable!("no unit test applies style reactions");
- }
- #[unsafe(no_mangle)]
- extern "C" fn web_css_sample_animations_for_style_update(_application: *mut HostStyleReactionApplication) {
- unreachable!("no unit test applies style reactions");
- }
- #[unsafe(no_mangle)]
- extern "C" fn web_css_begin_style_update_pass(_application: *mut HostStyleReactionApplication, _first: bool) {
- unreachable!("no unit test applies style reactions");
- }
- #[unsafe(no_mangle)]
- extern "C" fn web_css_style_inheritance_parent(
- _application: *mut HostStyleReactionApplication,
- _element: *mut HostElement,
- ) -> crate::css::style::reaction_application::FfiReactionElement {
- unreachable!("no unit test applies style reactions");
- }
- #[unsafe(no_mangle)]
- extern "C" fn web_css_apply_targeted_style_reaction(
- _application: *mut HostStyleReactionApplication,
- _element: *mut HostElement,
- _installation: *const crate::css::style::reaction_application::FfiRecordInstallation,
- _descendant_style_recompute_needed: bool,
- ) -> crate::css::style::reaction_application::FfiTargetedStyleReaction {
- unreachable!("no unit test applies style reactions");
- }
- #[unsafe(no_mangle)]
- extern "C" fn web_css_republish_moved_environment(
- _application: *mut HostStyleReactionApplication,
- _node: u32,
- _style_record: u64,
- _replaced: u64,
- _new_inheritable: *const c_void,
- ) {
- unreachable!("no unit test applies style reactions");
- }
- #[unsafe(no_mangle)]
- extern "C" fn web_css_rebuild_custom_property_environment(
- _application: *mut HostStyleReactionApplication,
- _node: u32,
- _new_inheritable: *const c_void,
- ) {
- unreachable!("no unit test applies style reactions");
- }
- #[unsafe(no_mangle)]
- extern "C" fn web_css_apply_style_reaction(
- _application: *mut HostStyleReactionApplication,
- _element: *mut HostElement,
- _reaction: u8,
- _installation: *const crate::css::style::reaction_application::FfiRecordInstallation,
- ) {
- unreachable!("no unit test applies style reactions");
- }
- #[unsafe(no_mangle)]
- extern "C" fn ladybird_utf16_string_unref(_raw: usize) {}
- #[unsafe(no_mangle)]
- extern "C" fn ladybird_utf16_string_create_uninitialized(_length: usize, _has_latin1_storage: bool) -> usize {
- unreachable!("no unit test makes a string the host owns");
- }
- #[unsafe(no_mangle)]
- unsafe extern "C" fn ladybird_utf16_fly_string_from_utf8(data: *const u8, length: usize) -> usize {
- let bytes = unsafe { ak::slice_from_raw_parts(data, length) };
- let units = std::str::from_utf8(bytes).unwrap().encode_utf16().collect::<Vec<_>>();
- unsafe { ladybird_utf16_fly_string_from_utf16(units.as_ptr(), units.len()) }
- }
- #[unsafe(no_mangle)]
- unsafe extern "C" fn ladybird_utf16_fly_string_from_utf16(data: *const u16, length: usize) -> usize {
- // Keep a process-wide test atom table with AK's header layout so worker-parsed
- // names remain alive after the worker exits.
- #[repr(C, align(8))]
- struct Header {
- references: std::sync::atomic::AtomicU32,
- length: u32,
- code_points: std::sync::atomic::AtomicU32,
- hash: std::sync::atomic::AtomicU32,
- flags: std::sync::atomic::AtomicU32,
- reserved: u32,
- }
- const _: () = assert!(size_of::<Header>() == 24);
- let units = unsafe { ak::slice_from_raw_parts(data, length) };
- static FLY_STRINGS: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<Vec<u16>, Box<[u64]>>>> =
- std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
- {
- let mut strings = FLY_STRINGS.lock().unwrap();
- let storage = strings.entry(units.to_vec()).or_insert_with(|| {
- let bytes = size_of::<Header>().checked_add(size_of_val(units)).unwrap();
- let mut storage = vec![0_u64; bytes.div_ceil(size_of::<u64>())].into_boxed_slice();
- unsafe {
- storage.as_mut_ptr().cast::<Header>().write(Header {
- references: std::sync::atomic::AtomicU32::new(1),
- length: u32::try_from(length).unwrap(),
- code_points: std::sync::atomic::AtomicU32::new(u32::MAX),
- hash: std::sync::atomic::AtomicU32::new(0),
- flags: std::sync::atomic::AtomicU32::new(1),
- reserved: 0,
- });
- storage
- .as_mut_ptr()
- .cast::<Header>()
- .add(1)
- .cast::<u16>()
- .copy_from_nonoverlapping(units.as_ptr(), length);
- }
- storage
- });
- let raw = storage.as_ptr() as usize;
- // The table retains its own reference for the process's lifetime.
- unsafe { ak::reference_utf16_string(raw) };
- raw
- }
- }
- #[unsafe(no_mangle)]
- extern "C" fn ladybird_gfx_font_cascade_list_ref(_raw: *const std::ffi::c_void) {}
- #[unsafe(no_mangle)]
- extern "C" fn ladybird_gfx_font_cascade_list_unref(_raw: *const std::ffi::c_void) {
- FONT_CASCADE_LIST_UNREFS.set(FONT_CASCADE_LIST_UNREFS.get() + 1);
- }
- #[unsafe(no_mangle)]
- extern "C" fn ladybird_gfx_font_cascade_list_equals(list: *const c_void, other: *const c_void) -> bool {
- list == other
- }
- #[unsafe(no_mangle)]
- extern "C" fn ladybird_gfx_font_cascade_list_frozen(_raw: *const std::ffi::c_void) -> *const std::ffi::c_void {
- std::ptr::null()
- }
- #[unsafe(no_mangle)]
- extern "C" fn ladybird_gfx_font_ref(_raw: *const std::ffi::c_void) {}
- #[unsafe(no_mangle)]
- extern "C" fn ladybird_gfx_font_unref(_raw: *const std::ffi::c_void) {}
- #[unsafe(no_mangle)]
- unsafe extern "C" fn ladybird_gfx_decoded_image_frame_retain(
- frame: *const std::ffi::c_void,
- out_snapshot: *mut libgfx_rust::image_frame::FfiImageFrameSnapshot,
- ) -> *mut std::ffi::c_void {
- // Test frames are dangling pointers; their address stands in for the id.
- unsafe {
- *out_snapshot = libgfx_rust::image_frame::FfiImageFrameSnapshot {
- id: frame as usize as u64,
- ..Default::default()
- }
- };
- frame.cast_mut()
- }
- #[unsafe(no_mangle)]
- extern "C" fn ladybird_gfx_decoded_image_frame_release(_frame: *mut std::ffi::c_void) {}
- #[unsafe(no_mangle)]
- unsafe extern "C" fn ladybird_gfx_font_snapshot(
- font: *const std::ffi::c_void,
- out_snapshot: *mut libgfx_rust::font::FfiFontSnapshot,
- ) {
- // Test fonts are dangling pointers; their address stands in for the id.
- unsafe {
- *out_snapshot = libgfx_rust::font::FfiFontSnapshot {
- id: font as usize as u64,
- ..Default::default()
- }
- };
- }
- #[unsafe(no_mangle)]
- unsafe extern "C" fn unicode_rust_idna_to_ascii(
- domain: *const u8,
- domain_length: usize,
- _options: *const c_void,
- context: *mut c_void,
- on_success: unsafe extern "C" fn(*mut c_void, *const u8, usize),
- ) {
- // The style tests only need ASCII URL hosts. The production build uses LibUnicode's C++
- // implementation for the full IDNA algorithm.
- let domain = unsafe { ak::slice_from_raw_parts(domain, domain_length) };
- if domain.is_ascii() {
- unsafe { on_success(context, domain.as_ptr(), domain.len()) };
- }
- }
- #[unsafe(no_mangle)]
- extern "C" fn ladybird_gfx_process_next_structural_epoch() -> u64 {
- static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
- NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
- }
- #[unsafe(no_mangle)]
- extern "C" fn unicode_layout_segmenter_destroy(_handle: *mut std::ffi::c_void) {}
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn url_dependencies_only_read_a_base_for_relative_urls() {
- for (url, needs_base) in [
- ("https://example.com/paint.svg#fill", false),
- ("data:image/svg+xml,paint", false),
- ("https://example.com/色.svg#fill", false),
- ("paint.svg#fill", true),
- ("色.svg#fill", true),
- ("/paint.svg#fill", true),
- ("//example.com/paint.svg#fill", true),
- ("#fill", false),
- ("", false),
- ] {
- let value = StyleValueData::Url {
- url: crate::css::style_value::RetainedString::from_utf16(&url.encode_utf16().collect::<Vec<_>>())
- .unwrap(),
- url_type: 0,
- modifiers: crate::css::style_value::RetainedRequestUrlModifierList::from_retained_modifiers(Vec::new()),
- };
- let dependencies = collect_external_value_dependencies(&value);
- assert_eq!(dependencies.needs_document_base_url, needs_base, "{url}");
- assert_eq!(dependencies.may_need_style_sheet_resource_context, needs_base, "{url}");
- }
- }
-
- #[test]
- fn calculated_random_values_record_their_document_dependency() {
- let number = || {
- Arc::new(crate::css::calc::CalcNode::Numeric(
- crate::css::calc::CalcNumericValue::Number {
- value: 1.0,
- number_type: 0,
- },
- ))
- };
- let calculation = crate::css::calc::CalcNode::Random {
- min: number(),
- max: number(),
- step: None,
- sharing: RetainedStyleValueData::from_owned(StyleValueData::Keyword { keyword: keyword::AUTO }),
- };
- let value = StyleValueData::Calculated {
- rust_calculation: crate::css::calc::CalcNodeHandle::from_arc(Arc::new(calculation)),
- resolve_as_is_number: true,
- resolve_as_base: 0,
- resolved_type: crate::css::calc::FfiNumericType::from_calc(None),
- has_percentages_resolve_as: false,
- percentages_resolve_as: 0,
- resolve_numbers_as_integers: false,
- accepted_ranges: crate::css::style_value::RetainedNumericRangeList::empty(),
- };
-
- assert!(external_value_dependencies(&value).uses_random_function);
- }
-
- #[test]
- fn effective_overflow_keywords_compute_together() {
- let result = resolve_effective_overflow_keywords(keyword::VISIBLE, keyword::AUTO);
- assert!(result.changed_x);
- assert_eq!(result.x_keyword, keyword::AUTO);
- assert!(!result.changed_y);
- assert_eq!(result.y_keyword, keyword::AUTO);
-
- let result = resolve_effective_overflow_keywords(keyword::CLIP, keyword::SCROLL);
- assert!(result.changed_x);
- assert_eq!(result.x_keyword, keyword::HIDDEN);
- assert!(!result.changed_y);
- assert_eq!(result.y_keyword, keyword::SCROLL);
-
- let result = resolve_effective_overflow_keywords(keyword::VISIBLE, keyword::CLIP);
- assert!(!result.changed_x);
- assert!(!result.changed_y);
- }
-
- #[test]
- fn effective_color_scheme_follows_element_and_document_preferences() {
- const AUTO: u8 = 0;
- const DARK: u8 = 1;
- const LIGHT: u8 = 2;
-
- assert_eq!(resolve_effective_color_scheme(&[LIGHT, DARK], DARK, None), DARK);
- assert_eq!(resolve_effective_color_scheme(&[DARK, LIGHT], LIGHT, None), LIGHT);
- assert_eq!(resolve_effective_color_scheme(&[DARK, LIGHT], AUTO, None), DARK);
- assert_eq!(
- resolve_effective_color_scheme(&[AUTO], DARK, Some(&[LIGHT, DARK])),
- DARK
- );
- assert_eq!(resolve_effective_color_scheme(&[], AUTO, Some(&[DARK])), DARK);
- assert_eq!(resolve_effective_color_scheme(&[], AUTO, None), LIGHT);
- }
-
- #[test]
- fn color_keyword_classification_uses_rust_color_metadata() {
- assert!(keyword_is_color(keyword::CURRENTCOLOR));
- assert!(keyword_is_color(keyword::CANVAS));
- assert!(keyword_is_color(keyword::_LIBWEB_BUTTONFACEHOVER));
- assert!(!keyword_is_color(keyword::AUTO));
- }
-
- #[test]
- fn text_align_adjusts_match_parent_and_table_header_defaults() {
- let result = compute_text_align_adjustment(keyword::MATCH_PARENT, false, true, keyword::START, false);
- assert!(result.changed);
- assert_eq!(result.keyword, keyword::RIGHT);
- assert!(!result.inherited);
-
- let result =
- compute_text_align_adjustment(keyword::_LIBWEB_INHERIT_OR_CENTER, true, true, keyword::JUSTIFY, true);
- assert!(result.changed);
- assert_eq!(result.keyword, keyword::JUSTIFY);
- assert!(result.inherited);
-
- let result = compute_text_align_adjustment(keyword::_LIBWEB_INHERIT_OR_CENTER, true, false, 0, true);
- assert!(result.changed);
- assert_eq!(result.keyword, keyword::CENTER);
- assert!(!result.inherited);
- }
-
- fn element_adjustment_input() -> FfiBoxTypeTransformationInput {
- FfiBoxTypeTransformationInput {
- display: FfiDisplay::inline(),
- position: keyword::STATIC,
- float_value: keyword::NONE,
- is_br_element: false,
- is_document_element: false,
- is_mathml_element: false,
- is_mathml_mtable: false,
- is_mathml_mtr: false,
- is_mathml_mtd: false,
- has_parent_display: false,
- writing_mode: crate::css::css_enums::writing_mode::HORIZONTAL_TB,
- parent_writing_mode: crate::css::css_enums::writing_mode::HORIZONTAL_TB,
- is_svg_element: false,
- parent_display: FfiDisplay::block(),
- is_wbr_element: false,
- disallow_display_contents: false,
- rewrite_inline_flow: false,
- is_button_element: false,
- force_line_height_normal: false,
- check_input_line_height: false,
- hide_audio_without_controls: false,
- is_table_element: false,
- force_position_static: false,
- force_symbol_display_inline: false,
- webkit_box_layout_transformation_applies: false,
- }
- }
-
- #[test]
- fn element_styles_adjust_from_marshaled_facts() {
- let mut input = element_adjustment_input();
- input.disallow_display_contents = true;
- let adjustment = adjust_element_style(&input, FfiDisplay::contents(), keyword::LEFT);
- assert!(adjustment.changed_display);
- assert!(adjustment.display.is_none());
-
- input = element_adjustment_input();
- input.is_button_element = true;
- let adjustment = adjust_element_style(&input, FfiDisplay::inline(), keyword::LEFT);
- assert!(adjustment.changed_display);
- assert!(adjustment.display.is_inline_block());
-
- input = element_adjustment_input();
- input.is_table_element = true;
- let adjustment = adjust_element_style(&input, FfiDisplay::block(), keyword::_LIBWEB_CENTER);
- assert!(adjustment.changed_text_align);
- assert_eq!(adjustment.text_align, keyword::START);
-
- input = element_adjustment_input();
- input.check_input_line_height = true;
- let adjustment = adjust_element_style(&input, FfiDisplay::inline(), keyword::LEFT);
- assert!(should_clamp_input_line_height(
- &adjustment,
- &FfiInputLineHeightMetrics {
- current_line_height: 12.0,
- minimum_line_height: 16.0,
- }
- ));
- assert!(!should_clamp_input_line_height(
- &adjustment,
- &FfiInputLineHeightMetrics {
- current_line_height: 18.0,
- minimum_line_height: 16.0,
- }
- ));
- }
-
- #[test]
- fn element_style_adjustments_follow_box_type_transformation() {
- let mut input = element_adjustment_input();
- input.is_button_element = true;
- input.position = keyword::ABSOLUTE;
-
- let adjustments = compute_element_style_adjustments(&input, keyword::LEFT);
- assert!(adjustments.box_type.changed_display);
- assert!(adjustments.box_type.display.is_block_outside());
- assert!(adjustments.element_style.changed_display);
- assert!(adjustments.element_style.display.is_flow_root_inside());
- }
-
- fn test_context() -> FfiLengthResolutionContext {
- FfiLengthResolutionContext {
- viewport_width: 800.0,
- viewport_height: 600.0,
- font_metrics: FfiFontMetrics {
- font_size: 16.0,
- x_height: 8.0,
- cap_height: 11.0,
- zero_advance: 7.5,
- line_height: 19.0,
- },
- root_font_metrics: FfiFontMetrics {
- font_size: 20.0,
- x_height: 10.0,
- cap_height: 14.0,
- zero_advance: 9.0,
- line_height: 24.0,
- },
- font_metrics_depend_on_viewport_metrics: false,
- root_font_metrics_depend_on_viewport_metrics: true,
- 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,
- }
- }
-
- fn unit_code(name: &str) -> usize {
- LENGTH_UNIT_NAMES.iter().position(|&n| n == name).unwrap()
- }
-
- #[test]
- fn px_is_unchanged() {
- let result = absolutize_length(4.0, unit_code("px"), &test_context());
- assert!(result.handled);
- assert!(!result.changed);
- }
-
- #[test]
- fn font_relative_units_resolve() {
- let context = test_context();
- let em = absolutize_length(2.0, unit_code("em"), &context);
- assert!(em.changed);
- assert_eq!(em.px, 32.0);
- assert!(!em.resolved_viewport_relative_length);
-
- let rem = absolutize_length(2.0, unit_code("rem"), &context);
- assert_eq!(rem.px, 40.0);
- assert!(rem.resolved_viewport_relative_length);
-
- assert_eq!(absolutize_length(1.0, unit_code("lh"), &context).px, 19.0);
- assert_eq!(absolutize_length(1.0, unit_code("rch"), &context).px, 9.0);
- }
-
- #[test]
- fn font_size_recascade_resolves_em_without_a_host_context() {
- let percentage = StyleValueData::Percentage { value: 200.0 };
- let em = StyleValueData::Length {
- value: 2.0,
- unit: unit_code("em") as u8,
- };
- let final_percentage = StyleValueData::Percentage { value: 50.0 };
- let values = [None, Some(&percentage), Some(&em), Some(&final_percentage)];
- let default_size = CssPixels::from_integer(13);
- let batch = recascade_font_size_batch(
- values.len(),
- |index| values[index],
- |_| 1.0,
- |_| true,
- 0,
- default_size.raw_value(),
- false,
- default_size.raw_value(),
- FfiFontSizeRecascadeDocumentInputs {
- root_font_size: 16.0,
- root_effective_zoom: 1.0,
- root_font_metrics_depend_on_viewport_metrics: false,
- viewport_width: 800.0,
- viewport_height: 600.0,
- },
- None,
- );
- assert!(batch.status == FontSizeRecascadeStatus::Complete);
- assert_eq!(batch.next_index, values.len());
- assert_eq!(batch.current_size_raw, CssPixels::from_integer(26).raw_value());
- }
-
- #[test]
- fn font_size_recascade_resolves_document_lengths() {
- let rem = StyleValueData::Length {
- value: 2.0,
- unit: unit_code("rem") as u8,
- };
- let vw = StyleValueData::Length {
- value: 10.0,
- unit: unit_code("vw") as u8,
- };
- let values = [Some(&rem), Some(&vw)];
- let batch = recascade_font_size_batch(
- values.len(),
- |index| values[index],
- |_| 1.0,
- |_| true,
- 0,
- CssPixels::from_integer(13).raw_value(),
- false,
- CssPixels::from_integer(13).raw_value(),
- FfiFontSizeRecascadeDocumentInputs {
- root_font_size: 20.0,
- root_effective_zoom: 1.0,
- root_font_metrics_depend_on_viewport_metrics: false,
- viewport_width: 800.0,
- viewport_height: 600.0,
- },
- None,
- );
- assert!(batch.status == FontSizeRecascadeStatus::Complete);
- assert_eq!(batch.current_size_raw, CssPixels::from_integer(80).raw_value());
- assert!(batch.depends_on_viewport_metrics);
- }
-
- #[test]
- fn font_size_recascade_applies_each_ancestor_zoom_once() {
- let px = StyleValueData::Length {
- value: 10.0,
- unit: unit_code("px") as u8,
- };
- let percentage = StyleValueData::Percentage { value: 200.0 };
- let em = StyleValueData::Length {
- value: 2.0,
- unit: unit_code("em") as u8,
- };
- let values = [Some(&px), None, Some(&percentage), Some(&em)];
- let zooms = [2.0, 6.0, 3.0, 1.5];
- let batch = recascade_font_size_batch(
- values.len(),
- |index| values[index],
- |index| zooms[index],
- |_| true,
- 0,
- CssPixels::from_integer(13).raw_value(),
- false,
- CssPixels::from_integer(13).raw_value(),
- FfiFontSizeRecascadeDocumentInputs {
- root_font_size: 20.0,
- root_effective_zoom: 2.0,
- root_font_metrics_depend_on_viewport_metrics: false,
- viewport_width: 800.0,
- viewport_height: 600.0,
- },
- None,
- );
- assert!(batch.status == FontSizeRecascadeStatus::Complete);
- assert_eq!(batch.current_size_raw, CssPixels::from_integer(60).raw_value());
- }
-
- #[test]
- fn font_size_recascade_stops_for_a_length_that_needs_font_metrics() {
- let ex = StyleValueData::Length {
- value: 2.0,
- unit: unit_code("ex") as u8,
- };
- let values = [Some(&ex)];
- let batch = recascade_font_size_batch(
- values.len(),
- |index| values[index],
- |_| 1.0,
- |_| true,
- 0,
- CssPixels::from_integer(13).raw_value(),
- false,
- CssPixels::from_integer(13).raw_value(),
- FfiFontSizeRecascadeDocumentInputs {
- root_font_size: 16.0,
- root_effective_zoom: 1.0,
- root_font_metrics_depend_on_viewport_metrics: false,
- viewport_width: 800.0,
- viewport_height: 600.0,
- },
- None,
- );
- assert!(batch.status == FontSizeRecascadeStatus::NeedsLengthResolution);
- assert_eq!(batch.next_index, 0);
- }
-
- #[test]
- fn viewport_relative_units_resolve() {
- let context = test_context();
- let vw = absolutize_length(50.0, unit_code("vw"), &context);
- assert_eq!(vw.px, 400.0);
- assert!(vw.resolved_viewport_relative_length);
- assert_eq!(absolutize_length(50.0, unit_code("vmin"), &context).px, 300.0);
- assert_eq!(absolutize_length(50.0, unit_code("dvmax"), &context).px, 400.0);
- }
-
- #[test]
- fn absolute_units_resolve() {
- let context = test_context();
- let inch = absolutize_length(1.0, unit_code("in"), &context);
- assert!(inch.changed);
- assert_eq!(inch.px, 96.0);
- }
-
- #[test]
- fn font_weight_keywords_compute() {
- let bolder = StyleValueData::Keyword {
- keyword: keyword::BOLDER,
- };
- assert_eq!(compute_font_weight(&bolder, 300.0).value, 400.0);
- assert_eq!(compute_font_weight(&bolder, 400.0).value, 700.0);
- assert_eq!(compute_font_weight(&bolder, 700.0).value, 900.0);
- assert_eq!(compute_font_weight(&bolder, 900.0).value, 900.0);
-
- let lighter = StyleValueData::Keyword {
- keyword: keyword::LIGHTER,
- };
- assert_eq!(compute_font_weight(&lighter, 50.0).value, 50.0);
- assert_eq!(compute_font_weight(&lighter, 400.0).value, 100.0);
- assert_eq!(compute_font_weight(&lighter, 700.0).value, 400.0);
- assert_eq!(compute_font_weight(&lighter, 900.0).value, 700.0);
-
- assert_eq!(
- compute_font_weight(
- &StyleValueData::Keyword {
- keyword: keyword::NORMAL
- },
- 700.0
- )
- .value,
- 400.0
- );
- assert_eq!(
- compute_font_weight(&StyleValueData::Keyword { keyword: keyword::BOLD }, 100.0).value,
- 700.0
- );
- assert!(compute_font_weight(&StyleValueData::Number { value: 512.0 }, 100.0).unchanged);
- }
-
- #[test]
- fn font_width_keywords_compute() {
- assert_eq!(
- compute_font_width(&StyleValueData::Keyword {
- keyword: keyword::ULTRA_CONDENSED
- })
- .value,
- 50.0
- );
- assert_eq!(
- compute_font_width(&StyleValueData::Keyword {
- keyword: keyword::SEMI_EXPANDED
- })
- .value,
- 112.5
- );
- assert_eq!(
- compute_font_width(&StyleValueData::Keyword {
- keyword: keyword::NORMAL
- })
- .value,
- 100.0
- );
- assert!(compute_font_width(&StyleValueData::Percentage { value: 80.0 }).unchanged);
- }
-
- #[test]
- fn font_size_keywords_compute() {
- let sixteen = CssPixels::from_integer(16);
- let medium = compute_font_size(
- &StyleValueData::Keyword {
- keyword: keyword::MEDIUM,
- },
- 0,
- sixteen,
- 0,
- sixteen,
- 1.0,
- );
- assert_eq!(medium.value, 16.0);
- let large = compute_font_size(
- &StyleValueData::Keyword {
- keyword: keyword::LARGE,
- },
- 0,
- sixteen,
- 0,
- sixteen,
- 1.0,
- );
- assert_eq!(large.value, 18.0);
- let percent = compute_font_size(
- &StyleValueData::Percentage { value: 150.0 },
- 0,
- sixteen,
- 0,
- sixteen,
- 1.0,
- );
- assert_eq!(percent.value, 24.0);
- let math = compute_font_size(
- &StyleValueData::Keyword { keyword: keyword::MATH },
- 1,
- sixteen,
- 0,
- sixteen,
- 1.0,
- );
- assert_eq!(math.value, CssPixels::from_integer(16).scaled(0.71).to_double());
- let math_two_levels = compute_font_size(
- &StyleValueData::Keyword { keyword: keyword::MATH },
- 2,
- sixteen,
- 0,
- sixteen,
- 1.0,
- );
- assert_eq!(
- math_two_levels.value,
- CssPixels::from_integer(16).scaled(0.71f64.powi(2)).to_double()
- );
- }
-
- #[test]
- fn math_depth_computes() {
- let auto_add = StyleValueData::Keyword {
- keyword: keyword::AUTO_ADD,
- };
- assert_eq!(compute_math_depth(&auto_add, 2, true).value, 3.0);
- assert_eq!(compute_math_depth(&auto_add, 2, false).value, 2.0);
- assert_eq!(
- compute_math_depth(&StyleValueData::Integer { value: 5 }, 2, true).value,
- 5.0
- );
- assert_eq!(
- compute_math_depth(&StyleValueData::Keyword { keyword: keyword::AUTO }, 4, true).value,
- 4.0
- );
- }
-
- #[test]
- fn line_height_computes() {
- let sixteen = CssPixels::from_integer(16);
- assert!(
- compute_line_height(
- &StyleValueData::Keyword {
- keyword: keyword::NORMAL
- },
- sixteen
- )
- .unchanged
- );
- assert!(compute_line_height(&StyleValueData::Number { value: 1.5 }, sixteen).unchanged);
- assert_eq!(
- compute_line_height(&StyleValueData::Percentage { value: 150.0 }, sixteen).value,
- 24.0
- );
- }
-
- #[test]
- fn border_width_snaps() {
- // 2.5px at 2 dppx is an integer number of device pixels: unchanged.
- let length = StyleValueData::Length {
- value: 2.5,
- unit: unit_code("px") as u8,
- };
- assert_eq!(compute_border_or_outline_width(&length, 2.0, 1.0, None).value, 2.5);
- // 0.4px at 1 dppx rounds up to 1 device pixel.
- let thin = StyleValueData::Length {
- value: 0.4,
- unit: unit_code("px") as u8,
- };
- assert_eq!(compute_border_or_outline_width(&thin, 1.0, 1.0, None).value, 1.0);
- // medium is 3px.
- assert_eq!(
- compute_border_or_outline_width(
- &StyleValueData::Keyword {
- keyword: keyword::MEDIUM
- },
- 1.0,
- 1.0,
- None
- )
- .value,
- 3.0
- );
- }
-
- #[test]
- fn corner_shapes_map_to_superellipse_parameters() {
- assert_eq!(
- compute_corner_shape_parameter(&StyleValueData::Keyword {
- keyword: keyword::ROUND
- })
- .value,
- 1.0
- );
- assert_eq!(
- compute_corner_shape_parameter(&StyleValueData::Keyword {
- keyword: keyword::NOTCH
- })
- .value,
- f64::NEG_INFINITY
- );
- }
-
- #[test]
- fn highlight_longhand_inheritance() {
- use crate::css::property_metadata::property_id;
- let selection = crate::css::selector::PseudoElementType::Selection as u8;
- let inherit = StyleValueData::Keyword {
- keyword: keyword::INHERIT,
- };
- let unset = StyleValueData::Keyword {
- keyword: keyword::UNSET,
- };
- let initial = StyleValueData::Keyword {
- keyword: keyword::INITIAL,
- };
- let currentcolor = StyleValueData::Keyword {
- keyword: keyword::CURRENTCOLOR,
- };
-
- // A supported property without a cascaded value, or with inherit or unset, takes the parent
- // highlight's value whether or not it is an inherited property.
- assert!(highlight_longhand_inherits(
- None,
- selection,
- property_id::BACKGROUND_COLOR
- ));
- assert!(highlight_longhand_inherits(
- Some(&inherit),
- selection,
- property_id::BACKGROUND_COLOR
- ));
- assert!(highlight_longhand_inherits(
- Some(&unset),
- selection,
- property_id::BACKGROUND_COLOR
- ));
- assert!(highlight_longhand_inherits(None, selection, property_id::COLOR));
-
- // Any other cascaded value stands, currentcolor included.
- assert!(!highlight_longhand_inherits(
- Some(&initial),
- selection,
- property_id::BACKGROUND_COLOR
- ));
- assert!(!highlight_longhand_inherits(
- Some(&currentcolor),
- selection,
- property_id::COLOR
- ));
-
- // A property the highlight cannot carry keeps the ordinary decision.
- assert!(!highlight_longhand_inherits(None, selection, property_id::DISPLAY));
- }
-
- #[test]
- fn longhand_decisions() {
- use crate::css::property_metadata::{FIRST_INHERITED_PROPERTY_ID, LAST_LONGHAND_PROPERTY_ID};
- let inherited_id = FIRST_INHERITED_PROPERTY_ID;
- let reset_id = LAST_LONGHAND_PROPERTY_ID;
-
- // Missing value: inherited properties inherit, reset properties go initial.
- let missing_inherited = longhand_decision(None, inherited_id);
- assert!(missing_inherited.should_inherit);
- let missing_reset = longhand_decision(None, reset_id);
- assert!(!missing_reset.should_inherit);
- assert!(missing_reset.use_initial_without_inherit);
-
- // Explicit inherit on a reset property is flagged.
- let inherit = StyleValueData::Keyword {
- keyword: keyword::INHERIT,
- };
- let explicit = longhand_decision(Some(&inherit), reset_id);
- assert!(explicit.should_inherit);
- assert!(explicit.explicitly_inherits_non_inherited_property);
-
- // unset: inherit for inherited properties, initial for reset ones.
- let unset = StyleValueData::Keyword {
- keyword: keyword::UNSET,
- };
- assert!(longhand_decision(Some(&unset), inherited_id).should_inherit);
- let unset_reset = longhand_decision(Some(&unset), reset_id);
- assert!(!unset_reset.should_inherit);
- assert!(unset_reset.use_initial_without_inherit);
-
- // currentcolor in the color property inherits.
- let currentcolor = StyleValueData::Keyword {
- keyword: keyword::CURRENTCOLOR,
- };
- assert!(
- longhand_decision(Some(&currentcolor), crate::css::property_metadata::property_id::COLOR).should_inherit
- );
- assert!(!longhand_decision(Some(&currentcolor), reset_id).should_inherit);
- }
-
- #[test]
- fn container_relative_units_without_snapshotted_bases_are_unhandled() {
- assert!(!absolutize_length(1.0, unit_code("cqw"), &test_context()).handled);
- }
-
- #[test]
- fn container_relative_units_resolve_from_snapshotted_bases() {
- let mut context = test_context();
- context.has_container_width_basis = true;
- context.has_container_height_basis = true;
- context.container_width_basis = 400.0;
- context.container_height_basis = 200.0;
-
- assert_eq!(absolutize_length(10.0, unit_code("cqw"), &context).px, 40.0);
- assert_eq!(absolutize_length(10.0, unit_code("cqh"), &context).px, 20.0);
- assert_eq!(absolutize_length(10.0, unit_code("cqi"), &context).px, 40.0);
- assert_eq!(absolutize_length(10.0, unit_code("cqb"), &context).px, 20.0);
- assert_eq!(absolutize_length(10.0, unit_code("cqmin"), &context).px, 20.0);
- assert_eq!(absolutize_length(10.0, unit_code("cqmax"), &context).px, 40.0);
-
- context.subject_inline_axis_is_horizontal = false;
- assert_eq!(absolutize_length(10.0, unit_code("cqi"), &context).px, 20.0);
- assert_eq!(absolutize_length(10.0, unit_code("cqb"), &context).px, 40.0);
- }
-
- #[test]
- fn container_relative_viewport_fallback_records_its_dependency() {
- let mut dependency_was_recorded = false;
- let mut context = test_context();
- context.has_container_width_basis = true;
- context.container_width_basis = 800.0;
- context.container_width_basis_depends_on_viewport_metrics = true;
- context.resolved_viewport_relative_length = &raw mut dependency_was_recorded;
-
- let result = absolutize_length(10.0, unit_code("cqw"), &context);
- assert_eq!(result.px, 80.0);
- assert!(result.resolved_viewport_relative_length);
- assert!(dependency_was_recorded);
- }
-
- fn svg_axis_case(svg: bool, vertical: bool) -> [f64; 3] {
- use crate::css::property_metadata::property_id as prop;
- let mut table = ComputedLonghandTable::new();
- table.set(prop::ZOOM, retained_new(StyleValueData::Number { value: 2.0 }), -1);
- let mut store = crate::css::cascaded_properties::CascadedPropertyStore::new();
- store.seed_retained_property(
- prop::WRITING_MODE,
- retained_new(StyleValueData::Keyword {
- keyword: if vertical {
- keyword::VERTICAL_RL
- } else {
- keyword::HORIZONTAL_TB
- },
- }),
- false,
- false,
- );
- for (property, value, unit) in [
- (prop::WIDTH, 7.0, "px"),
- (prop::HEIGHT, 1.0, "rem"),
- (prop::MARGIN_LEFT, 10.0, "vi"),
- ] {
- store.seed_retained_property(
- property,
- retained_new(StyleValueData::Length {
- value,
- unit: unit_code(unit) as u8,
- }),
- false,
- false,
- );
- }
- let mut box_type_input = element_adjustment_input();
- box_type_input.is_svg_element = svg;
- let environment = FfiStyleComputationEnvironment {
- box_type_input,
- 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: false,
- sibling_count: 0,
- sibling_index: 0,
- random_base_values: std::ptr::null(),
- random_base_value_count: 0,
- document_base_url: std::ptr::null(),
- document_base_url_length: 0,
- style_sheet_resource_contexts: std::ptr::null(),
- style_sheet_resource_context_count: 0,
- device_pixels_per_css_pixel: 1.0,
- initial_font_size_raw: 1024,
- default_font_size_raw: 1024,
- root_effective_zoom: 1.0,
- };
- let context = FfiLengthResolutionContext {
- viewport_width: 200.0,
- viewport_height: 100.0,
- root_font_metrics: FfiFontMetrics {
- font_size: 20.0,
- ..Default::default()
- },
- subject_inline_axis_is_horizontal: true,
- zoom: 1.0,
- ..Default::default()
- };
- let mut results = empty_longhand_driver_results();
- let mut color_scheme = -1;
- // SAFETY: All environment slices are empty and the borrowed contexts live throughout the drive.
- unsafe {
- drive_property_computation(
- &mut table,
- &store,
- None,
- None,
- &environment,
- None,
- LONGHAND_DRIVE_PHASE_REMAINING,
- Some(&context),
- None,
- &mut results,
- &mut color_scheme,
- false,
- );
- }
- [prop::WIDTH, prop::HEIGHT, prop::MARGIN_LEFT].map(|property| match table.get(property).unwrap().data() {
- StyleValueData::Length { value, unit } if *unit == px_length_unit() => *value,
- _ => panic!("expected absolute computed length"),
- })
- }
-
- #[test]
- fn svg_vertical_axis_preserves_unzoomed_lengths() {
- assert_eq!(svg_axis_case(true, true), [7.0, 20.0, 10.0]);
- }
- #[test]
- fn html_vertical_axis_applies_zoom() {
- assert_eq!(svg_axis_case(false, true), [14.0, 40.0, 20.0]);
- }
- #[test]
- fn svg_horizontal_axis_preserves_unzoomed_lengths() {
- assert_eq!(svg_axis_case(true, false), [7.0, 20.0, 20.0]);
- }
- fn font_phase_axis_case(
- declared: Option<u16>,
- parent_mode: u16,
- inherit_font: bool,
- context_horizontal: bool,
- ) -> [f64; 2] {
- use crate::css::property_metadata::property_id as prop;
- let mut table = ComputedLonghandTable::new();
- table.set(prop::ZOOM, retained_new(StyleValueData::Number { value: 1.0 }), -1);
- let mut store = crate::css::cascaded_properties::CascadedPropertyStore::new();
- if let Some(keyword) = declared {
- store.seed_retained_property(
- prop::WRITING_MODE,
- retained_new(StyleValueData::Keyword { keyword }),
- false,
- false,
- );
- }
- if !inherit_font {
- store.seed_retained_property(
- prop::FONT_SIZE,
- retained_new(StyleValueData::Length {
- value: 10.0,
- unit: unit_code("vi") as u8,
- }),
- false,
- false,
- );
- }
- store.seed_retained_property(
- prop::LINE_HEIGHT,
- retained_new(StyleValueData::Length {
- value: 10.0,
- unit: unit_code("vb") as u8,
- }),
- false,
- false,
- );
- let mut parent = ComputedLonghandTable::new();
- parent.set(
- prop::WRITING_MODE,
- retained_new(StyleValueData::Keyword { keyword: parent_mode }),
- -1,
- );
- parent.set(
- prop::FONT_SIZE,
- retained_new(StyleValueData::Length {
- value: 23.0,
- unit: px_length_unit(),
- }),
- -1,
- );
- parent.set(
- prop::FONT_WEIGHT,
- retained_new(StyleValueData::Number { value: 400.0 }),
- -1,
- );
- let snapshot = ParentSnapshot::new(&parent, None, false);
- let mut box_type_input = element_adjustment_input();
- box_type_input.is_svg_element = false;
- let environment = FfiStyleComputationEnvironment {
- box_type_input,
- 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: false,
- sibling_count: 0,
- sibling_index: 0,
- random_base_values: std::ptr::null(),
- random_base_value_count: 0,
- document_base_url: std::ptr::null(),
- document_base_url_length: 0,
- style_sheet_resource_contexts: std::ptr::null(),
- style_sheet_resource_context_count: 0,
- device_pixels_per_css_pixel: 1.0,
- initial_font_size_raw: 1024,
- default_font_size_raw: 1024,
- root_effective_zoom: 1.0,
- };
- let context = FfiLengthResolutionContext {
- viewport_width: 800.0,
- viewport_height: 600.0,
- root_font_metrics: FfiFontMetrics {
- font_size: 20.0,
- ..Default::default()
- },
- subject_inline_axis_is_horizontal: context_horizontal,
- zoom: 1.0,
- ..Default::default()
- };
- let mut results = empty_longhand_driver_results();
- let mut color_scheme = -1;
- // SAFETY: All environment slices are empty and the borrowed contexts live throughout the drive.
- for phase in [LONGHAND_DRIVE_PHASE_FONT, LONGHAND_DRIVE_PHASE_LINE_HEIGHT] {
- unsafe {
- drive_property_computation(
- &mut table,
- &store,
- Some(&snapshot),
- None,
- &environment,
- None,
- phase,
- Some(&context),
- None,
- &mut results,
- &mut color_scheme,
- false,
- );
- }
- }
- [prop::FONT_SIZE, prop::LINE_HEIGHT].map(|property| match table.get(property).unwrap().data() {
- StyleValueData::Length { value, unit } if *unit == px_length_unit() => *value,
- _ => panic!("expected absolute computed length"),
- })
- }
-
- #[test]
- fn font_and_line_height_follow_explicit_vertical_axis() {
- assert_eq!(
- font_phase_axis_case(Some(keyword::VERTICAL_RL), keyword::HORIZONTAL_TB, false, true),
- [60.0, 80.0]
- );
- }
- #[test]
- fn font_and_line_height_follow_explicit_horizontal_axis() {
- assert_eq!(
- font_phase_axis_case(Some(keyword::HORIZONTAL_TB), keyword::VERTICAL_RL, false, false),
- [80.0, 60.0]
- );
- }
- #[test]
- fn font_and_line_height_follow_inherited_axis() {
- assert_eq!(
- font_phase_axis_case(None, keyword::VERTICAL_RL, false, true),
- [60.0, 80.0]
- );
- }
- #[test]
- fn inherited_computed_font_size_is_not_reinterpreted_in_child_axis() {
- assert_eq!(
- font_phase_axis_case(Some(keyword::VERTICAL_RL), keyword::HORIZONTAL_TB, true, true),
- [23.0, 80.0]
- );
- }
- #[test]
- fn font_axis_initial_keyword_uses_initial_writing_mode() {
- assert_eq!(
- font_phase_axis_case(Some(keyword::INITIAL), keyword::VERTICAL_RL, false, false),
- [80.0, 60.0]
- );
- }
-}
+mod tests;
diff --git a/Libraries/LibWeb/Rust/src/css/style_compute/adjustments.rs b/Libraries/LibWeb/Rust/src/css/style_compute/adjustments.rs
new file mode 100644
index 00000000000..754c16da42a
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style_compute/adjustments.rs
@@ -0,0 +1,678 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use super::*;
+
+pub(crate) fn display_is_none(raw: u32) -> bool {
+ FfiDisplay::from_raw(raw).is_none()
+}
+
+/// The element facts the box type transformation needs, marshalled by the C++
+/// side. The parent display is the first non-`display: contents` ancestor's.
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct FfiBoxTypeTransformationInput {
+ pub display: FfiDisplay,
+ /// Computed position and float keywords.
+ pub position: u16,
+ pub float_value: u16,
+ pub is_br_element: bool,
+ pub is_document_element: bool,
+ pub is_mathml_element: bool,
+ pub is_mathml_mtable: bool,
+ pub is_mathml_mtr: bool,
+ pub is_mathml_mtd: bool,
+ pub has_parent_display: bool,
+ pub parent_display: FfiDisplay,
+ /// The computed writing-mode of the element and of the box it would be the child of.
+ pub writing_mode: u8,
+ pub parent_writing_mode: u8,
+ /// Whether the element is an SVG element, whose boxes are not laid out by the CSS display types.
+ pub is_svg_element: bool,
+ pub is_wbr_element: bool,
+ pub disallow_display_contents: bool,
+ pub rewrite_inline_flow: bool,
+ pub is_button_element: bool,
+ pub force_line_height_normal: bool,
+ pub check_input_line_height: bool,
+ pub hide_audio_without_controls: bool,
+ pub is_table_element: bool,
+ pub force_position_static: bool,
+ pub force_symbol_display_inline: bool,
+ pub webkit_box_layout_transformation_applies: bool,
+}
+
+/// Whether element-specific adjustments apply to the subject being computed.
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub enum StyleAdjustmentTarget {
+ Element,
+ PseudoElement,
+}
+
+/// Build the shared adjustment inputs from element facts. The caller supplies the first
+/// non-`display: contents` ancestor's display, using live styles on the C++ path.
+pub(crate) fn rust_box_type_transformation_input(
+ facts: u32,
+ target: StyleAdjustmentTarget,
+ has_parent_display: bool,
+ parent_display: FfiDisplay,
+ parent_writing_mode: u8,
+) -> FfiBoxTypeTransformationInput {
+ use crate::css::style::bridge::element_adjustment_fact as fact;
+
+ let has = |bit| facts & bit != 0;
+ let adjust_element = target == StyleAdjustmentTarget::Element;
+ FfiBoxTypeTransformationInput {
+ display: crate::css::display::FfiDisplay::inline(),
+ position: keyword::STATIC,
+ float_value: keyword::NONE,
+ is_br_element: adjust_element && has(fact::IS_BR),
+ is_document_element: adjust_element && has(fact::IS_DOCUMENT_ELEMENT),
+ is_mathml_element: has(fact::IS_MATHML),
+ is_mathml_mtable: has(fact::IS_MATHML_MTABLE),
+ is_mathml_mtr: has(fact::IS_MATHML_MTR),
+ is_mathml_mtd: has(fact::IS_MATHML_MTD),
+ has_parent_display,
+ parent_display,
+ writing_mode: crate::css::css_enums::writing_mode::HORIZONTAL_TB,
+ parent_writing_mode,
+ is_svg_element: has(fact::IS_SVG_ELEMENT),
+ is_wbr_element: adjust_element && has(fact::IS_WBR),
+ disallow_display_contents: adjust_element && has(fact::DISALLOW_DISPLAY_CONTENTS),
+ rewrite_inline_flow: adjust_element && has(fact::REWRITE_INLINE_FLOW),
+ is_button_element: adjust_element && has(fact::IS_BUTTON),
+ force_line_height_normal: adjust_element && has(fact::FORCE_LINE_HEIGHT_NORMAL),
+ check_input_line_height: adjust_element && has(fact::CHECK_INPUT_LINE_HEIGHT),
+ hide_audio_without_controls: adjust_element && has(fact::HIDE_AUDIO_WITHOUT_CONTROLS),
+ is_table_element: adjust_element && has(fact::IS_TABLE),
+ force_position_static: adjust_element && has(fact::FORCE_POSITION_STATIC),
+ force_symbol_display_inline: adjust_element && has(fact::FORCE_SYMBOL_DISPLAY_INLINE),
+ webkit_box_layout_transformation_applies: false,
+ }
+}
+
+/// The box-type transformation input of a style target's animated composition, which the host
+/// samples over the record the engine holds for it: the same input the engine drives the record
+/// against, read from the element's published facts and its parent's record. A target the engine
+/// does not know is transformed with no facts and no parent display.
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_animated_box_type_transformation_input(
+ host: &crate::render_state::DocumentHost,
+ read: &crate::render_state::BegunRead,
+ node: u32,
+ pseudo_kind: u32,
+) -> FfiBoxTypeTransformationInput {
+ let pseudo_kind = pseudo_kind as u8;
+ match crate::css::style::tree::StyleNodeID::from_raw(node) {
+ Some(node) => crate::css::style::engine_calls::with_engine(read, host, |engine| {
+ engine.composition_box_type_transformation_input(node, pseudo_kind)
+ }),
+ None => rust_box_type_transformation_input(
+ 0,
+ StyleAdjustmentTarget::Element,
+ false,
+ FfiDisplay::block(),
+ crate::css::css_enums::writing_mode::HORIZONTAL_TB,
+ ),
+ }
+}
+
+/// Result of the box type transformation: whether float must be reset to none,
+/// and the possibly replaced display.
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct FfiBoxTypeTransformation {
+ pub set_float_none: bool,
+ pub changed_display: bool,
+ pub display: FfiDisplay,
+}
+
+#[derive(Clone, Copy)]
+pub struct ElementStyleAdjustment {
+ pub changed_display: bool,
+ pub display: FfiDisplay,
+ pub set_line_height_normal: bool,
+ pub check_input_line_height: bool,
+ pub set_position_static: bool,
+ pub changed_text_align: bool,
+ pub text_align: u16,
+}
+
+/// The automatic box type transformation and element-specific adjustment,
+/// sequenced as they are in the normal property computation path.
+#[derive(Clone, Copy)]
+pub struct ElementStyleAdjustments {
+ pub box_type: FfiBoxTypeTransformation,
+ pub element_style: ElementStyleAdjustment,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct FfiInputLineHeightMetrics {
+ pub current_line_height: f64,
+ pub minimum_line_height: f64,
+}
+
+pub(super) fn should_clamp_input_line_height(
+ adjustment: &ElementStyleAdjustment,
+ metrics: &FfiInputLineHeightMetrics,
+) -> bool {
+ adjustment.check_input_line_height && metrics.current_line_height < metrics.minimum_line_height
+}
+
+pub(super) fn adjust_element_style(
+ input: &FfiBoxTypeTransformationInput,
+ display: FfiDisplay,
+ text_align: u16,
+) -> ElementStyleAdjustment {
+ let mut new_display = display;
+ if input.is_wbr_element && display.is_contents() {
+ new_display = FfiDisplay::none();
+ }
+ if input.disallow_display_contents && new_display.is_contents() {
+ new_display = FfiDisplay::none();
+ }
+ if input.rewrite_inline_flow && new_display.is_inline_outside() && new_display.inside == display_inside::FLOW {
+ new_display = FfiDisplay::inline_block();
+ }
+ if input.is_button_element
+ && !(new_display.is_flex_inside()
+ || new_display.is_grid_inside()
+ || new_display.is_none()
+ || new_display.is_contents())
+ {
+ new_display = if new_display.is_inline_outside() {
+ FfiDisplay::inline_block()
+ } else {
+ FfiDisplay::flow_root()
+ };
+ }
+ if input.is_br_element {
+ new_display = if new_display.is_contents() {
+ FfiDisplay::none()
+ } else if new_display.is_none() {
+ new_display
+ } else {
+ FfiDisplay::inline()
+ };
+ }
+ if input.hide_audio_without_controls {
+ new_display = FfiDisplay::none();
+ }
+ if input.force_symbol_display_inline {
+ new_display = FfiDisplay::inline();
+ }
+
+ let new_text_align = if input.is_table_element
+ && matches!(
+ text_align,
+ keyword::_LIBWEB_LEFT | keyword::_LIBWEB_CENTER | keyword::_LIBWEB_RIGHT
+ ) {
+ keyword::START
+ } else {
+ text_align
+ };
+
+ ElementStyleAdjustment {
+ changed_display: new_display != display,
+ display: new_display,
+ set_line_height_normal: input.force_line_height_normal,
+ check_input_line_height: input.check_input_line_height,
+ set_position_static: input.force_position_static,
+ changed_text_align: new_text_align != text_align,
+ text_align: new_text_align,
+ }
+}
+
+pub(super) fn compute_element_style_adjustments(
+ input: &FfiBoxTypeTransformationInput,
+ text_align: u16,
+) -> ElementStyleAdjustments {
+ let box_type = transform_box_type(input);
+ let display = if box_type.changed_display {
+ box_type.display
+ } else {
+ input.display
+ };
+ let element_style = adjust_element_style(input, display, text_align);
+ ElementStyleAdjustments {
+ box_type,
+ element_style,
+ }
+}
+
+// NB: css-display-3 also defines inlinification, but nothing triggers it yet (the only
+// candidate is the ruby containment FIXME below), so only blockification is modeled.
+pub(super) enum BoxTypeTransformation {
+ None,
+ Blockify,
+}
+
+pub(super) fn required_box_type_transformation(input: &FfiBoxTypeTransformationInput) -> BoxTypeTransformation {
+ // NOTE: We never blockify <br> elements. They are always inline.
+ // There is currently no way to express in CSS how a <br> element really behaves.
+ // Spec issue: https://github.com/whatwg/html/issues/2291
+ if input.is_br_element {
+ return BoxTypeTransformation::None;
+ }
+
+ // Absolute positioning or floating an element blockifies the box's display type. [CSS2]
+ if input.position == keyword::ABSOLUTE || input.position == keyword::FIXED || input.float_value != keyword::NONE {
+ return BoxTypeTransformation::Blockify;
+ }
+
+ // FIXME: Containment in a ruby container inlinifies the box's display type, as described in [CSS-RUBY-1].
+
+ // A parent with a grid or flex display value blockifies the box's display type. [CSS-GRID-1] [CSS-FLEXBOX-1]
+ // NB: The C++ side supplies the first ancestor that is not `display: contents`; for a
+ // pseudo-element that climb starts at the originating element itself.
+ if input.has_parent_display && (input.parent_display.is_grid_inside() || input.parent_display.is_flex_inside()) {
+ return BoxTypeTransformation::Blockify;
+ }
+
+ BoxTypeTransformation::None
+}
+
+/// https://drafts.csswg.org/css-display/#transformations
+/// 2.7. Automatic Box Type Transformations
+pub(super) fn transform_box_type(input: &FfiBoxTypeTransformationInput) -> FfiBoxTypeTransformation {
+ let display_before_transformation = input.display;
+ let mut display = display_before_transformation;
+
+ // https://drafts.csswg.org/css-overflow-4/#webkit-line-clamp
+ // If the specified value of the 'display' property is '-webkit-box', the computed value becomes 'flow-root'
+ // and the box establishes a BFC.
+ if input.webkit_box_layout_transformation_applies && display.is_webkit_box_inside() {
+ display = if display.is_inline_outside() {
+ FfiDisplay::inline_block()
+ } else {
+ FfiDisplay::flow_root()
+ };
+ }
+ let unchanged = |set_float_none: bool| FfiBoxTypeTransformation {
+ set_float_none,
+ changed_display: display != display_before_transformation,
+ display,
+ };
+
+ // Some layout effects require blockification or inlinification of the box type,
+ // which sets the box's computed outer display type to block or inline (respectively).
+ // (This has no effect on display types that generate no box at all, such as none or contents.)
+ if display.is_none() || (display.is_contents() && !input.is_document_element) {
+ return unchanged(false);
+ }
+
+ // https://drafts.csswg.org/css-display/#root
+ // The root element's display type is always blockified, and its principal box always establishes an independent formatting context.
+ if input.is_document_element && !display.is_block_outside() {
+ return FfiBoxTypeTransformation {
+ set_float_none: false,
+ changed_display: true,
+ display: FfiDisplay::block(),
+ };
+ }
+
+ let mut new_display = display;
+
+ if display.is_math_inside() {
+ // https://w3c.github.io/mathml-core/#new-display-math-value
+ // For elements that are not MathML elements, if the specified value of display is inline math or block math
+ // then the computed value is block flow and inline flow respectively.
+ if !input.is_mathml_element {
+ new_display = FfiDisplay::outside_and_inside(display.outside, display_inside::FLOW, display.list_item);
+ }
+ // For the mtable element the computed value is block table and inline table respectively.
+ else if input.is_mathml_mtable {
+ new_display = FfiDisplay::outside_and_inside(display.outside, display_inside::TABLE, display.list_item);
+ }
+ // For the mtr element, the computed value is table-row.
+ else if input.is_mathml_mtr {
+ new_display = FfiDisplay::internal(display_internal::TABLE_ROW);
+ }
+ // For the mtd element, the computed value is table-cell.
+ else if input.is_mathml_mtd {
+ new_display = FfiDisplay::internal(display_internal::TABLE_CELL);
+ }
+ }
+
+ // https://www.w3.org/TR/CSS2/visuren.html#dis-pos-flo
+ // If 'position' has the value 'absolute' or 'fixed', [...] 'float' is set to 'none'
+ let set_float_none = input.position == keyword::ABSOLUTE || input.position == keyword::FIXED;
+
+ match required_box_type_transformation(input) {
+ BoxTypeTransformation::None => {}
+ BoxTypeTransformation::Blockify => {
+ if display.is_block_outside() {
+ return unchanged(set_float_none);
+ }
+ // If a layout-internal box is blockified, its inner display type converts to flow so that it becomes a block container.
+ if display.is_internal() {
+ new_display = FfiDisplay::block();
+ } else {
+ assert!(display.is_outside_and_inside());
+
+ // For legacy reasons, if an inline block box (inline flow-root) is blockified, it becomes a block box (losing its flow-root nature).
+ // For consistency, a run-in flow-root box also blockifies to a block box.
+ if display.is_inline_block() {
+ new_display =
+ FfiDisplay::outside_and_inside(display_outside::BLOCK, display_inside::FLOW, display.list_item);
+ } else {
+ new_display =
+ FfiDisplay::outside_and_inside(display_outside::BLOCK, display.inside, display.list_item);
+ }
+ }
+ }
+ }
+
+ // https://drafts.csswg.org/css-writing-modes-4/#block-flow
+ // If a box has a different 'writing-mode' value than its parent box (i.e. nearest ancestor without
+ // 'display: contents'):
+ if input.has_parent_display
+ && input.writing_mode != input.parent_writing_mode
+ && !input.is_svg_element
+ && new_display.is_outside_and_inside()
+ {
+ // - If the box would otherwise become an in-flow box with a computed 'display' of 'inline', its 'display'
+ // computes instead to 'inline-block'.
+ // - If the box is a block container, then it establishes an independent block formatting context.
+ // - More generally, if its specified inner display type is 'flow', then its computed inner display type
+ // becomes 'flow-root'.
+ // NB: Layout makes a block container with another writing mode than its parent box establish an
+ // independent formatting context, so only the inline box's display changes here.
+ if new_display.is_flow_inside() && new_display.is_inline_outside() {
+ new_display = FfiDisplay::outside_and_inside(
+ new_display.outside,
+ crate::css::css_enums::display_inside::FLOW_ROOT,
+ new_display.list_item,
+ );
+ }
+ }
+
+ FfiBoxTypeTransformation {
+ set_float_none,
+ changed_display: new_display != display_before_transformation,
+ display: new_display,
+ }
+}
+
+/// Result of resolving the effective overflow pair: each axis' possibly
+/// replaced computed keyword.
+pub struct EffectiveOverflow {
+ pub changed_x: bool,
+ pub x_keyword: u16,
+ pub changed_y: bool,
+ pub y_keyword: u16,
+}
+
+/// https://www.w3.org/TR/css-overflow-3/#overflow-control
+/// The visible/clip values of overflow compute to auto/hidden (respectively) if one of overflow-x or
+/// overflow-y is neither visible nor clip.
+pub(super) fn resolve_effective_overflow_keywords(overflow_x: u16, overflow_y: u16) -> EffectiveOverflow {
+ let is_visible_or_clip = |keyword: u16| keyword == keyword::VISIBLE || keyword == keyword::CLIP;
+ let mut result = EffectiveOverflow {
+ changed_x: false,
+ x_keyword: overflow_x,
+ changed_y: false,
+ y_keyword: overflow_y,
+ };
+ if !is_visible_or_clip(overflow_x) || !is_visible_or_clip(overflow_y) {
+ if overflow_x == keyword::VISIBLE {
+ result.changed_x = true;
+ result.x_keyword = keyword::AUTO;
+ }
+ if overflow_x == keyword::CLIP {
+ result.changed_x = true;
+ result.x_keyword = keyword::HIDDEN;
+ }
+ if overflow_y == keyword::VISIBLE {
+ result.changed_y = true;
+ result.y_keyword = keyword::AUTO;
+ }
+ if overflow_y == keyword::CLIP {
+ result.changed_y = true;
+ result.y_keyword = keyword::HIDDEN;
+ }
+ }
+ result
+}
+
+// https://drafts.csswg.org/css-color-adjust-1/#determine-the-used-color-scheme
+pub(super) fn resolve_effective_color_scheme(
+ schemes: &[u8],
+ preferred_scheme: u8,
+ document_supported_schemes: Option<&[u8]>,
+) -> u8 {
+ const AUTO: u8 = 0;
+ const LIGHT: u8 = 2;
+
+ // To determine the used color scheme of an element:
+
+ // 1. If the user’s preferred color scheme, as indicated by the prefers-color-scheme media feature,
+ // is present among the listed color schemes, and is supported by the user agent,
+ // that’s the element’s used color scheme.
+ if preferred_scheme != AUTO && schemes.contains(&preferred_scheme) {
+ return preferred_scheme;
+ }
+
+ // 2. Otherwise, if the user has indicated an overriding preference for their chosen color scheme,
+ // and the only keyword is not present in color-scheme for the element,
+ // the user agent must override the color scheme with the user’s preferred color scheme.
+ // See § 2.3 Overriding the Color Scheme.
+ // FIXME: We don't currently support setting an "overriding preference" for color schemes.
+
+ // 3. Otherwise, if the user agent supports at least one of the listed color schemes,
+ // the used color scheme is the first supported color scheme in the list.
+ if let Some(first_supported) = schemes.iter().find(|scheme| **scheme != AUTO) {
+ return *first_supported;
+ }
+
+ // 4. Otherwise, the used color scheme is the browser default. (Same as normal.)
+ // `normal` indicates that the element supports the page’s supported color schemes, if they are set
+ if let Some(document_supported_schemes) = document_supported_schemes {
+ if preferred_scheme != AUTO && document_supported_schemes.contains(&preferred_scheme) {
+ return preferred_scheme;
+ }
+ if let Some(first_supported) = document_supported_schemes.iter().find(|scheme| **scheme != AUTO) {
+ return *first_supported;
+ }
+ }
+
+ LIGHT
+}
+
+/// Resolves the used color scheme for a value that required C++ computation.
+///
+/// # Safety
+/// `input` must point at valid document inputs for the duration of the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_resolve_effective_color_scheme(
+ value: &StyleValueData,
+ input: &FfiEffectiveColorSchemeInput,
+) -> u8 {
+ let StyleValueData::ColorScheme(color_scheme_payload) = value else {
+ unreachable!("computed color-scheme must have color-scheme data");
+ };
+ let ColorSchemePayload { scheme_codes, .. } = &**color_scheme_payload;
+ resolve_effective_color_scheme(scheme_codes.as_slice(), input.preferred_color_scheme, unsafe {
+ input.document_supported_schemes()
+ })
+}
+
+/// Result of the text-align adjustment: the replacement keyword and whether it
+/// counts as inherited.
+pub struct TextAlignAdjustment {
+ pub changed: bool,
+ pub keyword: u16,
+ pub inherited: bool,
+}
+
+/// Decides the text-align adjustments applied after computation. The parent
+/// arguments are only read when `has_parent_with_computed_values` is set.
+pub(super) fn compute_text_align_adjustment(
+ text_align: u16,
+ is_th_element: bool,
+ has_parent_with_computed_values: bool,
+ parent_text_align: u16,
+ parent_direction_is_ltr: bool,
+) -> TextAlignAdjustment {
+ let unchanged = TextAlignAdjustment {
+ changed: false,
+ keyword: text_align,
+ inherited: false,
+ };
+ let replace = |keyword: u16| TextAlignAdjustment {
+ changed: true,
+ keyword,
+ inherited: false,
+ };
+
+ // https://drafts.csswg.org/css-text-4/#valdef-text-align-match-parent
+ // This value behaves the same as inherit (computes to its parent's computed value) except that an inherited
+ // value of start or end is interpreted against the parent's direction value and results in a computed value of
+ // either left or right. Computes to start when specified on the root element.
+ if text_align == keyword::MATCH_PARENT {
+ if !has_parent_with_computed_values {
+ return replace(keyword::START);
+ }
+ return match parent_text_align {
+ keyword::START if parent_direction_is_ltr => replace(keyword::LEFT),
+ keyword::START => replace(keyword::RIGHT),
+ keyword::END if parent_direction_is_ltr => replace(keyword::RIGHT),
+ keyword::END => replace(keyword::LEFT),
+ _ => replace(parent_text_align),
+ };
+ }
+
+ // AD-HOC: The -libweb-inherit-or-center style defaults to centering, unless the parent element has a
+ // non-initial computed text-align value. This is used to support the ad-hoc default <th>
+ // text-align behavior.
+ if text_align == keyword::_LIBWEB_INHERIT_OR_CENTER && is_th_element {
+ if has_parent_with_computed_values && parent_text_align != keyword::START {
+ return TextAlignAdjustment {
+ changed: true,
+ keyword: parent_text_align,
+ inherited: true,
+ };
+ }
+ return replace(keyword::CENTER);
+ }
+
+ unchanged
+}
+
+/// Applies the box type transformation and element adjustments to an animated composition, in its overlay, over a base
+/// that stays as computed: what the transformation changes about the animated display, position, float, line-height and
+/// overflow is what the overlay holds.
+pub(super) fn finalize_animated_box_type(
+ mut box_type: FfiBoxTypeTransformationInput,
+ longhands: crate::css::style::ViewLonghands<'_>,
+ display_before_box_type_transformation: u32,
+ overlay: &mut AnimatedOverlay,
+ input_line_height_metrics: Option<&FfiInputLineHeightMetrics>,
+) {
+ use crate::css::property_metadata::property_id as prop;
+
+ let view = Some(&*overlay);
+ let text_align = effective_keyword(longhands, view, prop::TEXT_ALIGN);
+ let animated_display_missing = overlay.get(prop::DISPLAY).is_none();
+ box_type.display = if animated_display_missing {
+ FfiDisplay::from_raw(display_before_box_type_transformation)
+ } else {
+ longhands.effective_display(view)
+ };
+ box_type.position = effective_keyword(longhands, view, prop::POSITION);
+ box_type.float_value = effective_keyword(longhands, view, prop::FLOAT);
+ box_type.writing_mode = longhands.effective_writing_mode(view);
+ box_type.webkit_box_layout_transformation_applies = webkit_box_layout_transformation_applies(longhands, view);
+ // An axis the overlay does not animate is adjusted from its keyword before the base adjusted it against the other
+ // axis, which the overlay may animate out of that adjustment.
+ let before = longhands.overflow_before_adjustment();
+ let unadjusted = |property: u16, axis: usize| match before {
+ Some(before) if overlay.get(property).is_none() => before[axis],
+ _ => effective_keyword(longhands, view, property),
+ };
+ let overflow =
+ resolve_effective_overflow_keywords(unadjusted(prop::OVERFLOW_X, 0), unadjusted(prop::OVERFLOW_Y, 1));
+ let adjustments = compute_element_style_adjustments(&box_type, text_align);
+
+ // A value the overlay animates keeps its animation's place; one it does not is adjusted over the base value.
+ let mut adjust = |property_id: u16, keyword_or_display: StyleValueData| {
+ let value = retained_new(keyword_or_display);
+ let effective = longhands.effective_value(Some(&*overlay), property_id);
+ if effective.data() == value.data() {
+ return;
+ }
+ match overlay
+ .get(property_id)
+ .map(|entry| (entry.inherited, entry.result_of_transition))
+ {
+ Some((inherited, result_of_transition)) => {
+ overlay.set_owned(property_id, value, inherited, result_of_transition);
+ }
+ None if property_id == prop::OVERFLOW_X || property_id == prop::OVERFLOW_Y => {
+ overlay.set_adjusted(property_id, value);
+ }
+ None => overlay.set_owned(property_id, value, false, false),
+ }
+ };
+ let display = |display: FfiDisplay| StyleValueData::Display { raw: display.encoded() };
+ let keyword = |keyword: u16| StyleValueData::Keyword { keyword };
+ if animated_display_missing {
+ adjust(prop::DISPLAY, display(box_type.display));
+ }
+ if adjustments.box_type.set_float_none {
+ adjust(prop::FLOAT, keyword(keyword::NONE));
+ }
+ if adjustments.box_type.changed_display {
+ adjust(prop::DISPLAY, display(adjustments.box_type.display));
+ }
+ let element_style = adjustments.element_style;
+ if element_style.changed_display {
+ adjust(prop::DISPLAY, display(element_style.display));
+ }
+ if element_style.set_position_static {
+ adjust(prop::POSITION, keyword(keyword::STATIC));
+ }
+ if element_style.changed_text_align {
+ adjust(prop::TEXT_ALIGN, keyword(element_style.text_align));
+ }
+ if element_style.set_line_height_normal
+ || (element_style.check_input_line_height
+ && should_clamp_input_line_height(
+ &element_style,
+ input_line_height_metrics.expect("input line-height adjustment requires font metrics"),
+ ))
+ {
+ adjust(prop::LINE_HEIGHT, keyword(keyword::NORMAL));
+ }
+ adjust(prop::OVERFLOW_X, keyword(overflow.x_keyword));
+ adjust(prop::OVERFLOW_Y, keyword(overflow.y_keyword));
+}
+
+/// Applies the box type transformation and element adjustments to the animated composition `animated_overlay` holds
+/// over the longhands of `record`, whose display before the box type transformation the host settled as
+/// `display_before_box_type_transformation`.
+///
+/// # Safety
+/// `record` must be a style record the caller holds a reference to.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_finalize_animated_box_type(
+ box_type: FfiBoxTypeTransformationInput,
+ record: *const c_void,
+ display_before_box_type_transformation: u32,
+ animated_overlay: &mut AnimatedOverlay,
+ input_line_height_metrics: Option<&FfiInputLineHeightMetrics>,
+) {
+ // SAFETY: Guaranteed by the caller.
+ let longhands = unsafe { crate::css::style::ViewLonghands::of_raw_record(record) };
+ finalize_animated_box_type(
+ box_type,
+ longhands,
+ display_before_box_type_transformation,
+ animated_overlay,
+ input_line_height_metrics,
+ );
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style_compute/ffi_test_stubs.rs b/Libraries/LibWeb/Rust/src/css/style_compute/ffi_test_stubs.rs
new file mode 100644
index 00000000000..7d84d96a36b
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style_compute/ffi_test_stubs.rs
@@ -0,0 +1,209 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The standalone cargo test binary has no C++ side, so release callbacks are
+//! stubbed out here.
+
+use std::cell::Cell;
+use std::ffi::c_void;
+
+use crate::css::style::reaction_application::{HostElement, HostStyleReactionApplication};
+
+thread_local! {
+ static FONT_CASCADE_LIST_UNREFS: Cell<usize> = const { Cell::new(0) };
+}
+
+pub(crate) fn font_cascade_list_unref_count() -> usize {
+ FONT_CASCADE_LIST_UNREFS.get()
+}
+
+#[unsafe(no_mangle)]
+extern "C" fn ladybird_utf16_fly_string_unref(_raw: usize) {}
+#[unsafe(no_mangle)]
+extern "C" fn web_css_font_face_snapshot_reference(_snapshot: *const c_void) {}
+#[unsafe(no_mangle)]
+extern "C" fn web_css_font_cascade_memo_reference(_memo: *const c_void) {}
+#[unsafe(no_mangle)]
+extern "C" fn web_css_font_face_snapshot_unreference(_snapshot: *const c_void) {}
+#[unsafe(no_mangle)]
+extern "C" fn web_css_font_cascade_memo_unreference(_memo: *const c_void) {}
+#[unsafe(no_mangle)]
+extern "C" fn web_css_resolve_font(
+ _memo: *const c_void,
+ _snapshot: *const c_void,
+ _request: crate::css::style::bridge::FfiFontResolutionRequest,
+) -> crate::css::style::bridge::FfiResolvedFont {
+ crate::css::style::bridge::FfiResolvedFont::default()
+}
+#[unsafe(no_mangle)]
+extern "C" fn web_css_resolve_font_for_fork(
+ _memo: *const c_void,
+ _snapshot: *const c_void,
+ _request: crate::css::style::bridge::FfiFontResolutionRequest,
+) -> crate::css::style::bridge::FfiResolvedFont {
+ crate::css::style::bridge::FfiResolvedFont::default()
+}
+#[unsafe(no_mangle)]
+extern "C" fn web_css_style_reaction_element(
+ _application: *mut HostStyleReactionApplication,
+ _node: u32,
+) -> crate::css::style::reaction_application::FfiReactionElement {
+ unreachable!("no unit test applies style reactions");
+}
+#[unsafe(no_mangle)]
+extern "C" fn web_css_run_style_update(_application: *mut HostStyleReactionApplication, _flown: bool) {
+ unreachable!("no unit test applies style reactions");
+}
+#[unsafe(no_mangle)]
+extern "C" fn web_css_has_pending_style_update(_application: *mut HostStyleReactionApplication) -> bool {
+ unreachable!("no unit test applies style reactions");
+}
+#[unsafe(no_mangle)]
+extern "C" fn web_css_note_style_update_has_reactions(_application: *mut HostStyleReactionApplication) {
+ unreachable!("no unit test applies style reactions");
+}
+#[unsafe(no_mangle)]
+extern "C" fn web_css_sample_animations_for_style_update(_application: *mut HostStyleReactionApplication) {
+ unreachable!("no unit test applies style reactions");
+}
+#[unsafe(no_mangle)]
+extern "C" fn web_css_begin_style_update_pass(_application: *mut HostStyleReactionApplication, _first: bool) {
+ unreachable!("no unit test applies style reactions");
+}
+#[unsafe(no_mangle)]
+extern "C" fn web_css_style_inheritance_parent(
+ _application: *mut HostStyleReactionApplication,
+ _element: *mut HostElement,
+) -> crate::css::style::reaction_application::FfiReactionElement {
+ unreachable!("no unit test applies style reactions");
+}
+#[unsafe(no_mangle)]
+extern "C" fn ladybird_utf16_string_unref(_raw: usize) {}
+#[unsafe(no_mangle)]
+extern "C" fn ladybird_utf16_string_create_uninitialized(_length: usize, _has_latin1_storage: bool) -> usize {
+ unreachable!("no unit test makes a string the host owns");
+}
+#[unsafe(no_mangle)]
+unsafe extern "C" fn ladybird_utf16_fly_string_from_utf8(data: *const u8, length: usize) -> usize {
+ let bytes = unsafe { ak::slice_from_raw_parts(data, length) };
+ let units = std::str::from_utf8(bytes).unwrap().encode_utf16().collect::<Vec<_>>();
+ unsafe { ladybird_utf16_fly_string_from_utf16(units.as_ptr(), units.len()) }
+}
+#[unsafe(no_mangle)]
+unsafe extern "C" fn ladybird_utf16_fly_string_from_utf16(data: *const u16, length: usize) -> usize {
+ // Keep a process-wide test atom table with AK's header layout so worker-parsed
+ // names remain alive after the worker exits.
+ #[repr(C, align(8))]
+ struct Header {
+ references: std::sync::atomic::AtomicU32,
+ length: u32,
+ code_points: std::sync::atomic::AtomicU32,
+ hash: std::sync::atomic::AtomicU32,
+ flags: std::sync::atomic::AtomicU32,
+ reserved: u32,
+ }
+ const _: () = assert!(size_of::<Header>() == 24);
+ let units = unsafe { ak::slice_from_raw_parts(data, length) };
+ static FLY_STRINGS: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<Vec<u16>, Box<[u64]>>>> =
+ std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
+ {
+ let mut strings = FLY_STRINGS.lock().unwrap();
+ let storage = strings.entry(units.to_vec()).or_insert_with(|| {
+ let bytes = size_of::<Header>().checked_add(size_of_val(units)).unwrap();
+ let mut storage = vec![0_u64; bytes.div_ceil(size_of::<u64>())].into_boxed_slice();
+ unsafe {
+ storage.as_mut_ptr().cast::<Header>().write(Header {
+ references: std::sync::atomic::AtomicU32::new(1),
+ length: u32::try_from(length).unwrap(),
+ code_points: std::sync::atomic::AtomicU32::new(u32::MAX),
+ hash: std::sync::atomic::AtomicU32::new(0),
+ flags: std::sync::atomic::AtomicU32::new(1),
+ reserved: 0,
+ });
+ storage
+ .as_mut_ptr()
+ .cast::<Header>()
+ .add(1)
+ .cast::<u16>()
+ .copy_from_nonoverlapping(units.as_ptr(), length);
+ }
+ storage
+ });
+ let raw = storage.as_ptr() as usize;
+ // The table retains its own reference for the process's lifetime.
+ unsafe { ak::reference_utf16_string(raw) };
+ raw
+ }
+}
+#[unsafe(no_mangle)]
+extern "C" fn ladybird_gfx_font_cascade_list_ref(_raw: *const std::ffi::c_void) {}
+#[unsafe(no_mangle)]
+extern "C" fn ladybird_gfx_font_cascade_list_unref(_raw: *const std::ffi::c_void) {
+ FONT_CASCADE_LIST_UNREFS.set(FONT_CASCADE_LIST_UNREFS.get() + 1);
+}
+#[unsafe(no_mangle)]
+extern "C" fn ladybird_gfx_font_cascade_list_equals(list: *const c_void, other: *const c_void) -> bool {
+ list == other
+}
+#[unsafe(no_mangle)]
+extern "C" fn ladybird_gfx_font_cascade_list_frozen(_raw: *const std::ffi::c_void) -> *const std::ffi::c_void {
+ std::ptr::null()
+}
+#[unsafe(no_mangle)]
+extern "C" fn ladybird_gfx_font_ref(_raw: *const std::ffi::c_void) {}
+#[unsafe(no_mangle)]
+extern "C" fn ladybird_gfx_font_unref(_raw: *const std::ffi::c_void) {}
+#[unsafe(no_mangle)]
+unsafe extern "C" fn ladybird_gfx_decoded_image_frame_retain(
+ frame: *const std::ffi::c_void,
+ out_snapshot: *mut libgfx_rust::image_frame::FfiImageFrameSnapshot,
+) -> *mut std::ffi::c_void {
+ // Test frames are dangling pointers; their address stands in for the id.
+ unsafe {
+ *out_snapshot = libgfx_rust::image_frame::FfiImageFrameSnapshot {
+ id: frame as usize as u64,
+ ..Default::default()
+ }
+ };
+ frame.cast_mut()
+}
+#[unsafe(no_mangle)]
+extern "C" fn ladybird_gfx_decoded_image_frame_release(_frame: *mut std::ffi::c_void) {}
+#[unsafe(no_mangle)]
+unsafe extern "C" fn ladybird_gfx_font_snapshot(
+ font: *const std::ffi::c_void,
+ out_snapshot: *mut libgfx_rust::font::FfiFontSnapshot,
+) {
+ // Test fonts are dangling pointers; their address stands in for the id.
+ unsafe {
+ *out_snapshot = libgfx_rust::font::FfiFontSnapshot {
+ id: font as usize as u64,
+ ..Default::default()
+ }
+ };
+}
+#[unsafe(no_mangle)]
+unsafe extern "C" fn unicode_rust_idna_to_ascii(
+ domain: *const u8,
+ domain_length: usize,
+ _options: *const c_void,
+ context: *mut c_void,
+ on_success: unsafe extern "C" fn(*mut c_void, *const u8, usize),
+) {
+ // The style tests only need ASCII URL hosts. The production build uses LibUnicode's C++
+ // implementation for the full IDNA algorithm.
+ let domain = unsafe { ak::slice_from_raw_parts(domain, domain_length) };
+ if domain.is_ascii() {
+ unsafe { on_success(context, domain.as_ptr(), domain.len()) };
+ }
+}
+#[unsafe(no_mangle)]
+extern "C" fn ladybird_gfx_process_next_structural_epoch() -> u64 {
+ static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
+ NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
+}
+#[unsafe(no_mangle)]
+extern "C" fn unicode_layout_segmenter_destroy(_handle: *mut std::ffi::c_void) {}
diff --git a/Libraries/LibWeb/Rust/src/css/style_compute/tests.rs b/Libraries/LibWeb/Rust/src/css/style_compute/tests.rs
new file mode 100644
index 00000000000..43dde1eed80
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style_compute/tests.rs
@@ -0,0 +1,1043 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use super::*;
+use crate::css::style_value::StyleValueBox;
+
+#[test]
+fn all_transition_longhands_match_the_recursive_expansion_of_all() {
+ use crate::css::property_metadata::{longhand_is_logical_alias, property_id as prop};
+ fn expand(properties: &mut Vec<u16>, property: u16, writing_mode: u8, direction: u8) {
+ if property_is_shorthand(property) {
+ for &longhand in longhands_for_shorthand(property) {
+ expand(properties, longhand, writing_mode, direction);
+ }
+ } else if property != prop::CUSTOM {
+ properties.push(match longhand_is_logical_alias(property) {
+ true => map_logical_alias_to_physical(property, writing_mode, direction),
+ false => property,
+ });
+ }
+ }
+ for writing_mode in 0..WRITING_MODE_COUNT as u8 {
+ for direction in 0..DIRECTION_COUNT as u8 {
+ let mut expected = Vec::new();
+ expand(&mut expected, prop::ALL, writing_mode, direction);
+ assert_eq!(
+ crate::css::computed_values::all_transition_longhands(writing_mode, direction),
+ &expected[..]
+ );
+ }
+ }
+}
+
+#[test]
+fn url_dependencies_only_read_a_base_for_relative_urls() {
+ for (url, needs_base) in [
+ ("https://example.com/paint.svg#fill", false),
+ ("data:image/svg+xml,paint", false),
+ ("https://example.com/色.svg#fill", false),
+ ("paint.svg#fill", true),
+ ("色.svg#fill", true),
+ ("/paint.svg#fill", true),
+ ("//example.com/paint.svg#fill", true),
+ ("#fill", false),
+ ("", false),
+ ] {
+ let value = StyleValueData::Url(StyleValueBox::new(UrlPayload {
+ url: crate::css::style_value::RetainedString::from_utf16(&url.encode_utf16().collect::<Vec<_>>()).unwrap(),
+ url_type: 0,
+ modifiers: crate::css::style_value::RetainedRequestUrlModifierList::from_retained_modifiers(Vec::new()),
+ }));
+ let dependencies = collect_external_value_dependencies(&value);
+ assert_eq!(dependencies.needs_document_base_url, needs_base, "{url}");
+ assert_eq!(dependencies.may_need_style_sheet_resource_context, needs_base, "{url}");
+ }
+}
+
+#[test]
+fn calculated_random_values_record_their_document_dependency() {
+ let number = || {
+ std::sync::Arc::new(crate::css::calc::CalcNode::Numeric(
+ crate::css::calc::CalcNumericValue::Number {
+ value: 1.0,
+ number_type: 0,
+ },
+ ))
+ };
+ let calculation = crate::css::calc::CalcNode::Random {
+ min: number(),
+ max: number(),
+ step: None,
+ sharing: RetainedStyleValueData::from_owned(StyleValueData::Keyword { keyword: keyword::AUTO }),
+ };
+ let value = StyleValueData::Calculated(StyleValueBox::new(CalculatedPayload {
+ rust_calculation: crate::css::calc::CalcNodeHandle::from_arc(std::sync::Arc::new(calculation)),
+ resolve_as_is_number: true,
+ resolve_as_base: 0,
+ resolved_type: crate::css::calc::FfiNumericType::from_calc(None),
+ has_percentages_resolve_as: false,
+ percentages_resolve_as: 0,
+ resolve_numbers_as_integers: false,
+ accepted_ranges: crate::css::style_value::RetainedNumericRangeList::empty(),
+ }));
+
+ assert!(external_value_dependencies(&value).uses_random_function);
+}
+
+#[test]
+fn effective_overflow_keywords_compute_together() {
+ let result = resolve_effective_overflow_keywords(keyword::VISIBLE, keyword::AUTO);
+ assert!(result.changed_x);
+ assert_eq!(result.x_keyword, keyword::AUTO);
+ assert!(!result.changed_y);
+ assert_eq!(result.y_keyword, keyword::AUTO);
+
+ let result = resolve_effective_overflow_keywords(keyword::CLIP, keyword::SCROLL);
+ assert!(result.changed_x);
+ assert_eq!(result.x_keyword, keyword::HIDDEN);
+ assert!(!result.changed_y);
+ assert_eq!(result.y_keyword, keyword::SCROLL);
+
+ let result = resolve_effective_overflow_keywords(keyword::VISIBLE, keyword::CLIP);
+ assert!(!result.changed_x);
+ assert!(!result.changed_y);
+}
+
+#[test]
+fn effective_color_scheme_follows_element_and_document_preferences() {
+ const AUTO: u8 = 0;
+ const DARK: u8 = 1;
+ const LIGHT: u8 = 2;
+
+ assert_eq!(resolve_effective_color_scheme(&[LIGHT, DARK], DARK, None), DARK);
+ assert_eq!(resolve_effective_color_scheme(&[DARK, LIGHT], LIGHT, None), LIGHT);
+ assert_eq!(resolve_effective_color_scheme(&[DARK, LIGHT], AUTO, None), DARK);
+ assert_eq!(
+ resolve_effective_color_scheme(&[AUTO], DARK, Some(&[LIGHT, DARK])),
+ DARK
+ );
+ assert_eq!(resolve_effective_color_scheme(&[], AUTO, Some(&[DARK])), DARK);
+ assert_eq!(resolve_effective_color_scheme(&[], AUTO, None), LIGHT);
+}
+
+#[test]
+fn color_keyword_classification_uses_rust_color_metadata() {
+ assert!(keyword_is_color(keyword::CURRENTCOLOR));
+ assert!(keyword_is_color(keyword::CANVAS));
+ assert!(keyword_is_color(keyword::_LIBWEB_BUTTONFACEHOVER));
+ assert!(!keyword_is_color(keyword::AUTO));
+}
+
+#[test]
+fn text_align_adjusts_match_parent_and_table_header_defaults() {
+ let result = compute_text_align_adjustment(keyword::MATCH_PARENT, false, true, keyword::START, false);
+ assert!(result.changed);
+ assert_eq!(result.keyword, keyword::RIGHT);
+ assert!(!result.inherited);
+
+ let result = compute_text_align_adjustment(keyword::_LIBWEB_INHERIT_OR_CENTER, true, true, keyword::JUSTIFY, true);
+ assert!(result.changed);
+ assert_eq!(result.keyword, keyword::JUSTIFY);
+ assert!(result.inherited);
+
+ let result = compute_text_align_adjustment(keyword::_LIBWEB_INHERIT_OR_CENTER, true, false, 0, true);
+ assert!(result.changed);
+ assert_eq!(result.keyword, keyword::CENTER);
+ assert!(!result.inherited);
+}
+
+fn element_adjustment_input() -> FfiBoxTypeTransformationInput {
+ FfiBoxTypeTransformationInput {
+ display: FfiDisplay::inline(),
+ position: keyword::STATIC,
+ float_value: keyword::NONE,
+ is_br_element: false,
+ is_document_element: false,
+ is_mathml_element: false,
+ is_mathml_mtable: false,
+ is_mathml_mtr: false,
+ is_mathml_mtd: false,
+ has_parent_display: false,
+ writing_mode: crate::css::css_enums::writing_mode::HORIZONTAL_TB,
+ parent_writing_mode: crate::css::css_enums::writing_mode::HORIZONTAL_TB,
+ is_svg_element: false,
+ parent_display: FfiDisplay::block(),
+ is_wbr_element: false,
+ disallow_display_contents: false,
+ rewrite_inline_flow: false,
+ is_button_element: false,
+ force_line_height_normal: false,
+ check_input_line_height: false,
+ hide_audio_without_controls: false,
+ is_table_element: false,
+ force_position_static: false,
+ force_symbol_display_inline: false,
+ webkit_box_layout_transformation_applies: false,
+ }
+}
+
+#[test]
+fn element_styles_adjust_from_marshaled_facts() {
+ let mut input = element_adjustment_input();
+ input.disallow_display_contents = true;
+ let adjustment = adjust_element_style(&input, FfiDisplay::contents(), keyword::LEFT);
+ assert!(adjustment.changed_display);
+ assert!(adjustment.display.is_none());
+
+ input = element_adjustment_input();
+ input.is_button_element = true;
+ let adjustment = adjust_element_style(&input, FfiDisplay::inline(), keyword::LEFT);
+ assert!(adjustment.changed_display);
+ assert!(adjustment.display.is_inline_block());
+
+ input = element_adjustment_input();
+ input.is_table_element = true;
+ let adjustment = adjust_element_style(&input, FfiDisplay::block(), keyword::_LIBWEB_CENTER);
+ assert!(adjustment.changed_text_align);
+ assert_eq!(adjustment.text_align, keyword::START);
+
+ input = element_adjustment_input();
+ input.check_input_line_height = true;
+ let adjustment = adjust_element_style(&input, FfiDisplay::inline(), keyword::LEFT);
+ assert!(should_clamp_input_line_height(
+ &adjustment,
+ &FfiInputLineHeightMetrics {
+ current_line_height: 12.0,
+ minimum_line_height: 16.0,
+ }
+ ));
+ assert!(!should_clamp_input_line_height(
+ &adjustment,
+ &FfiInputLineHeightMetrics {
+ current_line_height: 18.0,
+ minimum_line_height: 16.0,
+ }
+ ));
+}
+
+#[test]
+fn element_style_adjustments_follow_box_type_transformation() {
+ let mut input = element_adjustment_input();
+ input.is_button_element = true;
+ input.position = keyword::ABSOLUTE;
+
+ let adjustments = compute_element_style_adjustments(&input, keyword::LEFT);
+ assert!(adjustments.box_type.changed_display);
+ assert!(adjustments.box_type.display.is_block_outside());
+ assert!(adjustments.element_style.changed_display);
+ assert!(adjustments.element_style.display.is_flow_root_inside());
+}
+
+fn test_context() -> FfiLengthResolutionContext {
+ FfiLengthResolutionContext {
+ viewport_width: 800.0,
+ viewport_height: 600.0,
+ font_metrics: FfiFontMetrics {
+ font_size: 16.0,
+ x_height: 8.0,
+ cap_height: 11.0,
+ zero_advance: 7.5,
+ line_height: 19.0,
+ },
+ root_font_metrics: FfiFontMetrics {
+ font_size: 20.0,
+ x_height: 10.0,
+ cap_height: 14.0,
+ zero_advance: 9.0,
+ line_height: 24.0,
+ },
+ font_metrics_depend_on_viewport_metrics: false,
+ root_font_metrics_depend_on_viewport_metrics: true,
+ 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,
+ }
+}
+
+fn unit_code(name: &str) -> usize {
+ LENGTH_UNIT_NAMES.iter().position(|&n| n == name).unwrap()
+}
+
+#[test]
+fn px_is_unchanged() {
+ let result = absolutize_length(4.0, unit_code("px"), &test_context());
+ assert!(result.handled);
+ assert!(!result.changed);
+}
+
+#[test]
+fn font_relative_units_resolve() {
+ let context = test_context();
+ let em = absolutize_length(2.0, unit_code("em"), &context);
+ assert!(em.changed);
+ assert_eq!(em.px, 32.0);
+ assert!(!em.resolved_viewport_relative_length);
+
+ let rem = absolutize_length(2.0, unit_code("rem"), &context);
+ assert_eq!(rem.px, 40.0);
+ assert!(rem.resolved_viewport_relative_length);
+
+ assert_eq!(absolutize_length(1.0, unit_code("lh"), &context).px, 19.0);
+ assert_eq!(absolutize_length(1.0, unit_code("rch"), &context).px, 9.0);
+}
+
+#[test]
+fn font_size_recascade_resolves_em_without_a_host_context() {
+ let percentage = StyleValueData::Percentage { value: 200.0 };
+ let em = StyleValueData::Length {
+ value: 2.0,
+ unit: unit_code("em") as u8,
+ };
+ let final_percentage = StyleValueData::Percentage { value: 50.0 };
+ let values = [None, Some(&percentage), Some(&em), Some(&final_percentage)];
+ let default_size = CssPixels::from_integer(13);
+ let batch = recascade_font_size_batch(
+ values.len(),
+ |index| values[index],
+ |_| 1.0,
+ |_| true,
+ 0,
+ default_size.raw_value(),
+ false,
+ default_size.raw_value(),
+ FontSizeRecascadeDocumentInputs {
+ root_font_size: 16.0,
+ root_effective_zoom: 1.0,
+ root_font_metrics_depend_on_viewport_metrics: false,
+ viewport_width: 800.0,
+ viewport_height: 600.0,
+ },
+ None,
+ );
+ assert!(batch.status == FontSizeRecascadeStatus::Complete);
+ assert_eq!(batch.next_index, values.len());
+ assert_eq!(batch.current_size_raw, CssPixels::from_integer(26).raw_value());
+}
+
+#[test]
+fn font_size_recascade_resolves_document_lengths() {
+ let rem = StyleValueData::Length {
+ value: 2.0,
+ unit: unit_code("rem") as u8,
+ };
+ let vw = StyleValueData::Length {
+ value: 10.0,
+ unit: unit_code("vw") as u8,
+ };
+ let values = [Some(&rem), Some(&vw)];
+ let batch = recascade_font_size_batch(
+ values.len(),
+ |index| values[index],
+ |_| 1.0,
+ |_| true,
+ 0,
+ CssPixels::from_integer(13).raw_value(),
+ false,
+ CssPixels::from_integer(13).raw_value(),
+ FontSizeRecascadeDocumentInputs {
+ root_font_size: 20.0,
+ root_effective_zoom: 1.0,
+ root_font_metrics_depend_on_viewport_metrics: false,
+ viewport_width: 800.0,
+ viewport_height: 600.0,
+ },
+ None,
+ );
+ assert!(batch.status == FontSizeRecascadeStatus::Complete);
+ assert_eq!(batch.current_size_raw, CssPixels::from_integer(80).raw_value());
+ assert!(batch.depends_on_viewport_metrics);
+}
+
+#[test]
+fn font_size_recascade_applies_each_ancestor_zoom_once() {
+ let px = StyleValueData::Length {
+ value: 10.0,
+ unit: unit_code("px") as u8,
+ };
+ let percentage = StyleValueData::Percentage { value: 200.0 };
+ let em = StyleValueData::Length {
+ value: 2.0,
+ unit: unit_code("em") as u8,
+ };
+ let values = [Some(&px), None, Some(&percentage), Some(&em)];
+ let zooms = [2.0, 6.0, 3.0, 1.5];
+ let batch = recascade_font_size_batch(
+ values.len(),
+ |index| values[index],
+ |index| zooms[index],
+ |_| true,
+ 0,
+ CssPixels::from_integer(13).raw_value(),
+ false,
+ CssPixels::from_integer(13).raw_value(),
+ FontSizeRecascadeDocumentInputs {
+ root_font_size: 20.0,
+ root_effective_zoom: 2.0,
+ root_font_metrics_depend_on_viewport_metrics: false,
+ viewport_width: 800.0,
+ viewport_height: 600.0,
+ },
+ None,
+ );
+ assert!(batch.status == FontSizeRecascadeStatus::Complete);
+ assert_eq!(batch.current_size_raw, CssPixels::from_integer(60).raw_value());
+}
+
+#[test]
+fn font_size_recascade_stops_for_a_length_that_needs_font_metrics() {
+ let ex = StyleValueData::Length {
+ value: 2.0,
+ unit: unit_code("ex") as u8,
+ };
+ let values = [Some(&ex)];
+ let batch = recascade_font_size_batch(
+ values.len(),
+ |index| values[index],
+ |_| 1.0,
+ |_| true,
+ 0,
+ CssPixels::from_integer(13).raw_value(),
+ false,
+ CssPixels::from_integer(13).raw_value(),
+ FontSizeRecascadeDocumentInputs {
+ root_font_size: 16.0,
+ root_effective_zoom: 1.0,
+ root_font_metrics_depend_on_viewport_metrics: false,
+ viewport_width: 800.0,
+ viewport_height: 600.0,
+ },
+ None,
+ );
+ assert!(batch.status == FontSizeRecascadeStatus::NeedsLengthResolution);
+ assert_eq!(batch.next_index, 0);
+}
+
+#[test]
+fn viewport_relative_units_resolve() {
+ let context = test_context();
+ let vw = absolutize_length(50.0, unit_code("vw"), &context);
+ assert_eq!(vw.px, 400.0);
+ assert!(vw.resolved_viewport_relative_length);
+ assert_eq!(absolutize_length(50.0, unit_code("vmin"), &context).px, 300.0);
+ assert_eq!(absolutize_length(50.0, unit_code("dvmax"), &context).px, 400.0);
+}
+
+#[test]
+fn absolute_units_resolve() {
+ let context = test_context();
+ let inch = absolutize_length(1.0, unit_code("in"), &context);
+ assert!(inch.changed);
+ assert_eq!(inch.px, 96.0);
+}
+
+#[test]
+fn font_weight_keywords_compute() {
+ let bolder = StyleValueData::Keyword {
+ keyword: keyword::BOLDER,
+ };
+ assert_eq!(compute_font_weight(&bolder, 300.0).value, 400.0);
+ assert_eq!(compute_font_weight(&bolder, 400.0).value, 700.0);
+ assert_eq!(compute_font_weight(&bolder, 700.0).value, 900.0);
+ assert_eq!(compute_font_weight(&bolder, 900.0).value, 900.0);
+
+ let lighter = StyleValueData::Keyword {
+ keyword: keyword::LIGHTER,
+ };
+ assert_eq!(compute_font_weight(&lighter, 50.0).value, 50.0);
+ assert_eq!(compute_font_weight(&lighter, 400.0).value, 100.0);
+ assert_eq!(compute_font_weight(&lighter, 700.0).value, 400.0);
+ assert_eq!(compute_font_weight(&lighter, 900.0).value, 700.0);
+
+ assert_eq!(
+ compute_font_weight(
+ &StyleValueData::Keyword {
+ keyword: keyword::NORMAL
+ },
+ 700.0
+ )
+ .value,
+ 400.0
+ );
+ assert_eq!(
+ compute_font_weight(&StyleValueData::Keyword { keyword: keyword::BOLD }, 100.0).value,
+ 700.0
+ );
+ assert!(compute_font_weight(&StyleValueData::Number { value: 512.0 }, 100.0).unchanged);
+}
+
+#[test]
+fn font_width_keywords_compute() {
+ assert_eq!(
+ compute_font_width(&StyleValueData::Keyword {
+ keyword: keyword::ULTRA_CONDENSED
+ })
+ .value,
+ 50.0
+ );
+ assert_eq!(
+ compute_font_width(&StyleValueData::Keyword {
+ keyword: keyword::SEMI_EXPANDED
+ })
+ .value,
+ 112.5
+ );
+ assert_eq!(
+ compute_font_width(&StyleValueData::Keyword {
+ keyword: keyword::NORMAL
+ })
+ .value,
+ 100.0
+ );
+ assert!(compute_font_width(&StyleValueData::Percentage { value: 80.0 }).unchanged);
+}
+
+#[test]
+fn font_size_keywords_compute() {
+ let sixteen = CssPixels::from_integer(16);
+ let medium = compute_font_size(
+ &StyleValueData::Keyword {
+ keyword: keyword::MEDIUM,
+ },
+ 0,
+ sixteen,
+ 0,
+ sixteen,
+ 1.0,
+ );
+ assert_eq!(medium.value, 16.0);
+ let large = compute_font_size(
+ &StyleValueData::Keyword {
+ keyword: keyword::LARGE,
+ },
+ 0,
+ sixteen,
+ 0,
+ sixteen,
+ 1.0,
+ );
+ assert_eq!(large.value, 18.0);
+ let percent = compute_font_size(
+ &StyleValueData::Percentage { value: 150.0 },
+ 0,
+ sixteen,
+ 0,
+ sixteen,
+ 1.0,
+ );
+ assert_eq!(percent.value, 24.0);
+ let math = compute_font_size(
+ &StyleValueData::Keyword { keyword: keyword::MATH },
+ 1,
+ sixteen,
+ 0,
+ sixteen,
+ 1.0,
+ );
+ assert_eq!(math.value, CssPixels::from_integer(16).scaled(0.71).to_double());
+ let math_two_levels = compute_font_size(
+ &StyleValueData::Keyword { keyword: keyword::MATH },
+ 2,
+ sixteen,
+ 0,
+ sixteen,
+ 1.0,
+ );
+ assert_eq!(
+ math_two_levels.value,
+ CssPixels::from_integer(16).scaled(0.71f64.powi(2)).to_double()
+ );
+}
+
+#[test]
+fn math_depth_computes() {
+ let auto_add = StyleValueData::Keyword {
+ keyword: keyword::AUTO_ADD,
+ };
+ assert_eq!(compute_math_depth(&auto_add, 2, true).value, 3.0);
+ assert_eq!(compute_math_depth(&auto_add, 2, false).value, 2.0);
+ assert_eq!(
+ compute_math_depth(&StyleValueData::Integer { value: 5 }, 2, true).value,
+ 5.0
+ );
+ assert_eq!(
+ compute_math_depth(&StyleValueData::Keyword { keyword: keyword::AUTO }, 4, true).value,
+ 4.0
+ );
+}
+
+#[test]
+fn line_height_computes() {
+ let sixteen = CssPixels::from_integer(16);
+ assert!(
+ compute_line_height(
+ &StyleValueData::Keyword {
+ keyword: keyword::NORMAL
+ },
+ sixteen
+ )
+ .unchanged
+ );
+ assert!(compute_line_height(&StyleValueData::Number { value: 1.5 }, sixteen).unchanged);
+ assert_eq!(
+ compute_line_height(&StyleValueData::Percentage { value: 150.0 }, sixteen).value,
+ 24.0
+ );
+}
+
+#[test]
+fn border_width_snaps() {
+ // 2.5px at 2 dppx is an integer number of device pixels: unchanged.
+ let length = StyleValueData::Length {
+ value: 2.5,
+ unit: unit_code("px") as u8,
+ };
+ assert_eq!(compute_border_or_outline_width(&length, 2.0, 1.0, None).value, 2.5);
+ // 0.4px at 1 dppx rounds up to 1 device pixel.
+ let thin = StyleValueData::Length {
+ value: 0.4,
+ unit: unit_code("px") as u8,
+ };
+ assert_eq!(compute_border_or_outline_width(&thin, 1.0, 1.0, None).value, 1.0);
+ // medium is 3px.
+ assert_eq!(
+ compute_border_or_outline_width(
+ &StyleValueData::Keyword {
+ keyword: keyword::MEDIUM
+ },
+ 1.0,
+ 1.0,
+ None
+ )
+ .value,
+ 3.0
+ );
+}
+
+#[test]
+fn corner_shapes_map_to_superellipse_parameters() {
+ assert_eq!(
+ compute_corner_shape_parameter(&StyleValueData::Keyword {
+ keyword: keyword::ROUND
+ })
+ .value,
+ 1.0
+ );
+ assert_eq!(
+ compute_corner_shape_parameter(&StyleValueData::Keyword {
+ keyword: keyword::NOTCH
+ })
+ .value,
+ f64::NEG_INFINITY
+ );
+}
+
+#[test]
+fn highlight_longhand_inheritance() {
+ use crate::css::property_metadata::property_id;
+ let selection = crate::css::selector::PseudoElementType::Selection as u8;
+ let inherit = StyleValueData::Keyword {
+ keyword: keyword::INHERIT,
+ };
+ let unset = StyleValueData::Keyword {
+ keyword: keyword::UNSET,
+ };
+ let initial = StyleValueData::Keyword {
+ keyword: keyword::INITIAL,
+ };
+ let currentcolor = StyleValueData::Keyword {
+ keyword: keyword::CURRENTCOLOR,
+ };
+
+ // A supported property without a cascaded value, or with inherit or unset, takes the parent
+ // highlight's value whether or not it is an inherited property.
+ assert!(highlight_longhand_inherits(
+ None,
+ selection,
+ property_id::BACKGROUND_COLOR
+ ));
+ assert!(highlight_longhand_inherits(
+ Some(&inherit),
+ selection,
+ property_id::BACKGROUND_COLOR
+ ));
+ assert!(highlight_longhand_inherits(
+ Some(&unset),
+ selection,
+ property_id::BACKGROUND_COLOR
+ ));
+ assert!(highlight_longhand_inherits(None, selection, property_id::COLOR));
+
+ // Any other cascaded value stands, currentcolor included.
+ assert!(!highlight_longhand_inherits(
+ Some(&initial),
+ selection,
+ property_id::BACKGROUND_COLOR
+ ));
+ assert!(!highlight_longhand_inherits(
+ Some(&currentcolor),
+ selection,
+ property_id::COLOR
+ ));
+
+ // A property the highlight cannot carry keeps the ordinary decision.
+ assert!(!highlight_longhand_inherits(None, selection, property_id::DISPLAY));
+}
+
+#[test]
+fn longhand_decisions() {
+ use crate::css::property_metadata::{FIRST_INHERITED_PROPERTY_ID, LAST_LONGHAND_PROPERTY_ID};
+ let inherited_id = FIRST_INHERITED_PROPERTY_ID;
+ let reset_id = LAST_LONGHAND_PROPERTY_ID;
+
+ // Missing value: inherited properties inherit, reset properties go initial.
+ let missing_inherited = longhand_decision(None, inherited_id);
+ assert!(missing_inherited.should_inherit);
+ let missing_reset = longhand_decision(None, reset_id);
+ assert!(!missing_reset.should_inherit);
+ assert!(missing_reset.use_initial_without_inherit);
+
+ // Explicit inherit on a reset property inherits.
+ let inherit = StyleValueData::Keyword {
+ keyword: keyword::INHERIT,
+ };
+ let explicit = longhand_decision(Some(&inherit), reset_id);
+ assert!(explicit.should_inherit);
+
+ // unset: inherit for inherited properties, initial for reset ones.
+ let unset = StyleValueData::Keyword {
+ keyword: keyword::UNSET,
+ };
+ assert!(longhand_decision(Some(&unset), inherited_id).should_inherit);
+ let unset_reset = longhand_decision(Some(&unset), reset_id);
+ assert!(!unset_reset.should_inherit);
+ assert!(unset_reset.use_initial_without_inherit);
+
+ // currentcolor in the color property inherits.
+ let currentcolor = StyleValueData::Keyword {
+ keyword: keyword::CURRENTCOLOR,
+ };
+ assert!(longhand_decision(Some(&currentcolor), crate::css::property_metadata::property_id::COLOR).should_inherit);
+ assert!(!longhand_decision(Some(&currentcolor), reset_id).should_inherit);
+}
+
+#[test]
+fn container_relative_units_without_snapshotted_bases_are_unhandled() {
+ assert!(!absolutize_length(1.0, unit_code("cqw"), &test_context()).handled);
+}
+
+#[test]
+fn container_relative_units_resolve_from_snapshotted_bases() {
+ let mut context = test_context();
+ context.has_container_width_basis = true;
+ context.has_container_height_basis = true;
+ context.container_width_basis = 400.0;
+ context.container_height_basis = 200.0;
+
+ assert_eq!(absolutize_length(10.0, unit_code("cqw"), &context).px, 40.0);
+ assert_eq!(absolutize_length(10.0, unit_code("cqh"), &context).px, 20.0);
+ assert_eq!(absolutize_length(10.0, unit_code("cqi"), &context).px, 40.0);
+ assert_eq!(absolutize_length(10.0, unit_code("cqb"), &context).px, 20.0);
+ assert_eq!(absolutize_length(10.0, unit_code("cqmin"), &context).px, 20.0);
+ assert_eq!(absolutize_length(10.0, unit_code("cqmax"), &context).px, 40.0);
+
+ context.subject_inline_axis_is_horizontal = false;
+ assert_eq!(absolutize_length(10.0, unit_code("cqi"), &context).px, 20.0);
+ assert_eq!(absolutize_length(10.0, unit_code("cqb"), &context).px, 40.0);
+}
+
+#[test]
+fn container_relative_viewport_fallback_records_its_dependency() {
+ let mut dependency_was_recorded = false;
+ let mut context = test_context();
+ context.has_container_width_basis = true;
+ context.container_width_basis = 800.0;
+ context.container_width_basis_depends_on_viewport_metrics = true;
+ context.resolved_viewport_relative_length = &raw mut dependency_was_recorded;
+
+ let result = absolutize_length(10.0, unit_code("cqw"), &context);
+ assert_eq!(result.px, 80.0);
+ assert!(result.resolved_viewport_relative_length);
+ assert!(dependency_was_recorded);
+}
+
+fn svg_axis_case(svg: bool, vertical: bool) -> [f64; 3] {
+ use crate::css::property_metadata::property_id as prop;
+ let zoom = (prop::ZOOM, retained_new(StyleValueData::Number { value: 2.0 }));
+ let mut store = crate::css::cascaded_properties::CascadedPropertyStore::new();
+ store.seed_retained_property(
+ prop::WRITING_MODE,
+ retained_new(StyleValueData::Keyword {
+ keyword: if vertical {
+ keyword::VERTICAL_RL
+ } else {
+ keyword::HORIZONTAL_TB
+ },
+ }),
+ false,
+ false,
+ );
+ for (property, value, unit) in [
+ (prop::WIDTH, 7.0, "px"),
+ (prop::HEIGHT, 1.0, "rem"),
+ (prop::MARGIN_LEFT, 10.0, "vi"),
+ ] {
+ store.seed_retained_property(
+ property,
+ retained_new(StyleValueData::Length {
+ value,
+ unit: unit_code(unit) as u8,
+ }),
+ false,
+ false,
+ );
+ }
+ let mut box_type_input = element_adjustment_input();
+ box_type_input.is_svg_element = svg;
+ let environment = FfiStyleComputationEnvironment {
+ box_type_input,
+ 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: false,
+ sibling_count: 0,
+ sibling_index: 0,
+ random_base_values: std::ptr::null(),
+ random_base_value_count: 0,
+ document_base_url: std::ptr::null(),
+ document_base_url_length: 0,
+ style_sheet_resource_contexts: std::ptr::null(),
+ style_sheet_resource_context_count: 0,
+ device_pixels_per_css_pixel: 1.0,
+ initial_font_size_raw: 1024,
+ default_font_size_raw: 1024,
+ root_effective_zoom: 1.0,
+ };
+ let context = FfiLengthResolutionContext {
+ viewport_width: 200.0,
+ viewport_height: 100.0,
+ root_font_metrics: FfiFontMetrics {
+ font_size: 20.0,
+ ..Default::default()
+ },
+ subject_inline_axis_is_horizontal: true,
+ zoom: 1.0,
+ ..Default::default()
+ };
+ crate::css::computed_values::with_default_seed(&crate::css::computed_values::DefaultGroups::default(), |seed| {
+ let mut writer = crate::css::computed_values::GroupValuesWriter::seeded_for_child(
+ seed,
+ seed,
+ [zoom].into_iter(),
+ LonghandTableFlags::empty(),
+ 0,
+ );
+ let mut results = empty_longhand_driver_results();
+ let mut color_scheme = -1;
+ // SAFETY: All environment slices are empty and the borrowed contexts live throughout the drive.
+ unsafe {
+ drive_property_computation(
+ &mut writer,
+ &store,
+ None,
+ None,
+ &environment,
+ None,
+ LONGHAND_DRIVE_PHASE_REMAINING,
+ Some(&context),
+ None,
+ &mut results,
+ &mut color_scheme,
+ false,
+ );
+ }
+ [prop::WIDTH, prop::HEIGHT, prop::MARGIN_LEFT].map(|property| match writer.get(property).unwrap().data() {
+ StyleValueData::Length { value, unit } if *unit == px_length_unit() => *value,
+ _ => panic!("expected absolute computed length"),
+ })
+ })
+}
+
+#[test]
+fn svg_vertical_axis_preserves_unzoomed_lengths() {
+ assert_eq!(svg_axis_case(true, true), [7.0, 20.0, 10.0]);
+}
+#[test]
+fn html_vertical_axis_applies_zoom() {
+ assert_eq!(svg_axis_case(false, true), [14.0, 40.0, 20.0]);
+}
+#[test]
+fn svg_horizontal_axis_preserves_unzoomed_lengths() {
+ assert_eq!(svg_axis_case(true, false), [7.0, 20.0, 20.0]);
+}
+fn font_phase_axis_case(
+ declared: Option<u16>,
+ parent_mode: u16,
+ inherit_font: bool,
+ context_horizontal: bool,
+) -> [f64; 2] {
+ use crate::css::property_metadata::property_id as prop;
+ let zoom = (prop::ZOOM, retained_new(StyleValueData::Number { value: 1.0 }));
+ let mut store = crate::css::cascaded_properties::CascadedPropertyStore::new();
+ if let Some(keyword) = declared {
+ store.seed_retained_property(
+ prop::WRITING_MODE,
+ retained_new(StyleValueData::Keyword { keyword }),
+ false,
+ false,
+ );
+ }
+ if !inherit_font {
+ store.seed_retained_property(
+ prop::FONT_SIZE,
+ retained_new(StyleValueData::Length {
+ value: 10.0,
+ unit: unit_code("vi") as u8,
+ }),
+ false,
+ false,
+ );
+ }
+ store.seed_retained_property(
+ prop::LINE_HEIGHT,
+ retained_new(StyleValueData::Length {
+ value: 10.0,
+ unit: unit_code("vb") as u8,
+ }),
+ false,
+ false,
+ );
+ let parent = |property| match property {
+ prop::WRITING_MODE => retained_new(StyleValueData::Keyword { keyword: parent_mode }),
+ prop::FONT_SIZE => retained_new(StyleValueData::Length {
+ value: 23.0,
+ unit: px_length_unit(),
+ }),
+ prop::FONT_WEIGHT => retained_new(StyleValueData::Number { value: 400.0 }),
+ _ => initial_value_handle(property).clone(),
+ };
+ crate::css::style::ViewLonghands::with_test_record(parent, |parent| {
+ let snapshot = ParentSnapshot::from_view(parent, None, false);
+ let mut box_type_input = element_adjustment_input();
+ box_type_input.is_svg_element = false;
+ let environment = FfiStyleComputationEnvironment {
+ box_type_input,
+ 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: false,
+ sibling_count: 0,
+ sibling_index: 0,
+ random_base_values: std::ptr::null(),
+ random_base_value_count: 0,
+ document_base_url: std::ptr::null(),
+ document_base_url_length: 0,
+ style_sheet_resource_contexts: std::ptr::null(),
+ style_sheet_resource_context_count: 0,
+ device_pixels_per_css_pixel: 1.0,
+ initial_font_size_raw: 1024,
+ default_font_size_raw: 1024,
+ root_effective_zoom: 1.0,
+ };
+ let context = FfiLengthResolutionContext {
+ viewport_width: 800.0,
+ viewport_height: 600.0,
+ root_font_metrics: FfiFontMetrics {
+ font_size: 20.0,
+ ..Default::default()
+ },
+ subject_inline_axis_is_horizontal: context_horizontal,
+ zoom: 1.0,
+ ..Default::default()
+ };
+ crate::css::computed_values::with_default_seed(&crate::css::computed_values::DefaultGroups::default(), |seed| {
+ let mut writer = crate::css::computed_values::GroupValuesWriter::seeded_for_child(
+ seed,
+ seed,
+ [zoom].into_iter(),
+ LonghandTableFlags::empty(),
+ 0,
+ );
+ let mut results = empty_longhand_driver_results();
+ let mut color_scheme = -1;
+ // SAFETY: All environment slices are empty and the borrowed contexts live throughout the drive.
+ for phase in [LONGHAND_DRIVE_PHASE_FONT, LONGHAND_DRIVE_PHASE_LINE_HEIGHT] {
+ unsafe {
+ drive_property_computation(
+ &mut writer,
+ &store,
+ Some(&snapshot),
+ None,
+ &environment,
+ None,
+ phase,
+ Some(&context),
+ None,
+ &mut results,
+ &mut color_scheme,
+ false,
+ );
+ }
+ }
+ [prop::FONT_SIZE, prop::LINE_HEIGHT].map(|property| match writer.get(property).unwrap().data() {
+ StyleValueData::Length { value, unit } if *unit == px_length_unit() => *value,
+ _ => panic!("expected absolute computed length"),
+ })
+ })
+ })
+}
+
+#[test]
+fn font_and_line_height_follow_explicit_vertical_axis() {
+ assert_eq!(
+ font_phase_axis_case(Some(keyword::VERTICAL_RL), keyword::HORIZONTAL_TB, false, true),
+ [60.0, 80.0]
+ );
+}
+#[test]
+fn font_and_line_height_follow_explicit_horizontal_axis() {
+ assert_eq!(
+ font_phase_axis_case(Some(keyword::HORIZONTAL_TB), keyword::VERTICAL_RL, false, false),
+ [80.0, 60.0]
+ );
+}
+#[test]
+fn font_and_line_height_follow_inherited_axis() {
+ assert_eq!(
+ font_phase_axis_case(None, keyword::VERTICAL_RL, false, true),
+ [60.0, 80.0]
+ );
+}
+#[test]
+fn inherited_computed_font_size_is_not_reinterpreted_in_child_axis() {
+ assert_eq!(
+ font_phase_axis_case(Some(keyword::VERTICAL_RL), keyword::HORIZONTAL_TB, true, true),
+ [23.0, 80.0]
+ );
+}
+#[test]
+fn font_axis_initial_keyword_uses_initial_writing_mode() {
+ assert_eq!(
+ font_phase_axis_case(Some(keyword::INITIAL), keyword::VERTICAL_RL, false, false),
+ [80.0, 60.0]
+ );
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style_rule.rs b/Libraries/LibWeb/Rust/src/css/style_rule.rs
index a69019034a7..bc4dcf49e2d 100644
--- a/Libraries/LibWeb/Rust/src/css/style_rule.rs
+++ b/Libraries/LibWeb/Rust/src/css/style_rule.rs
@@ -5,7 +5,7 @@
*/
use crate::css::css_tokenizer::TokenizerInput;
-use crate::css::declaration_block::{DeclarationBlock, DeclarationBlockData};
+use crate::css::declaration_block::{DeclarationBlock, SharedDeclarationBlock};
use crate::css::selector_parser::{
RustParsedSelectorList, SelectorParsingMode, SelectorType, StyleNestingParent, parse_selector_list,
};
@@ -18,7 +18,7 @@ pub(crate) struct StyleRule {
}
impl StyleRule {
- pub(crate) fn new(selectors: Arc<RustParsedSelectorList>, declarations: Arc<DeclarationBlockData>) -> Self {
+ pub(crate) fn new(selectors: Arc<RustParsedSelectorList>, declarations: SharedDeclarationBlock) -> Self {
Self {
selectors: RefCell::new(selectors),
declarations: DeclarationBlock::new(declarations),
@@ -29,10 +29,15 @@ impl StyleRule {
self.selectors.borrow().clone()
}
+ pub(crate) fn replace_selectors(&self, selectors: Arc<RustParsedSelectorList>) {
+ *self.selectors.borrow_mut() = selectors;
+ }
+
pub(crate) fn set_selector_text(
&self,
input: TokenizerInput<'_>,
namespaces: &[TokenizerInput<'_>],
+ declarations: crate::css::selector_arena::NamespaceDeclarations,
nesting_parent: StyleNestingParent,
) -> bool {
let selector_type = if nesting_parent == StyleNestingParent::None {
@@ -43,8 +48,11 @@ impl StyleRule {
let Ok(selectors) = parse_selector_list(input, namespaces, selector_type, SelectorParsingMode::Standard) else {
return false;
};
- *self.selectors.borrow_mut() =
- Arc::new(RustParsedSelectorList::new(selectors).adapt_for_nesting(nesting_parent));
+ *self.selectors.borrow_mut() = Arc::new(
+ selectors
+ .adapt_for_nesting(nesting_parent)
+ .into_list_declaring(nesting_parent, declarations),
+ );
true
}
}
@@ -71,16 +79,19 @@ mod tests {
fn native_publication_and_image_discovery_keep_style_data_immutable() {
use crate::css::style::StyleEngine;
use crate::css::style::bridge::publish_rule_declarations;
- use crate::css::style::program::{CascadeOrigin, RuleKind, StyleSheetObjectID};
+ use crate::css::style::pipeline::rule_store::{CascadeOrigin, RuleKind};
let rules = rules(".文字 { width: 13px; transition: width 1s; background-image: url(image.png); }");
let rule = &rules.rule_at(0);
let style = rule.style_rule();
assert!(style.declarations.is_immutable());
assert!(Arc::ptr_eq(&style.selectors(), &style.selectors.borrow()));
let declarations = rule.cascade_declarations().unwrap();
- assert!(Arc::ptr_eq(&declarations, &style.declarations.data()));
+ assert!(SharedDeclarationBlock::ptr_eq(
+ &declarations,
+ &style.declarations.data()
+ ));
let mut engine = StyleEngine::new();
- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);
+ let sheet = engine.add_sheet(CascadeOrigin::Author);
let id = engine.add_non_matching_rule(sheet, None, RuleKind::Style);
assert!(publish_rule_declarations(&mut engine, id.0 + 1, &declarations));
extern "C" fn image(context: *mut c_void, _: *const c_void) {
@@ -103,7 +114,7 @@ mod tests {
use crate::css::rule::rust_rule_list_clear;
use crate::css::style::StyleEngine;
use crate::css::style::bridge::{FfiNativeRuleTarget, native_rule_target};
- use crate::css::style::program::{CascadeOrigin, RuleKind, StyleSheetObjectID};
+ use crate::css::style::pipeline::rule_store::{CascadeOrigin, RuleKind};
use crate::css::style::rule_writes::publish_native_rule_declarations;
use crate::css::style_sheet::NativeStyleSheet;
@@ -118,23 +129,24 @@ mod tests {
drop(retained_rule);
let style = rule.style_rule();
let mut engine = StyleEngine::new();
- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);
+ let sheet = engine.add_sheet(CascadeOrigin::Author);
let id = engine.add_non_matching_rule(sheet, None, RuleKind::Style);
engine.register_native_rule(
id,
crate::css::rule::rust_rule_identity(&rule),
- rule.cascade_declarations(),
source.identity(),
- &[],
+ std::sync::Arc::default(),
Box::default(),
);
+ // NB: The engine reads the declarations through the rule, which holds the block published to it.
+ publish_native_rule_declarations(&mut engine, rule.cascade_declarations(), id);
// All fields are integers, nullable pointers, booleans, or enums whose zero variant is valid.
let mut target: FfiNativeRuleTarget = unsafe { std::mem::zeroed() };
assert!(native_rule_target(&mut engine, id.0 + 1, &mut target,));
- let snapshot = unsafe { Arc::from_raw(target.declarations.cast::<DeclarationBlockData>()) };
+ let snapshot = unsafe { SharedDeclarationBlock::from_raw(target.declarations.cast()) };
assert_eq!(target.source_identity, source_identity);
assert!(style.declarations.is_immutable());
- assert!(Arc::ptr_eq(&snapshot, &style.declarations.data()));
+ assert!(SharedDeclarationBlock::ptr_eq(&snapshot, &style.declarations.data()));
let identity = target.identity;
let version = target.declaration_version;
@@ -146,10 +158,10 @@ mod tests {
.expect("the rule owns its declarations");
publish_native_rule_declarations(&mut engine, rule.cascade_declarations(), owner);
assert!(native_rule_target(&mut engine, id.0 + 1, &mut target,));
- let edited_snapshot = unsafe { Arc::from_raw(target.declarations.cast::<DeclarationBlockData>()) };
+ let edited_snapshot = unsafe { SharedDeclarationBlock::from_raw(target.declarations.cast()) };
assert_eq!(target.identity, identity);
assert_ne!(target.declaration_version, version);
- assert!(!Arc::ptr_eq(&snapshot, &edited_snapshot));
+ assert!(!SharedDeclarationBlock::ptr_eq(&snapshot, &edited_snapshot));
drop(declarations);
drop(rule);
rust_rule_list_clear(&rules);
@@ -159,8 +171,8 @@ mod tests {
assert!(rule_lifetime.upgrade().is_none());
// The program reads its published snapshot, not a live document-local rule record.
assert!(native_rule_target(&mut engine, id.0 + 1, &mut target,));
- let surviving_snapshot = unsafe { Arc::from_raw(target.declarations.cast::<DeclarationBlockData>()) };
- assert!(Arc::ptr_eq(&edited_snapshot, &surviving_snapshot));
+ let surviving_snapshot = unsafe { SharedDeclarationBlock::from_raw(target.declarations.cast()) };
+ assert!(SharedDeclarationBlock::ptr_eq(&edited_snapshot, &surviving_snapshot));
assert_eq!(target.identity, identity);
assert_eq!(target.source_identity, source_identity);
engine.remove_style_rule(id);
@@ -168,18 +180,18 @@ mod tests {
drop(engine);
assert!(
snapshot
- .properties
+ .properties()
.iter()
.any(|property| property.property_id == property_id::WIDTH)
);
- assert!(edited_snapshot.properties.is_empty());
+ assert!(edited_snapshot.properties().is_empty());
assert_eq!(
- snapshot.custom_properties[0].name.units(),
+ snapshot.custom_properties().get(0).unwrap().name.units(),
"--幅".encode_utf16().collect::<Vec<_>>()
);
assert_eq!(
- edited_snapshot.custom_properties[0].name.units(),
- snapshot.custom_properties[0].name.units()
+ edited_snapshot.custom_properties().get(0).unwrap().name.units(),
+ snapshot.custom_properties().get(0).unwrap().name.units()
);
}
@@ -202,19 +214,24 @@ mod tests {
!style
.declarations
.data()
- .properties
+ .properties()
.iter()
.any(|property| property.property_id == property_id::WIDTH)
);
- assert!(Arc::ptr_eq(&fork.declarations.data(), &snapshot));
+ assert!(SharedDeclarationBlock::ptr_eq(&fork.declarations.data(), &snapshot));
assert!(
snapshot
- .properties
+ .properties()
.iter()
.any(|property| property.property_id == property_id::WIDTH)
);
let selectors: Vec<_> = ".編集".encode_utf16().collect();
- assert!(retained.set_selector_text(TokenizerInput::Utf16(&selectors), &[], StyleNestingParent::None));
+ assert!(retained.set_selector_text(
+ TokenizerInput::Utf16(&selectors),
+ &[],
+ Default::default(),
+ StyleNestingParent::None
+ ));
assert!(Arc::ptr_eq(&style.selectors(), &retained.selectors()));
assert!(!Arc::ptr_eq(&style.selectors(), &fork.selectors()));
}
diff --git a/Libraries/LibWeb/Rust/src/css/style_sheet.rs b/Libraries/LibWeb/Rust/src/css/style_sheet.rs
index 6b6ac872231..978f1bd4e6c 100644
--- a/Libraries/LibWeb/Rust/src/css/style_sheet.rs
+++ b/Libraries/LibWeb/Rust/src/css/style_sheet.rs
@@ -548,6 +548,51 @@ pub extern "C" fn rust_style_sheet_publish_conditions(
write_rule_conditions(host, conditions);
}
+/// Queue the rules of a user agent sheet a document just attached whose conditions do not hold in it: those of the
+/// others hold in a document until it hears otherwise.
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_style_sheet_publish_failing_conditions(
+ sheet: &NativeStyleSheet,
+ host: &crate::render_state::DocumentHost,
+ environment: FfiMediaEnvironment<'_>,
+) {
+ let mut conditions = Vec::new();
+ sheet.visit_conditions(environment.borrow(), true, &mut |identity, holds| {
+ if !holds {
+ conditions.push((identity, holds));
+ }
+ });
+ write_rule_conditions(host, conditions);
+}
+
+/// Have the process build the user agent index of the documents deciding with `sheet` alone, as `environment` says its
+/// conditions, off the thread of the document that would otherwise build it as it first needs it.
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_user_agent_style_sheet_index_ahead(
+ sheet: &NativeStyleSheet,
+ environment: FfiMediaEnvironment<'_>,
+) {
+ let mut failing = Vec::new();
+ sheet.visit_conditions(environment.borrow(), true, &mut |identity, holds| {
+ if !holds {
+ failing.push(identity);
+ }
+ });
+ crate::render_state::process_style().index_user_agent_sheet_ahead(sheet.identity(), &failing);
+}
+
+/// Lets go of the parsed sheets and sheet segments only the process keeps and nothing asked for lately.
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_style_prune_kept_data() {
+ crate::render_state::process_style().prune_kept_past_release();
+}
+
+/// Lets go of all the parsed sheets and sheet segments only the process keeps, for a process short of memory.
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_style_release_kept_data() {
+ crate::render_state::process_style().release_kept_past_release();
+}
+
/// Writes whether the conditions of each rule hold, for the rules the engine has.
fn write_rule_conditions(host: &crate::render_state::DocumentHost, conditions: Vec<(u64, bool)>) {
if conditions.is_empty() {
diff --git a/Libraries/LibWeb/Rust/src/css/style_value.rs b/Libraries/LibWeb/Rust/src/css/style_value.rs
index b700d2abfd9..10d33fe6ec7 100644
--- a/Libraries/LibWeb/Rust/src/css/style_value.rs
+++ b/Libraries/LibWeb/Rust/src/css/style_value.rs
@@ -11,16 +11,16 @@
//! [`StyleValueData`] is exposed to C++
//! through cbindgen so that hot accessors compile to inline field reads with no FFI call.
-use crate::css::ffi_support::OwnedArc;
+use crate::css::style_value_arc::OwnedStyleValue;
+use crate::css::style_value_arc::StyleValueArc;
use std::ffi::c_void;
-use std::sync::Arc;
use crate::css::css_tokenizer::{
- ParserSource, ParserTokenKind, SourcePosition, TextDetacher, TokenizerInput,
- trim_component_value_boundary_whitespace,
+ ParserSource, ParserTokenKind, SourcePosition, TokenizerInput, trim_component_value_boundary_whitespace,
};
+use crate::css::parser::arbitrary_substitution::SubstitutionFunctionsPresence;
use crate::css::parser::component_value::{
- ComponentKind, ComponentSerializationMode, ComponentValue, ComponentValueList, ComponentValueSlice,
+ ComponentKind, ComponentSerializationMode, ComponentValue, ComponentValueList,
};
use crate::css::serialize::{
original_component_values_source, serialize_component_values_to_utf16, trim_ascii_whitespace_start,
@@ -28,55 +28,6 @@ use crate::css::serialize::{
pub(crate) use crate::css::css_string::{CssString, CssStringList};
-/// A Rust-owned component-value slice. C++ retains the opaque allocation as part of an
-/// unresolved style value but never inspects its elements.
-#[repr(C)]
-pub struct RetainedComponentValueList {
- pointer: *mut c_void,
- length: usize,
- token_count: usize,
-}
-
-// SAFETY: This handle owns an immutable boxed slice. The bounds cover the erased element type.
-unsafe impl Send for RetainedComponentValueList where ComponentValue: Send {}
-unsafe impl Sync for RetainedComponentValueList where ComponentValue: Sync {}
-
-impl RetainedComponentValueList {
- pub(crate) fn from_values(values: impl Into<ComponentValueList>) -> Self {
- let values = values.into();
- let token_count = values.token_count;
- let mut values = values.into_vec().into_boxed_slice();
- TextDetacher::detach(|detacher| values.iter_mut().for_each(|value| value.detach(detacher)));
- let result = Self {
- pointer: values.as_mut_ptr().cast(),
- length: values.len(),
- token_count,
- };
- std::mem::forget(values);
- result
- }
-
- pub(crate) fn from_source(source: &[u16]) -> Self {
- let values = crate::css::parser::component_value::consume_a_counted_list_of_component_values(
- crate::css::css_tokenizer::tokenize_for_parser(source),
- )
- .unwrap_or_default();
- Self::from_values(values)
- }
-
- pub(crate) fn as_counted_slice(&self) -> ComponentValueSlice<'_> {
- ComponentValueSlice::with_token_count(self.as_slice(), self.token_count)
- }
-
- pub(crate) fn as_slice(&self) -> &[ComponentValue] {
- if self.pointer.is_null() {
- return &[];
- }
- // SAFETY: The allocation is owned by this handle and has `length` initialized elements.
- unsafe { ak::slice_from_raw_parts(self.pointer.cast(), self.length) }
- }
-}
-
enum ReifiedUnresolvedSegment {
Text(Vec<u16>),
Variable {
@@ -214,7 +165,10 @@ fn visit_reified_unresolved_segments(
// Appends the name of every custom property a `var()` or `inherit()` in `values` refers to, and returns whether every
// reference names its property with a plain identifier.
-fn scan_custom_property_references<'a>(values: &'a [ComponentValue], references: &mut Vec<&'a [u16]>) -> bool {
+fn scan_custom_property_references<'a>(
+ values: &'a [ComponentValue],
+ references: &mut smallvec::SmallVec<[&'a [u16]; 4]>,
+) -> bool {
let mut all_references_visible = true;
for value in values {
let ComponentKind::Function {
@@ -248,12 +202,13 @@ fn scan_custom_property_references<'a>(values: &'a [ComponentValue], references:
}
pub(crate) fn custom_property_references(value: &StyleValueData) -> Option<(Vec<&[u16]>, bool)> {
- let StyleValueData::Unresolved { components, .. } = value else {
+ let StyleValueData::Unresolved(unresolved_payload) = value else {
return None;
};
- let mut references = Vec::new();
- let all_references_visible = scan_custom_property_references(components.as_slice(), &mut references);
- Some((references, all_references_visible))
+ Some((
+ unresolved_payload.references().collect(),
+ unresolved_payload.references_visible(),
+ ))
}
/// Visits the Typed OM reification of an unresolved style value. Event 0 appends a text segment,
@@ -268,10 +223,10 @@ pub unsafe extern "C" fn rust_unresolved_style_value_visit_reification(
context: *mut c_void,
visit: unsafe extern "C" fn(*mut c_void, u8, *const u16, usize, bool),
) {
- let StyleValueData::Unresolved { components, .. } = (unsafe { &*value.cast::<StyleValueData>() }) else {
+ let StyleValueData::Unresolved(unresolved_payload) = (unsafe { &*value.cast::<StyleValueData>() }) else {
unreachable!("reification requires an unresolved style value");
};
- let segments = reify_unresolved_segments(components.as_slice());
+ let segments = reify_unresolved_segments(&unresolved_payload.components());
visit_reified_unresolved_segments(&segments, context, visit);
}
@@ -279,6 +234,17 @@ pub unsafe extern "C" fn rust_unresolved_style_value_visit_reification(
mod unresolved_component_tests {
use super::*;
+ #[test]
+ fn unresolved_text_is_kept_as_ascii_however_it_arrives() {
+ let units: Vec<u16> = "var(--x, 1px)".encode_utf16().collect();
+ let from_utf16 = RetainedString::from_text(TokenizerInput::Utf16(&units));
+ let from_ascii = RetainedString::from_text(TokenizerInput::Latin1(b"var(--x, 1px)"));
+ assert!(matches!(from_utf16.units(), TokenizerInput::Latin1(_)));
+ assert!(from_utf16 == from_ascii);
+ let wide: Vec<u16> = "var(--\u{96ea})".encode_utf16().chain([0xd800]).collect();
+ assert_eq!(RetainedString::from_text(TokenizerInput::Utf16(&wide)).to_utf16(), wide);
+ }
+
fn components(source: &str) -> Vec<ComponentValue> {
crate::css::parser::component_value::consume_a_list_of_component_values(
crate::css::css_tokenizer::tokenize_for_parser(source.as_bytes()),
@@ -314,76 +280,135 @@ mod unresolved_component_tests {
#[test]
fn reference_scan_reports_dynamic_names() {
let values = components("var(--one) [inherit(--two)] var(var(--dynamic))");
- let mut names = Vec::new();
- let all_visible = scan_custom_property_references(&values, &mut names);
- assert!(!all_visible);
+ let references = CustomPropertyReferences::scan(&values);
+ assert!(!references.all_visible);
assert_eq!(
- names,
+ references.names.to_vec(),
["--one", "--two", "--dynamic"].map(|name| name.encode_utf16().collect::<Vec<_>>())
);
}
-}
-impl Clone for RetainedComponentValueList {
- fn clone(&self) -> Self {
- Self::from_values(self.as_counted_slice().to_owned())
+ fn unresolved(source: &str) -> StyleValueData {
+ let units: Vec<u16> = source.encode_utf16().collect();
+ crate::css::parser::value_parser::unresolved_value_from_string(
+ &units,
+ crate::css::parser::arbitrary_substitution::SubstitutionFunctionsPresence::default(),
+ )
}
-}
-impl PartialEq for RetainedComponentValueList {
- fn eq(&self, other: &Self) -> bool {
- fn components_equal(first: &[ComponentValue], second: &[ComponentValue]) -> bool {
- first.len() == second.len()
- && first
- .iter()
- .zip(second)
- .all(|(first, second)| match (&first.kind, &second.kind) {
- (ComponentKind::Token(first), ComponentKind::Token(second)) => first == second,
- (
- ComponentKind::Function {
- name: first_name,
- values: first,
- },
- ComponentKind::Function {
- name: second_name,
- values: second,
- },
- ) => first_name == second_name && components_equal(first, second),
- (
- ComponentKind::SimpleBlock {
- opening: first_opening,
- values: first,
- },
- ComponentKind::SimpleBlock {
- opening: second_opening,
- values: second,
- },
- ) => first_opening == second_opening && components_equal(first, second),
- _ => false,
- })
- }
-
- // Parsing retained components depends on their token kinds, even when their normalized
- // serialization is identical. Source text and positions do not affect this comparison.
- components_equal(self.as_slice(), other.as_slice())
- }
-}
-
-impl Drop for RetainedComponentValueList {
- fn drop(&mut self) {
- if self.pointer.is_null() {
- return;
- }
- // SAFETY: `from_values` leaked exactly this boxed slice to the handle.
- unsafe {
- drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut(
- self.pointer.cast::<ComponentValue>(),
- self.length,
- )));
- }
+ fn reference_names(value: &StyleValueData) -> (Vec<String>, bool) {
+ let (names, all_visible) = custom_property_references(value).unwrap();
+ (
+ names.iter().map(|name| String::from_utf16(name).unwrap()).collect(),
+ all_visible,
+ )
+ }
+
+ #[test]
+ fn a_value_notes_the_custom_properties_it_references() {
+ assert_eq!(
+ reference_names(&unresolved("calc(var(--a) + inherit(--bc, 1px)) var(--a)")),
+ (vec!["--a".to_owned(), "--bc".to_owned(), "--a".to_owned()], true)
+ );
+ assert_eq!(reference_names(&unresolved("1px solid")), (vec![], true));
+ assert_eq!(
+ reference_names(&unresolved("var(var(--d))")),
+ (vec!["--d".to_owned()], false)
+ );
+ // NB: A name is noted with its escapes decoded, and a text that is not all ASCII is kept as
+ // UTF-16, after which the names follow aligned all the same.
+ assert_eq!(
+ reference_names(&unresolved("var(--\\61 b)")),
+ (vec!["--ab".to_owned()], true)
+ );
+ assert_eq!(
+ reference_names(&unresolved("var(--\u{96ea}) var(--abc)")),
+ (vec!["--\u{96ea}".to_owned(), "--abc".to_owned()], true)
+ );
+ let copied = unresolved("var(--\u{96ea}, x) var(--abc)").clone();
+ assert_eq!(
+ reference_names(&copied),
+ (vec!["--\u{96ea}".to_owned(), "--abc".to_owned()], true)
+ );
+ }
+
+ #[test]
+ fn a_value_notes_what_its_text_holds() {
+ let facts = |source: &str| {
+ let StyleValueData::Unresolved(payload) = unresolved(source) else {
+ unreachable!();
+ };
+ (
+ payload.facts().is_lone_css_wide_keyword(),
+ payload.facts().calls_tree_counting_function(),
+ )
+ };
+ assert_eq!(facts(" inherit "), (true, false));
+ assert_eq!(facts("inherit green"), (false, false));
+ assert_eq!(facts("calc(sibling-index() * 1px)"), (false, true));
+ }
+
+ #[test]
+ fn a_value_made_of_its_serialization_tokenizes_back_to_its_components() {
+ use crate::css::parser::component_value::ComponentSerializationMode;
+ // NB: Two numbers with nothing between them, as a substitution leaves `var(--n)0`, which their
+ // serialization keeps apart with a comment.
+ let values: Vec<ComponentValue> = components("12 1.0")
+ .into_iter()
+ .filter(|value| !value.is_whitespace())
+ .collect();
+ let source =
+ crate::css::serialize::serialize_component_values_to_utf16(&values, ComponentSerializationMode::Retokenize);
+ assert_eq!(String::from_utf16_lossy(&source), "12/**/1.0");
+ let made_of = |components| {
+ UnresolvedBox::new(
+ TokenizerInput::Utf16(&source),
+ components,
+ SubstitutionFunctionsPresence::default(),
+ false,
+ RetainedStyleValueData::none(),
+ )
+ };
+ let serialized = made_of(UnresolvedValueComponents::OfSerialization(&values));
+ assert!(components_equal(&serialized.components(), &values));
+ let written = made_of(UnresolvedValueComponents::OfText(&values));
+ assert_eq!(written.components().len(), 3);
}
}
+/// Whether two lists hold the same components, by their token kinds, wherever their text came from.
+#[cfg(test)]
+pub(crate) fn components_equal(first: &[ComponentValue], second: &[ComponentValue]) -> bool {
+ first.len() == second.len()
+ && first
+ .iter()
+ .zip(second)
+ .all(|(first, second)| match (&first.kind, &second.kind) {
+ (ComponentKind::Token(first), ComponentKind::Token(second)) => first == second,
+ (
+ ComponentKind::Function {
+ name: first_name,
+ values: first,
+ },
+ ComponentKind::Function {
+ name: second_name,
+ values: second,
+ },
+ ) => first_name == second_name && components_equal(first, second),
+ (
+ ComponentKind::SimpleBlock {
+ opening: first_opening,
+ values: first,
+ },
+ ComponentKind::SimpleBlock {
+ opening: second_opening,
+ values: second,
+ },
+ ) => first_opening == second_opening && components_equal(first, second),
+ _ => false,
+ })
+}
+
pub(crate) fn style_value_content_hash(value: Option<&StyleValueData>) -> u64 {
let Some(value) = value else {
return 0;
@@ -397,6 +422,19 @@ pub struct RetainedStyleValueData {
pointer: *const c_void,
}
+impl crate::heap_size::HeapSize for RetainedStyleValueData {
+ /// Counts the value's allocation aside, the first time it is reached, as every owner holding
+ /// it shares it. The values a value holds are not counted.
+ fn heap_size(&self, sizer: &mut crate::heap_size::HeapSizer) -> usize {
+ if sizer.first_sight(self.pointer()) {
+ sizer.style_value_bytes += crate::heap_size::STYLE_VALUE_HEADER_BYTES
+ + size_of::<StyleValueData>()
+ + self.optional_data().map_or(0, StyleValueData::boxed_payload_bytes);
+ }
+ 0
+ }
+}
+
// SAFETY: This handle owns an Arc reference and only exposes shared access to its pointee.
unsafe impl Send for RetainedStyleValueData where StyleValueData: Send + Sync {}
unsafe impl Sync for RetainedStyleValueData where StyleValueData: Send + Sync {}
@@ -411,41 +449,60 @@ impl PartialEq for RetainedStyleValueData {
}
}
-pub(crate) fn shared_style_value(value: StyleValueData) -> Arc<StyleValueData> {
- // Common scalars recur in parsed values, computed styles, and values created through FFI.
- // Direct indexing shares them without hashing every property or retaining arbitrary input.
- const KEYWORDS: usize = 1024;
- const INTEGERS: usize = 384;
- const NUMBERS: usize = 256;
- const LENGTHS: usize = 1024;
- const PERCENTAGES: usize = 101;
- const COUNT: usize = KEYWORDS + INTEGERS + NUMBERS + LENGTHS + PERCENTAGES;
- static VALUES: [std::sync::OnceLock<Arc<StyleValueData>>; COUNT] = [const { std::sync::OnceLock::new() }; COUNT];
+// Common scalars recur in parsed values, computed styles, and values created through FFI.
+// Direct indexing shares them without hashing every property or retaining arbitrary input.
+const SHARED_KEYWORDS: usize = 1024;
+const SHARED_INTEGERS: usize = 384;
+const SHARED_NUMBERS: usize = 256;
+const SHARED_LENGTHS: usize = 1024;
+const SHARED_PERCENTAGES: usize = 101;
+const SHARED_VALUE_COUNT: usize =
+ SHARED_KEYWORDS + SHARED_INTEGERS + SHARED_NUMBERS + SHARED_LENGTHS + SHARED_PERCENTAGES;
+static VALUES: [std::sync::OnceLock<StyleValueArc>; SHARED_VALUE_COUNT] =
+ [const { std::sync::OnceLock::new() }; SHARED_VALUE_COUNT];
+pub(crate) fn shared_style_value(value: StyleValueData) -> StyleValueArc {
let integer_index = |value: f64, count: usize| {
(value >= 0.0 && value < count as f64 && value.to_bits() == (value as u16 as f64).to_bits())
.then_some(value as usize)
};
let index = match &value {
- StyleValueData::Keyword { keyword } if usize::from(*keyword) < KEYWORDS => Some(usize::from(*keyword)),
- StyleValueData::Integer { value } if (-128..256).contains(value) => Some(KEYWORDS + (*value + 128) as usize),
- StyleValueData::Number { value } => integer_index(*value, NUMBERS).map(|index| KEYWORDS + INTEGERS + index),
- StyleValueData::Length { value, unit } if *unit == crate::css::style_compute::px_length_unit() => {
- integer_index(*value, LENGTHS).map(|index| KEYWORDS + INTEGERS + NUMBERS + index)
+ StyleValueData::Keyword { keyword } if usize::from(*keyword) < SHARED_KEYWORDS => Some(usize::from(*keyword)),
+ StyleValueData::Integer { value } if (-128..256).contains(value) => {
+ Some(SHARED_KEYWORDS + (*value + 128) as usize)
+ }
+ StyleValueData::Number { value } => {
+ integer_index(*value, SHARED_NUMBERS).map(|index| SHARED_KEYWORDS + SHARED_INTEGERS + index)
}
- StyleValueData::Percentage { value } => {
- integer_index(*value, PERCENTAGES).map(|index| KEYWORDS + INTEGERS + NUMBERS + LENGTHS + index)
+ StyleValueData::Length { value, unit } if *unit == crate::css::style_compute::px_length_unit() => {
+ integer_index(*value, SHARED_LENGTHS)
+ .map(|index| SHARED_KEYWORDS + SHARED_INTEGERS + SHARED_NUMBERS + index)
}
+ StyleValueData::Percentage { value } => integer_index(*value, SHARED_PERCENTAGES)
+ .map(|index| SHARED_KEYWORDS + SHARED_INTEGERS + SHARED_NUMBERS + SHARED_LENGTHS + index),
_ => None,
};
if let Some(index) = index {
- Arc::clone(VALUES[index].get_or_init(|| Arc::new(value)))
+ StyleValueArc::clone(VALUES[index].get_or_init(|| StyleValueArc::new(value)))
} else {
- Arc::new(value)
+ StyleValueArc::new(value)
}
}
impl RetainedStyleValueData {
+ /// The value of `keyword` the shared values hold, which every value of it shares.
+ pub(crate) fn shared_keyword(keyword: u16) -> &'static Self {
+ assert!(
+ usize::from(keyword) < SHARED_KEYWORDS,
+ "the shared values hold every keyword"
+ );
+ let value =
+ VALUES[usize::from(keyword)].get_or_init(|| StyleValueArc::new(StyleValueData::Keyword { keyword }));
+ // SAFETY: A handle is one pointer at the value, as an arc is, and the shared values keep
+ // theirs for the life of the process.
+ unsafe { &*std::ptr::from_ref(value).cast::<Self>() }
+ }
+
pub(crate) fn none() -> Self {
Self {
pointer: std::ptr::null(),
@@ -456,27 +513,15 @@ impl RetainedStyleValueData {
Self::from_arc(shared_style_value(data))
}
- pub(crate) fn from_arc(value: Arc<StyleValueData>) -> Self {
- // SAFETY: Arc::into_raw transfers one strong reference to this handle.
- unsafe { Self::from_retained_pointer(Arc::into_raw(value)) }
+ pub(crate) fn from_arc(value: StyleValueArc) -> Self {
+ // SAFETY: `into_raw` transfers one reference to this handle.
+ unsafe { Self::from_retained_pointer(StyleValueArc::into_raw(value)) }
}
- pub(crate) fn from_optional_arc(value: Option<Arc<StyleValueData>>) -> Self {
+ pub(crate) fn from_optional_arc(value: Option<StyleValueArc>) -> Self {
value.map_or_else(Self::none, Self::from_arc)
}
- /// Borrow the handles' pointer storage without copying or transferring ownership.
- pub(crate) fn pointer_slice(values: &[Self]) -> &[*const c_void] {
- const {
- assert!(size_of::<RetainedStyleValueData>() == size_of::<*const c_void>());
- assert!(align_of::<RetainedStyleValueData>() == align_of::<*const c_void>());
- }
- // SAFETY: This repr(C) type has exactly one field, a *const c_void, so its
- // size, alignment and layout match that pointer. The shared slice
- // borrows the handles and cannot outlive or modify their storage.
- unsafe { ak::slice_from_raw_parts(values.as_ptr().cast(), values.len()) }
- }
-
pub(crate) fn pointer(&self) -> *const StyleValueData {
self.pointer.cast()
}
@@ -523,12 +568,31 @@ impl RetainedStyleValueData {
pointer
}
+ /// The handles of `values`, borrowed: each is one pointer at the same value.
+ pub(crate) fn slice_from_shared(values: &[StyleValueArc]) -> &[Self] {
+ const _: () = assert!(size_of::<StyleValueArc>() == size_of::<RetainedStyleValueData>());
+ const _: () = assert!(align_of::<StyleValueArc>() == align_of::<RetainedStyleValueData>());
+ // SAFETY: Both are one pointer at the counted value, `StyleValueArc` transparently and the
+ // handle as `repr(C)`, and a borrowed handle neither adds nor drops a reference.
+ unsafe { ak::slice_from_raw_parts(values.as_ptr().cast(), values.len()) }
+ }
+
+ /// Whether this is the only reference to the value, which a handle without one is not.
+ pub(crate) fn is_unique(&self) -> bool {
+ if self.optional_data().is_none() {
+ return false;
+ }
+ // SAFETY: The handle holds a reference to the value, which the borrowed one never drops.
+ let value = std::mem::ManuallyDrop::new(unsafe { StyleValueArc::from_raw(self.pointer()) });
+ StyleValueArc::is_unique(&value)
+ }
+
/// Converts the retained reference into an Arc, transferring the strong reference.
- pub(crate) fn into_arc(self) -> std::sync::Arc<StyleValueData> {
+ pub(crate) fn into_arc(self) -> StyleValueArc {
let pointer = self.pointer();
std::mem::forget(self);
// SAFETY: The retained reference owns exactly one strong reference.
- unsafe { std::sync::Arc::from_raw(pointer) }
+ unsafe { StyleValueArc::from_raw(pointer) }
}
}
@@ -544,26 +608,71 @@ impl Drop for RetainedStyleValueData {
}
}
-/// A retained, Rust-owned array of shared style value data references.
+/// A retained, Rust-owned array of shared style value data references, held by one pointer to its
+/// first element, with the element count in the word before it (null when empty). A list fits in
+/// the value holding it beside a few small fields.
#[repr(C)]
pub struct RetainedStyleValueDataList {
pointer: *mut RetainedStyleValueData,
- length: usize,
}
impl RetainedStyleValueDataList {
+ const HEADER: usize = size_of::<usize>();
+
+ fn layout(length: usize) -> std::alloc::Layout {
+ const _: () = assert!(align_of::<RetainedStyleValueData>() <= size_of::<usize>());
+ let bytes = length
+ .checked_mul(size_of::<RetainedStyleValueData>())
+ .and_then(|bytes| bytes.checked_add(Self::HEADER))
+ .expect("style value list too long");
+ std::alloc::Layout::from_size_align(bytes, align_of::<usize>()).expect("style value list too long")
+ }
+
+ pub(crate) fn len(&self) -> usize {
+ if self.pointer.is_null() {
+ return 0;
+ }
+ // SAFETY: A non-null pointer follows the element count of a live allocation.
+ unsafe { *self.pointer.cast::<usize>().sub(1) }
+ }
+
pub(crate) fn as_slice(&self) -> &[RetainedStyleValueData] {
if self.pointer.is_null() {
return &[];
}
- unsafe { ak::slice_from_raw_parts(self.pointer, self.length) }
+ // SAFETY: A non-null pointer points at `len()` initialized elements.
+ unsafe { ak::slice_from_raw_parts(self.pointer, self.len()) }
+ }
+
+ fn from_iterator(values: impl ExactSizeIterator<Item = RetainedStyleValueData>) -> Self {
+ let length = values.len();
+ if length == 0 {
+ return Self {
+ pointer: std::ptr::null_mut(),
+ };
+ }
+ let layout = Self::layout(length);
+ // SAFETY: The layout has a nonzero size.
+ let base = unsafe { std::alloc::alloc(layout) };
+ if base.is_null() {
+ std::alloc::handle_alloc_error(layout);
+ }
+ // SAFETY: The allocation holds the count, then `length` elements.
+ unsafe {
+ base.cast::<usize>().write(length);
+ let pointer = base.add(Self::HEADER).cast::<RetainedStyleValueData>();
+ let mut written = 0;
+ for value in values.take(length) {
+ pointer.add(written).write(value);
+ written += 1;
+ }
+ assert_eq!(written, length, "style value list iterator ended early");
+ Self { pointer }
+ }
}
pub(crate) fn from_retained_values(values: Vec<RetainedStyleValueData>) -> Self {
- let slice = values.into_boxed_slice();
- let length = slice.len();
- let pointer = Box::into_raw(slice) as *mut RetainedStyleValueData;
- Self { pointer, length }
+ Self::from_iterator(values.into_iter())
}
/// Takes ownership of one strong reference to each value.
@@ -571,12 +680,29 @@ impl RetainedStyleValueDataList {
/// # Safety
/// `values` must point to `length` strong references returned by `rust_style_value_retain`.
unsafe fn from_retained_pointers(values: *const *const StyleValueData, length: usize) -> Self {
- let slice: Box<[RetainedStyleValueData]> = (0..length)
- .map(|i| unsafe { RetainedStyleValueData::from_retained_pointer(*values.add(i)) })
- .collect();
- let length = slice.len();
- let pointer = Box::into_raw(slice) as *mut RetainedStyleValueData;
- Self { pointer, length }
+ Self::from_iterator(
+ (0..length).map(|i| unsafe { RetainedStyleValueData::from_retained_pointer(*values.add(i)) }),
+ )
+ }
+}
+
+impl PartialEq for RetainedStyleValueDataList {
+ fn eq(&self, other: &Self) -> bool {
+ self.as_slice() == other.as_slice()
+ }
+}
+
+impl Drop for RetainedStyleValueDataList {
+ fn drop(&mut self) {
+ if self.pointer.is_null() {
+ return;
+ }
+ let length = self.len();
+ // SAFETY: The list owns its `length` elements and the allocation they are in.
+ unsafe {
+ std::ptr::drop_in_place(std::ptr::slice_from_raw_parts_mut(self.pointer, length));
+ std::alloc::dealloc(self.pointer.cast::<u8>().sub(Self::HEADER), Self::layout(length));
+ }
}
}
@@ -619,7 +745,7 @@ impl Clone for RetainedStyleValueDataList {
if let Some((_, cloned)) = cloned_by_pointer.iter().find(|(original, _)| *original == pointer) {
return unsafe { RetainedStyleValueData::from_retained_pointer(retain_style_value(*cloned)) };
}
- let cloned = Arc::into_raw(Arc::new(data.clone()));
+ let cloned = StyleValueArc::into_raw(StyleValueArc::new(data.clone()));
cloned_by_pointer.push((pointer, cloned));
unsafe { RetainedStyleValueData::from_retained_pointer(cloned) }
})
@@ -643,8 +769,6 @@ macro_rules! retained_list_drop {
}
pub(crate) use retained_list_drop;
-retained_list_drop!(RetainedStyleValueDataList);
-
/// Implements the shared behavior for a `Retained*List` struct whose `from_raw` input is an
/// array of its own element type: `from_raw` copies `length` elements into a Rust-owned boxed
/// slice, assuming ownership of the elements' retained references, and `Drop` releases them.
@@ -716,36 +840,90 @@ impl RetainedPropertyIdList {
/// Shared native URL text, independent of host strings and the atom table.
#[repr(C)]
pub struct RetainedString {
+ /// Null for the empty string, which most images' unset base URL is.
storage: *const c_void,
}
-// SAFETY: This handle owns an Arc to immutable ASCII or UTF-16 storage.
+// SAFETY: This handle owns a reference to immutable ASCII or UTF-16 text, counted atomically.
unsafe impl Send for RetainedString {}
unsafe impl Sync for RetainedString {}
+/// The header of a retained string's one allocation, which its text follows: ASCII bytes or UTF-16
+/// code units.
+#[repr(C)]
+struct RetainedStringHeader {
+ references: std::sync::atomic::AtomicUsize,
+ length: u32,
+ is_latin1: bool,
+}
+
impl RetainedString {
- fn from_storage(storage: crate::css::css_tokenizer::SourceStorage) -> Self {
- Self {
- storage: Arc::into_raw(Arc::new(storage)).cast(),
+ fn layout(length: usize, is_latin1: bool) -> std::alloc::Layout {
+ let unit = if is_latin1 { 1 } else { size_of::<u16>() };
+ let bytes = length
+ .checked_mul(unit)
+ .and_then(|bytes| bytes.checked_add(size_of::<RetainedStringHeader>()))
+ .expect("retained string too long");
+ std::alloc::Layout::from_size_align(bytes, align_of::<RetainedStringHeader>())
+ .expect("retained string too long")
+ }
+
+ /// A string of `length` units, Latin-1 bytes or UTF-16 code units as `is_latin1` says, which
+ /// `write` fills.
+ fn with_units(length: usize, is_latin1: bool, write: impl FnOnce(*mut u8)) -> Self {
+ if length == 0 {
+ return Self {
+ storage: std::ptr::null(),
+ };
+ }
+ let layout = Self::layout(length, is_latin1);
+ // SAFETY: The layout is nonzero; the header is written, then `write` fills the text.
+ unsafe {
+ let base = std::alloc::alloc(layout);
+ if base.is_null() {
+ std::alloc::handle_alloc_error(layout);
+ }
+ base.cast::<RetainedStringHeader>().write(RetainedStringHeader {
+ references: std::sync::atomic::AtomicUsize::new(1),
+ length: u32::try_from(length).expect("retained string too long"),
+ is_latin1,
+ });
+ write(base.add(size_of::<RetainedStringHeader>()));
+ Self { storage: base.cast() }
}
}
+ fn header(&self) -> Option<&RetainedStringHeader> {
+ // SAFETY: A non-null storage is a live allocation starting with its header.
+ (!self.storage.is_null()).then(|| unsafe { &*self.storage.cast::<RetainedStringHeader>() })
+ }
+
+ /// Any text, which need not be well-formed UTF-16.
+ pub(crate) fn from_text(units: TokenizerInput<'_>) -> Self {
+ Self::from_units(units)
+ }
+
fn from_units(units: TokenizerInput<'_>) -> Self {
- use crate::css::css_tokenizer::SourceStorage;
- Self::from_storage(match units {
- TokenizerInput::Latin1(bytes) => SourceStorage::Latin1(bytes.into()),
+ match units {
+ TokenizerInput::Latin1(bytes) => Self::with_units(bytes.len(), true, |text| unsafe {
+ std::ptr::copy_nonoverlapping(bytes.as_ptr(), text, bytes.len());
+ }),
TokenizerInput::Utf16(units) if units.iter().all(|unit| *unit <= 0x7f) => {
- SourceStorage::Latin1(units.iter().map(|unit| *unit as u8).collect())
+ Self::with_units(units.len(), true, |text| {
+ for (index, unit) in units.iter().enumerate() {
+ unsafe { text.add(index).write(*unit as u8) };
+ }
+ })
}
- TokenizerInput::Utf16(units) => SourceStorage::Utf16(units.into()),
- })
+ TokenizerInput::Utf16(units) => Self::with_units(units.len(), false, |text| unsafe {
+ std::ptr::copy_nonoverlapping(units.as_ptr(), text.cast::<u16>(), units.len());
+ }),
+ }
}
pub(crate) fn from_ascii(string: String) -> Self {
assert!(string.is_ascii());
- Self::from_storage(crate::css::css_tokenizer::SourceStorage::Latin1(
- string.into_bytes().into_boxed_slice(),
- ))
+ Self::from_units(TokenizerInput::Latin1(string.as_bytes()))
}
pub(crate) fn from_utf16(string: &[u16]) -> Option<Self> {
@@ -755,11 +933,28 @@ impl RetainedString {
Some(Self::from_units(TokenizerInput::Utf16(string)))
}
+ /// The text as UTF-16 code units.
+ #[cfg(test)]
+ pub(crate) fn to_utf16(&self) -> Vec<u16> {
+ let units = self.units();
+ let mut text = Vec::with_capacity(units.len());
+ units.append_to(&mut text);
+ text
+ }
+
pub(crate) fn units(&self) -> TokenizerInput<'_> {
- use crate::css::css_tokenizer::SourceStorage;
- match unsafe { &*self.storage.cast::<SourceStorage>() } {
- SourceStorage::Latin1(bytes) => TokenizerInput::Latin1(bytes),
- SourceStorage::Utf16(units) => TokenizerInput::Utf16(units),
+ let Some(header) = self.header() else {
+ return TokenizerInput::Latin1(&[]);
+ };
+ let length = header.length as usize;
+ // SAFETY: The text follows the header, `length` units of the kind the header names.
+ unsafe {
+ let text = self.storage.cast::<u8>().add(size_of::<RetainedStringHeader>());
+ if header.is_latin1 {
+ TokenizerInput::Latin1(ak::slice_from_raw_parts(text, length))
+ } else {
+ TokenizerInput::Utf16(ak::slice_from_raw_parts(text.cast::<u16>(), length))
+ }
}
}
@@ -810,14 +1005,25 @@ impl PartialEq for RetainedString {
impl Clone for RetainedString {
fn clone(&self) -> Self {
- unsafe { Arc::increment_strong_count(self.storage.cast::<crate::css::css_tokenizer::SourceStorage>()) };
+ if let Some(header) = self.header() {
+ header.references.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ }
Self { storage: self.storage }
}
}
impl Drop for RetainedString {
fn drop(&mut self) {
- unsafe { Arc::decrement_strong_count(self.storage.cast::<crate::css::css_tokenizer::SourceStorage>()) };
+ let Some(header) = self.header() else {
+ return;
+ };
+ if header.references.fetch_sub(1, std::sync::atomic::Ordering::Release) != 1 {
+ return;
+ }
+ std::sync::atomic::fence(std::sync::atomic::Ordering::Acquire);
+ let layout = Self::layout(header.length as usize, header.is_latin1);
+ // SAFETY: The last reference frees the allocation it was made in.
+ unsafe { std::alloc::dealloc(self.storage.cast_mut().cast::<u8>(), layout) };
}
}
@@ -1627,7 +1833,6 @@ retained_list_send_sync!(RetainedGridTrackEntryList, RetainedGridTrackEntry);
retained_list_send_sync!(RetainedShapePointList, RetainedShapePoint);
retained_list_send_sync!(RetainedNumericRangeList, RetainedNumericRangeByType);
-retained_list_partial_eq!(RetainedStyleValueDataList, RetainedStyleValueData);
retained_list_partial_eq!(RetainedPropertyIdList, u16);
retained_list_partial_eq!(RetainedRequestUrlModifierList, RetainedRequestUrlModifier);
retained_list_partial_eq!(RetainedByteList, u8);
@@ -1777,6 +1982,67 @@ impl PartialEq for ShapeCommands {
}
}
+/// The box a [`StyleValueData`] variant too large to sit beside the tag keeps its payload in, laid
+/// out as one pointer C++ reads the payload through.
+#[repr(C)]
+pub struct StyleValueBox<T> {
+ pointer: std::ptr::NonNull<T>,
+}
+
+// SAFETY: The box owns its payload as a `Box` would.
+unsafe impl<T: Send> Send for StyleValueBox<T> {}
+unsafe impl<T: Sync> Sync for StyleValueBox<T> {}
+
+impl<T> StyleValueBox<T> {
+ pub(crate) fn new(payload: T) -> Self {
+ Self {
+ pointer: std::ptr::NonNull::from(Box::leak(Box::new(payload))),
+ }
+ }
+
+ pub(crate) fn into_inner(self) -> T {
+ let pointer = self.pointer.as_ptr();
+ std::mem::forget(self);
+ // SAFETY: The box owned the payload it leaked in `new`, and is forgotten.
+ *unsafe { Box::from_raw(pointer) }
+ }
+}
+
+impl<T> std::ops::Deref for StyleValueBox<T> {
+ type Target = T;
+
+ fn deref(&self) -> &T {
+ // SAFETY: The box owns a live payload.
+ unsafe { self.pointer.as_ref() }
+ }
+}
+
+impl<T> std::ops::DerefMut for StyleValueBox<T> {
+ fn deref_mut(&mut self) -> &mut T {
+ // SAFETY: The box owns a live payload, and `&mut self` borrows it exclusively.
+ unsafe { self.pointer.as_mut() }
+ }
+}
+
+impl<T: Clone> Clone for StyleValueBox<T> {
+ fn clone(&self) -> Self {
+ Self::new((**self).clone())
+ }
+}
+
+impl<T: PartialEq> PartialEq for StyleValueBox<T> {
+ fn eq(&self, other: &Self) -> bool {
+ **self == **other
+ }
+}
+
+impl<T> Drop for StyleValueBox<T> {
+ fn drop(&mut self) {
+ // SAFETY: The box owns the payload it leaked in `new`.
+ drop(unsafe { Box::from_raw(self.pointer.as_ptr()) });
+ }
+}
+
/// A Rust-owned shape allocation with an explicit pointer layout for C++ bindings.
#[repr(C)]
pub struct OwnedBasicShapeData {
@@ -1839,43 +2105,28 @@ pub enum StyleValueData {
/// A CSS `<integer>`.
Integer { value: i32 },
/// A CSS `<angle>`. The unit is the C++ `enum class AngleUnit : u8`, opaque to Rust.
- Angle { value: f64, unit: u8 },
+ Angle { unit: u8, value: f64 },
/// A CSS `<flex>`. The unit is the C++ `enum class FlexUnit : u8`, opaque to Rust.
- Flex { value: f64, unit: u8 },
+ Flex { unit: u8, value: f64 },
/// A CSS `<frequency>`. The unit is the C++ `enum class FrequencyUnit : u8`, opaque to Rust.
- Frequency { value: f64, unit: u8 },
+ Frequency { unit: u8, value: f64 },
/// A CSS `<length>`. The unit is the C++ `enum class LengthUnit : u8`, opaque to Rust.
- Length { value: f64, unit: u8 },
+ Length { unit: u8, value: f64 },
/// A CSS `<percentage>`.
Percentage { value: f64 },
/// A CSS `<resolution>`. The unit is the C++ `enum class ResolutionUnit : u8`, opaque to Rust.
- Resolution { value: f64, unit: u8 },
+ Resolution { unit: u8, value: f64 },
/// A CSS `<time>`. The unit is the C++ `enum class TimeUnit : u8`, opaque to Rust.
- Time { value: f64, unit: u8 },
+ Time { unit: u8, value: f64 },
/// A basic shape. Kinds: inset (0), xywh (1) and rect (2) use five retained value slots;
/// circle (3) and ellipse (4) use two; polygon (5) uses the fill rule and points; path (6)
/// uses the fill rule and the retained serialized path data string.
BasicShape { shape: OwnedBasicShapeData },
/// A calc() or other math function: the retained calculation node tree root, its resolved
/// numeric type, and the parse-time calculation context.
- Calculated {
- /// The resolve-against target, base-mapped at creation: whether one
- /// exists, whether it is the number type, and otherwise its base type
- /// index in the numeric type order.
- resolve_as_is_number: bool,
- resolve_as_base: u8,
- has_percentages_resolve_as: bool,
- percentages_resolve_as: u8,
- resolve_numbers_as_integers: bool,
- rust_calculation: crate::css::calc::CalcNodeHandle,
- resolved_type: crate::css::calc::FfiNumericType,
- accepted_ranges: RetainedNumericRangeList,
- },
+ Calculated(StyleValueBox<CalculatedPayload>),
/// A CSS `<ratio>`, e.g. `16 / 9`. The numerator and denominator are style values.
- Ratio {
- numerator: RetainedStyleValueData,
- denominator: RetainedStyleValueData,
- },
+ Ratio(StyleValueBox<RatioPayload>),
/// A unicode-range, e.g. `U+0025-00FF`.
UnicodeRange { min_code_point: u32, max_code_point: u32 },
/// A CSS `<opacity-value>`: a number, percentage or calculated style value.
@@ -1902,42 +2153,28 @@ pub enum StyleValueData {
},
/// superellipse() with its retained parameter style value.
Superellipse { parameter: RetainedStyleValueData },
- /// A pending-substitution value retaining the shorthand value it came from.
+ /// A pending-substitution value retaining the shorthand it is part of and the value that
+ /// shorthand was written with.
PendingSubstitution {
+ original_shorthand: u16,
original_shorthand_value: RetainedStyleValueData,
},
/// scrollbar-color with retained thumb and track color values.
- ScrollbarColor {
- thumb_color: RetainedStyleValueData,
- track_color: RetainedStyleValueData,
- },
+ ScrollbarColor(StyleValueBox<ScrollbarColorPayload>),
/// rect() with four retained edge style values.
- Rect {
- top: RetainedStyleValueData,
- right: RetainedStyleValueData,
- bottom: RetainedStyleValueData,
- left: RetainedStyleValueData,
- },
+ Rect(StyleValueBox<RectPayload>),
/// A CSS `<string>`, with its animation-name custom-ident classification captured when C++
/// creates the immutable value so computation does not read the string across FFI.
String {
- string: CssString,
is_valid_animation_name_custom_ident: bool,
serialize_without_quotes: bool,
+ string: CssString,
},
/// An unrecognized CSS function, kept as its name and argument value.
- Function {
- name: CssString,
- value: RetainedStyleValueData,
- },
+ Function(StyleValueBox<FunctionPayload>),
/// An OpenType tag with its value, from font-feature-settings or font-variation-settings.
/// The mode is the C++ OpenTypeTaggedStyleValue::Mode, opaque to Rust.
- OpenTypeTagged {
- mode: u8,
- tag_name: CssString,
- packed_tag: u32,
- value: RetainedStyleValueData,
- },
+ OpenTypeTagged(StyleValueBox<OpenTypeTaggedPayload>),
/// font-style: a keyword (the C++ `enum class FontStyleKeyword : u8`, opaque to Rust) and
/// an optional oblique angle style value (null when absent).
FontStyle {
@@ -1946,9 +2183,9 @@ pub enum StyleValueData {
},
/// text-indent: a length-percentage style value plus the hanging and each-line flags.
TextIndent {
- length_percentage: RetainedStyleValueData,
hanging: bool,
each_line: bool,
+ length_percentage: RetainedStyleValueData,
},
/// overflow-clip-margin: an optional visual box (the C++ `enum class BackgroundBox : u8`,
/// opaque to Rust) and an offset style value.
@@ -1961,217 +2198,84 @@ pub enum StyleValueData {
/// opaque to Rust.
TreeCountingFunction { function: u8, computed_type: u8 },
/// background-size with its two retained size style values.
- BackgroundSize {
- size_x: RetainedStyleValueData,
- size_y: RetainedStyleValueData,
- },
+ BackgroundSize(StyleValueBox<BackgroundSizePayload>),
/// A background repeat-style. Both fields are the C++ `enum class Repetition : u8`, opaque
/// to Rust.
RepeatStyle { repeat_x: u8, repeat_y: u8 },
/// border-image-slice: four retained offset data allocations and the fill keyword.
- BorderImageSlice {
- top: RetainedStyleValueData,
- right: RetainedStyleValueData,
- bottom: RetainedStyleValueData,
- left: RetainedStyleValueData,
- fill: bool,
- },
+ BorderImageSlice(StyleValueBox<BorderImageSlicePayload>),
/// anchor-size(): an optional anchor name, an optional size keyword (the C++ `enum class
/// AnchorSize : u8`, opaque to Rust) and an optional retained fallback value.
- AnchorSize {
- has_anchor_name: bool,
- anchor_name: CssString,
- has_anchor_size: bool,
- anchor_size: u8,
- fallback_value: RetainedStyleValueData,
- },
+ AnchorSize(StyleValueBox<AnchorSizePayload>),
/// anchor(): an optional anchor name, the retained side style value and an optional
/// retained fallback value.
- Anchor {
- has_anchor_name: bool,
- anchor_name: CssString,
- anchor_side: RetainedStyleValueData,
- fallback_value: RetainedStyleValueData,
- },
+ Anchor(StyleValueBox<AnchorPayload>),
/// A CSS `<position>` with its two retained edge style values.
- Position {
- edge_x: RetainedStyleValueData,
- edge_y: RetainedStyleValueData,
- },
+ Position(StyleValueBox<PositionPayload>),
/// A shadow. The type and placement are C++ enums, opaque to Rust; the color, blur radius
/// and spread distance are optional retained style values (null when absent).
- Shadow {
- shadow_type: u8,
- color: RetainedStyleValueData,
- offset_x: RetainedStyleValueData,
- offset_y: RetainedStyleValueData,
- blur_radius: RetainedStyleValueData,
- spread_distance: RetainedStyleValueData,
- placement: u8,
- },
+ Shadow(StyleValueBox<ShadowPayload>),
/// content with its retained content list and optional alt-text list (null when absent).
- Content {
- content: RetainedStyleValueData,
- alt_text: RetainedStyleValueData,
- },
+ Content(StyleValueBox<ContentPayload>),
/// A @counter-style system descriptor: a plain system keyword (kind 0, the C++ `enum class
/// CounterStyleSystem : u8`, opaque to Rust), fixed with an optional retained first symbol
/// (kind 1), or extends with a retained counter style name (kind 2).
- CounterStyleSystem {
- kind: u8,
- system: u8,
- first_symbol: RetainedStyleValueData,
- name: CssString,
- },
+ CounterStyleSystem(StyleValueBox<CounterStyleSystemPayload>),
/// A counter style reference: either a retained counter style name, or a symbols() function
/// with its type (a `css_enums::symbols_type` value) and retained symbol strings.
- CounterStyle {
- is_symbols: bool,
- name: CssString,
- symbols_type: u8,
- symbols: CssStringList,
- },
+ CounterStyle(StyleValueBox<CounterStylePayload>),
/// A color function such as rgb() or oklch(): three retained channel values, an optional
/// retained alpha, an optional name and an optional retained origin color for relative
/// color syntax.
- ColorFunction {
- color_base: ColorBase,
- channel_0: RetainedStyleValueData,
- channel_1: RetainedStyleValueData,
- channel_2: RetainedStyleValueData,
- alpha: RetainedStyleValueData,
- has_name: bool,
- name: CssString,
- origin_color: RetainedStyleValueData,
- },
+ ColorFunction(StyleValueBox<ColorFunctionPayload>),
/// color-mix() with its optional retained interpolation method value and its mix items:
/// one or more retained colors, each with an optional retained percentage. The two lists
/// have the same length, and an omitted percentage is a null entry.
- ColorMix {
- color_base: ColorBase,
- color_interpolation_method: RetainedStyleValueData,
- colors: RetainedStyleValueDataList,
- percentages: RetainedStyleValueDataList,
- },
+ ColorMix(StyleValueBox<ColorMixPayload>),
/// The shared data of every color style value: an optional color type and the color syntax
/// (both C++ enums on ColorStyleValue, opaque to Rust).
/// linear-gradient(): a direction (either a retained angle value or a side-or-corner
/// keyword), the retained color stops, the gradient type, the repeating flag, an optional
/// retained interpolation method and the color syntax. Enums are C++ types, opaque to Rust.
- LinearGradient {
- has_direction_value: bool,
- direction_value: RetainedStyleValueData,
- side_or_corner: u8,
- color_stop_list: RetainedColorStopList,
- gradient_type: u8,
- repeating: bool,
- color_interpolation_method: RetainedStyleValueData,
- color_syntax: u8,
- },
+ LinearGradient(StyleValueBox<LinearGradientPayload>),
/// conic-gradient(): an optional retained from-angle, the retained position, the retained
/// color stops, the repeating flag, an optional retained interpolation method and the color
/// syntax (a C++ enum, opaque to Rust).
- ConicGradient {
- from_angle: RetainedStyleValueData,
- position: RetainedStyleValueData,
- color_stop_list: RetainedColorStopList,
- repeating: bool,
- color_interpolation_method: RetainedStyleValueData,
- color_syntax: u8,
- },
+ ConicGradient(StyleValueBox<ConicGradientPayload>),
/// radial-gradient(): the ending shape (a C++ enum, opaque to Rust), the retained size and
/// position values, the retained color stops, the repeating flag, an optional retained
/// interpolation method and the color syntax.
- RadialGradient {
- ending_shape: u8,
- size: RetainedStyleValueData,
- position: RetainedStyleValueData,
- color_stop_list: RetainedColorStopList,
- repeating: bool,
- color_interpolation_method: RetainedStyleValueData,
- color_syntax: u8,
- },
+ RadialGradient(StyleValueBox<RadialGradientPayload>),
/// A url() image. The resource context is snapshotted into computed images so a later C++
/// wrapper can remain a lazy consumer adapter. Loading state stays on the C++ side.
- Image {
- url: RetainedString,
- url_type: u8,
- url_modifiers: RetainedRequestUrlModifierList,
- resource_context: ImageResourceContext,
- },
+ Image(StyleValueBox<ImagePayload>),
/// image-set() with its retained options.
- ImageSet { options: RetainedImageSetOptionList },
+ ImageSet(StyleValueBox<ImageSetPayload>),
/// An easing function: linear() with its retained stops (kind 0), cubic-bezier() with four
/// retained control values (kind 1), or steps() with a retained interval count and a step
/// position (kind 2, the C++ `enum class StepPosition : u8`, opaque to Rust).
- Easing {
- kind: u8,
- step_position: u8,
- is_keyword: bool,
- linear_stops: RetainedLinearEasingStopList,
- x1: RetainedStyleValueData,
- y1: RetainedStyleValueData,
- x2: RetainedStyleValueData,
- y2: RetainedStyleValueData,
- number_of_intervals: RetainedStyleValueData,
- },
+ Easing(StyleValueBox<EasingPayload>),
/// A cursor with its retained image value and optional retained hotspot coordinates (both
/// null or both non-null).
- Cursor {
- image: RetainedStyleValueData,
- x: RetainedStyleValueData,
- y: RetainedStyleValueData,
- },
+ Cursor(StyleValueBox<CursorPayload>),
/// A grid track size list: the subgrid and preserve-line-name-sets flags and the retained
/// track entries.
- GridTrackSizeList {
- is_subgrid: bool,
- preserve_line_name_sets: bool,
- entries: RetainedGridTrackEntryList,
- },
+ GridTrackSizeList(StyleValueBox<GridTrackSizeListPayload>),
/// grid-template-areas with its retained named areas and the row and column counts.
- GridTemplateArea {
- grid_areas: RetainedGridAreaList,
- row_count: usize,
- column_count: usize,
- },
+ GridTemplateArea(StyleValueBox<GridTemplateAreaPayload>),
/// counter-increment, counter-reset or counter-set with its retained counter definitions.
- CounterDefinitions {
- counter_definitions: RetainedCounterDefinitionList,
- },
+ CounterDefinitions(StyleValueBox<CounterDefinitionsPayload>),
/// A grid-row/grid-column placement: auto (0), a span (1) or an area/line (2), with an
/// optional retained line value and an optional retained name.
- GridTrackPlacement {
- kind: u8,
- value: RetainedStyleValueData,
- has_name: bool,
- name: CssString,
- implicit_start_name: CssString,
- implicit_end_name: CssString,
- },
+ GridTrackPlacement(StyleValueBox<GridTrackPlacementPayload>),
/// counter() or counters(). The function is `COUNTER_FUNCTION_COUNTER` or
/// `COUNTER_FUNCTION_COUNTERS`; the join string is empty for counter().
- Counter {
- function: u8,
- counter_name: CssString,
- counter_style: RetainedStyleValueData,
- join_string: CssString,
- },
+ Counter(StyleValueBox<CounterPayload>),
/// light-dark() with its two retained color style values.
- LightDark {
- color_base: ColorBase,
- light: RetainedStyleValueData,
- dark: RetainedStyleValueData,
- },
+ LightDark(StyleValueBox<LightDarkPayload>),
/// random-value-sharing: an optional retained fixed value (null when absent), the auto flag,
/// an optional name and the element-shared flag.
- RandomValueSharing {
- fixed_value: RetainedStyleValueData,
- is_auto: bool,
- has_name: bool,
- name: CssString,
- element_shared: bool,
- },
+ RandomValueSharing(StyleValueBox<RandomValueSharingPayload>),
/// scrollbar-gutter. The value is the C++ `enum class ScrollbarGutter : u8`, opaque to Rust.
ScrollbarGutter { value: u8 },
/// A color interpolation method: either a rectangular color space, or a polar color space
@@ -2185,9 +2289,9 @@ pub enum StyleValueData {
/// A list of style values. The separator and collapsible flag come from the C++
/// StyleValueList enums, opaque to Rust.
ValueList {
- values: RetainedStyleValueDataList,
separator: u8,
collapsible: bool,
+ values: RetainedStyleValueDataList,
},
/// A tuple of optional style values (null entries represent absent optionals).
Tuple { values: RetainedStyleValueDataList },
@@ -2195,88 +2299,32 @@ pub enum StyleValueData {
/// packed u8 enums), opaque to Rust.
Display { raw: u32 },
/// color-scheme with its retained scheme names and the only keyword flag.
- ColorScheme {
- schemes: CssStringList,
- scheme_codes: RetainedByteList,
- only: bool,
- },
+ ColorScheme(StyleValueBox<ColorSchemePayload>),
/// An unresolved value with retained source text and components, flags for substitution functions,
/// attr taint, and an optional parsed value cached for an attr()-tainted registered custom property.
- Unresolved {
- components: RetainedComponentValueList,
- source_text: CssString,
- presence_attr: bool,
- presence_dashed_function: bool,
- presence_env: bool,
- presence_if: bool,
- presence_inherit: bool,
- presence_var: bool,
- contains_attr_tainted_values: bool,
- parsed_value: RetainedStyleValueData,
- },
+ Unresolved(UnresolvedBox),
/// A CSS url() or src() with its retained URL string, type (the C++ URL::Type, opaque to
/// Rust) and request URL modifiers.
- Url {
- url: RetainedString,
- url_type: u8,
- modifiers: RetainedRequestUrlModifierList,
- },
+ Url(StyleValueBox<UrlPayload>),
/// A @font-face source: either local() with a retained family name value, or a URL (encoded
/// as in [`StyleValueData::Url`]) with an optional format string and a list of font
/// technologies (C++ `enum class FontTech : u8`, opaque to Rust).
- FontSource {
- is_local: bool,
- url_type: u8,
- has_format: bool,
- local_name: RetainedStyleValueData,
- url: RetainedString,
- url_modifiers: RetainedRequestUrlModifierList,
- format: CssString,
- tech: RetainedByteList,
- },
+ FontSource(StyleValueBox<FontSourcePayload>),
/// A radial gradient size: one or two components, each either a RadialExtent keyword (the
/// C++ `enum class RadialExtent : u8`, opaque to Rust) or a retained style value.
- RadialSize {
- component_count: u8,
- is_extent_0: bool,
- extent_0: u8,
- value_0: RetainedStyleValueData,
- is_extent_1: bool,
- extent_1: u8,
- value_1: RetainedStyleValueData,
- },
+ RadialSize(StyleValueBox<RadialSizePayload>),
/// A transform function with its argument values. The property (PropertyID : u16) and
/// function are C++ enums, opaque to Rust.
- Transformation {
- property: u16,
- transform_function: u8,
- values: RetainedStyleValueDataList,
- /// Matrix-only arguments preserving literal angle precision across canonicalization.
- /// Empty when the canonical arguments lower to the same matrix inputs.
- matrix_values: RetainedStyleValueDataList,
- },
+ Transformation(StyleValueBox<TransformationPayload>),
/// A shorthand property value: the shorthand id, its longhand ids (both C++
/// `enum class PropertyID : u16`, opaque to Rust) and their values.
- Shorthand {
- shorthand_property: u16,
- sub_properties: RetainedPropertyIdList,
- values: RetainedStyleValueDataList,
- },
+ Shorthand(StyleValueBox<ShorthandPayload>),
/// A CSS `<custom-ident>`.
CustomIdent { custom_ident: CssString },
/// A border-radius rect of four retained corner radius data allocations.
- BorderRadiusRect {
- top_left: RetainedStyleValueData,
- top_right: RetainedStyleValueData,
- bottom_right: RetainedStyleValueData,
- bottom_left: RetainedStyleValueData,
- },
+ BorderRadiusRect(StyleValueBox<BorderRadiusRectPayload>),
/// A single corner radius: the horizontal and vertical radii and whether they differ.
- BorderRadius {
- is_elliptical: bool,
- horizontal_radius: RetainedStyleValueData,
- vertical_radius: RetainedStyleValueData,
- },
+ BorderRadius(StyleValueBox<BorderRadiusPayload>),
/// A filter function. Kinds: blur (0, value = radius), drop-shadow (1, value = shadow),
/// hue-rotate (2, value = angle), color (3, value = amount, with the color operation).
/// The kind and the color operation are C++ enum values, opaque to Rust.
@@ -2288,26 +2336,985 @@ pub enum StyleValueData {
/// https://drafts.csswg.org/motion-1/#ray-function
/// A ray() offset path: its angle, its <ray-size> keyword, whether it has `contain`, and its
/// optional `at <position>` (null when absent).
- Ray {
- size: u16,
- contain: bool,
- angle: RetainedStyleValueData,
- position: RetainedStyleValueData,
- },
+ Ray(StyleValueBox<RayPayload>),
}
-// The kinds of a filter style value, which are C++ enum values.
-pub(crate) const FILTER_KIND_BLUR: u8 = 0;
-pub(crate) const FILTER_KIND_DROP_SHADOW: u8 = 1;
+/// What a [`StyleValueData::Calculated`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct CalculatedPayload {
+ /// The resolve-against target, base-mapped at creation: whether one
+ /// exists, whether it is the number type, and otherwise its base type
+ /// index in the numeric type order.
+ pub resolve_as_is_number: bool,
+ pub resolve_as_base: u8,
+ pub has_percentages_resolve_as: bool,
+ pub percentages_resolve_as: u8,
+ pub resolve_numbers_as_integers: bool,
+ pub rust_calculation: crate::css::calc::CalcNodeHandle,
+ pub resolved_type: crate::css::calc::FfiNumericType,
+ pub accepted_ranges: RetainedNumericRangeList,
+}
+
+/// What a [`StyleValueData::Ratio`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct RatioPayload {
+ pub numerator: RetainedStyleValueData,
+ pub denominator: RetainedStyleValueData,
+}
+
+/// What a [`StyleValueData::ScrollbarColor`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct ScrollbarColorPayload {
+ pub thumb_color: RetainedStyleValueData,
+ pub track_color: RetainedStyleValueData,
+}
+
+/// What a [`StyleValueData::Rect`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct RectPayload {
+ pub top: RetainedStyleValueData,
+ pub right: RetainedStyleValueData,
+ pub bottom: RetainedStyleValueData,
+ pub left: RetainedStyleValueData,
+}
+
+/// What a [`StyleValueData::Function`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct FunctionPayload {
+ pub name: CssString,
+ pub value: RetainedStyleValueData,
+}
+
+/// What a [`StyleValueData::OpenTypeTagged`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct OpenTypeTaggedPayload {
+ pub mode: u8,
+ pub tag_name: CssString,
+ pub packed_tag: u32,
+ pub value: RetainedStyleValueData,
+}
+
+/// What a [`StyleValueData::BackgroundSize`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct BackgroundSizePayload {
+ pub size_x: RetainedStyleValueData,
+ pub size_y: RetainedStyleValueData,
+}
+
+/// What a [`StyleValueData::BorderImageSlice`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct BorderImageSlicePayload {
+ pub top: RetainedStyleValueData,
+ pub right: RetainedStyleValueData,
+ pub bottom: RetainedStyleValueData,
+ pub left: RetainedStyleValueData,
+ pub fill: bool,
+}
+
+/// What a [`StyleValueData::AnchorSize`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct AnchorSizePayload {
+ pub has_anchor_name: bool,
+ pub anchor_name: CssString,
+ pub has_anchor_size: bool,
+ pub anchor_size: u8,
+ pub fallback_value: RetainedStyleValueData,
+}
+
+/// What a [`StyleValueData::Anchor`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct AnchorPayload {
+ pub has_anchor_name: bool,
+ pub anchor_name: CssString,
+ pub anchor_side: RetainedStyleValueData,
+ pub fallback_value: RetainedStyleValueData,
+}
+
+/// What a [`StyleValueData::Position`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct PositionPayload {
+ pub edge_x: RetainedStyleValueData,
+ pub edge_y: RetainedStyleValueData,
+}
+
+/// What a [`StyleValueData::Shadow`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct ShadowPayload {
+ pub shadow_type: u8,
+ pub color: RetainedStyleValueData,
+ pub offset_x: RetainedStyleValueData,
+ pub offset_y: RetainedStyleValueData,
+ pub blur_radius: RetainedStyleValueData,
+ pub spread_distance: RetainedStyleValueData,
+ pub placement: u8,
+}
+
+/// What a [`StyleValueData::Content`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct ContentPayload {
+ pub content: RetainedStyleValueData,
+ pub alt_text: RetainedStyleValueData,
+}
+
+/// What a [`StyleValueData::CounterStyleSystem`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct CounterStyleSystemPayload {
+ pub kind: u8,
+ pub system: u8,
+ pub first_symbol: RetainedStyleValueData,
+ pub name: CssString,
+}
+
+/// What a [`StyleValueData::CounterStyle`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct CounterStylePayload {
+ pub is_symbols: bool,
+ pub name: CssString,
+ pub symbols_type: u8,
+ pub symbols: CssStringList,
+}
+
+/// What a [`StyleValueData::ColorFunction`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct ColorFunctionPayload {
+ pub color_base: ColorBase,
+ pub channel_0: RetainedStyleValueData,
+ pub channel_1: RetainedStyleValueData,
+ pub channel_2: RetainedStyleValueData,
+ pub alpha: RetainedStyleValueData,
+ pub has_name: bool,
+ pub name: CssString,
+ pub origin_color: RetainedStyleValueData,
+}
+
+/// What a [`StyleValueData::ColorMix`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct ColorMixPayload {
+ pub color_base: ColorBase,
+ pub color_interpolation_method: RetainedStyleValueData,
+ pub colors: RetainedStyleValueDataList,
+ pub percentages: RetainedStyleValueDataList,
+}
+
+/// What a [`StyleValueData::LinearGradient`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct LinearGradientPayload {
+ pub has_direction_value: bool,
+ pub direction_value: RetainedStyleValueData,
+ pub side_or_corner: u8,
+ pub color_stop_list: RetainedColorStopList,
+ pub gradient_type: u8,
+ pub repeating: bool,
+ pub color_interpolation_method: RetainedStyleValueData,
+ pub color_syntax: u8,
+}
+
+/// What a [`StyleValueData::ConicGradient`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct ConicGradientPayload {
+ pub from_angle: RetainedStyleValueData,
+ pub position: RetainedStyleValueData,
+ pub color_stop_list: RetainedColorStopList,
+ pub repeating: bool,
+ pub color_interpolation_method: RetainedStyleValueData,
+ pub color_syntax: u8,
+}
+
+/// What a [`StyleValueData::RadialGradient`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct RadialGradientPayload {
+ pub ending_shape: u8,
+ pub size: RetainedStyleValueData,
+ pub position: RetainedStyleValueData,
+ pub color_stop_list: RetainedColorStopList,
+ pub repeating: bool,
+ pub color_interpolation_method: RetainedStyleValueData,
+ pub color_syntax: u8,
+}
+
+/// What a [`StyleValueData::Image`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct ImagePayload {
+ pub url: RetainedString,
+ pub url_type: u8,
+ pub url_modifiers: RetainedRequestUrlModifierList,
+ pub resource_context: ImageResourceContext,
+}
+
+/// What a [`StyleValueData::ImageSet`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct ImageSetPayload {
+ pub options: RetainedImageSetOptionList,
+}
+
+/// What a [`StyleValueData::Easing`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct EasingPayload {
+ pub kind: u8,
+ pub step_position: u8,
+ pub is_keyword: bool,
+ pub linear_stops: RetainedLinearEasingStopList,
+ pub x1: RetainedStyleValueData,
+ pub y1: RetainedStyleValueData,
+ pub x2: RetainedStyleValueData,
+ pub y2: RetainedStyleValueData,
+ pub number_of_intervals: RetainedStyleValueData,
+}
+
+/// What a [`StyleValueData::Cursor`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct CursorPayload {
+ pub image: RetainedStyleValueData,
+ pub x: RetainedStyleValueData,
+ pub y: RetainedStyleValueData,
+}
+
+/// What a [`StyleValueData::GridTrackSizeList`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct GridTrackSizeListPayload {
+ pub is_subgrid: bool,
+ pub preserve_line_name_sets: bool,
+ pub entries: RetainedGridTrackEntryList,
+}
+
+/// What a [`StyleValueData::GridTemplateArea`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct GridTemplateAreaPayload {
+ pub grid_areas: RetainedGridAreaList,
+ pub row_count: usize,
+ pub column_count: usize,
+}
+
+/// What a [`StyleValueData::CounterDefinitions`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct CounterDefinitionsPayload {
+ pub counter_definitions: RetainedCounterDefinitionList,
+}
+
+/// What a [`StyleValueData::GridTrackPlacement`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct GridTrackPlacementPayload {
+ pub kind: u8,
+ pub value: RetainedStyleValueData,
+ pub has_name: bool,
+ pub name: CssString,
+ pub implicit_start_name: CssString,
+ pub implicit_end_name: CssString,
+}
+
+/// What a [`StyleValueData::Counter`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct CounterPayload {
+ pub function: u8,
+ pub counter_name: CssString,
+ pub counter_style: RetainedStyleValueData,
+ pub join_string: CssString,
+}
+
+/// What a [`StyleValueData::LightDark`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct LightDarkPayload {
+ pub color_base: ColorBase,
+ pub light: RetainedStyleValueData,
+ pub dark: RetainedStyleValueData,
+}
+
+/// What a [`StyleValueData::RandomValueSharing`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct RandomValueSharingPayload {
+ pub fixed_value: RetainedStyleValueData,
+ pub is_auto: bool,
+ pub has_name: bool,
+ pub name: CssString,
+ pub element_shared: bool,
+}
+
+/// What a [`StyleValueData::ColorScheme`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct ColorSchemePayload {
+ pub schemes: CssStringList,
+ pub scheme_codes: RetainedByteList,
+ pub only: bool,
+}
+
+/// What an unresolved value's text holds, found once when the value is made from the components it
+/// tokenizes to: which substitution functions it uses (bits 0-5, in the order of
+/// `SubstitutionFunctionsPresence`'s fields), whether it is a lone CSS-wide keyword (bit 6), whether
+/// it calls a tree-counting function (bit 7), whether it references a custom property by name (bit
+/// 8), whether a reference names its property by anything but a plain identifier (bit 9), and
+/// whether the engine serialized the text from tokens, so that its comments only keep tokens apart
+/// (bit 10).
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[repr(transparent)]
+pub struct UnresolvedFacts(u16);
+
+const _: () = assert!(size_of::<UnresolvedFacts>() == 2);
+
+impl UnresolvedFacts {
+ const LONE_CSS_WIDE_KEYWORD: u16 = 1 << 6;
+ const CALLS_TREE_COUNTING_FUNCTION: u16 = 1 << 7;
+ const NAMES_CUSTOM_PROPERTIES: u16 = 1 << 8;
+ const HIDES_A_REFERENCE: u16 = 1 << 9;
+ const SERIALIZED_BY_THE_ENGINE: u16 = 1 << 10;
+
+ /// The facts of a value whose text tokenizes to `values` and uses the substitution functions
+ /// `presence` says, beside those of the custom properties it references.
+ pub(crate) fn of(values: &[ComponentValue], presence: SubstitutionFunctionsPresence) -> Self {
+ let presence_bits = [
+ presence.attr,
+ presence.dashed_function,
+ presence.env,
+ presence.if_,
+ presence.inherit,
+ presence.var,
+ ]
+ .iter()
+ .enumerate()
+ .fold(0_u16, |bits, (index, present)| bits | (u16::from(*present) << index));
+ let mut bits = presence_bits;
+ if crate::css::custom_properties::single_css_wide_keyword(values).is_some() {
+ bits |= Self::LONE_CSS_WIDE_KEYWORD;
+ }
+ if crate::css::parser::value_parser::contains_tree_counting_function(values) {
+ bits |= Self::CALLS_TREE_COUNTING_FUNCTION;
+ }
+ Self(bits)
+ }
+
+ fn with_references(self, references: &CustomPropertyReferences<'_>) -> Self {
+ let mut bits = self.0 & !(Self::NAMES_CUSTOM_PROPERTIES | Self::HIDES_A_REFERENCE);
+ if !references.names.is_empty() {
+ bits |= Self::NAMES_CUSTOM_PROPERTIES;
+ }
+ if !references.all_visible {
+ bits |= Self::HIDES_A_REFERENCE;
+ }
+ Self(bits)
+ }
+
+ /// Which substitution functions the text uses.
+ pub(crate) fn presence(self) -> SubstitutionFunctionsPresence {
+ let bit = |index: u16| self.0 & (1 << index) != 0;
+ SubstitutionFunctionsPresence {
+ attr: bit(0),
+ dashed_function: bit(1),
+ env: bit(2),
+ if_: bit(3),
+ inherit: bit(4),
+ var: bit(5),
+ }
+ }
+
+ /// Whether the text is one CSS-wide keyword, beside whitespace.
+ pub(crate) fn is_lone_css_wide_keyword(self) -> bool {
+ self.0 & Self::LONE_CSS_WIDE_KEYWORD != 0
+ }
+
+ /// Whether the text calls sibling-count() or sibling-index().
+ pub(crate) fn calls_tree_counting_function(self) -> bool {
+ self.0 & Self::CALLS_TREE_COUNTING_FUNCTION != 0
+ }
+
+ fn names_custom_properties(self) -> bool {
+ self.0 & Self::NAMES_CUSTOM_PROPERTIES != 0
+ }
+
+ /// What a comment in the text tokenizes as.
+ fn comments(self) -> crate::css::css_tokenizer::Comments {
+ match self.0 & Self::SERIALIZED_BY_THE_ENGINE != 0 {
+ true => crate::css::css_tokenizer::Comments::Separating,
+ false => crate::css::css_tokenizer::Comments::AsWhitespace,
+ }
+ }
+}
+
+/// The custom properties a value's `var()` and `inherit()` functions name, as written, and whether
+/// every one of them names its property with a plain identifier.
+pub(crate) struct CustomPropertyReferences<'a> {
+ pub(crate) names: smallvec::SmallVec<[&'a [u16]; 4]>,
+ pub(crate) all_visible: bool,
+}
+
+impl<'a> CustomPropertyReferences<'a> {
+ /// The references of a value whose text tokenizes to `values`.
+ pub(crate) fn scan(values: &'a [ComponentValue]) -> Self {
+ let mut names = smallvec::SmallVec::new();
+ let all_visible = scan_custom_property_references(values, &mut names);
+ Self { names, all_visible }
+ }
+}
+
+/// What a [`StyleValueData::Unresolved`] holds: the start of one allocation its source text
+/// follows, as one byte per unit where every unit is ASCII, else as UTF-16 code units. Where the
+/// text references custom properties by name, the names follow the text, aligned to 4 bytes: their
+/// count as a `u32`, then each name as its length in a `u32` and its UTF-16 code units, escapes
+/// decoded, aligned to 4 bytes.
+#[repr(C)]
+pub struct UnresolvedPayload {
+ pub parsed_value: RetainedStyleValueData,
+ pub contains_attr_tainted_values: bool,
+ units_are_latin1: bool,
+ facts: UnresolvedFacts,
+ length: u32,
+}
+
+const _: () = assert!(size_of::<UnresolvedPayload>() == 16);
+
+impl UnresolvedPayload {
+ /// The text the value was written as.
+ pub(crate) fn source_text(&self) -> TokenizerInput<'_> {
+ let length = self.length as usize;
+ // SAFETY: The text follows the payload in its allocation, `length` units of the kind it
+ // says.
+ unsafe {
+ let text = std::ptr::from_ref(self).cast::<u8>().add(size_of::<Self>());
+ if self.units_are_latin1 {
+ TokenizerInput::Latin1(ak::slice_from_raw_parts(text, length))
+ } else {
+ TokenizerInput::Utf16(ak::slice_from_raw_parts(text.cast::<u16>(), length))
+ }
+ }
+ }
+
+ /// The components of the value, tokenized from its text for this read.
+ pub(crate) fn components(&self) -> ComponentValueList {
+ components_of_text(self.source_text(), self.facts.comments()).unwrap_or_default()
+ }
+
+ /// What the text holds.
+ pub(crate) fn facts(&self) -> UnresolvedFacts {
+ self.facts
+ }
+
+ /// Which substitution functions the text uses.
+ pub(crate) fn presence(&self) -> SubstitutionFunctionsPresence {
+ self.facts.presence()
+ }
+
+ /// The names of the custom properties the text references, as written, in the order it does.
+ pub(crate) fn references(&self) -> impl Iterator<Item = &[u16]> {
+ let (mut entry, mut remaining) = if self.facts.names_custom_properties() {
+ // SAFETY: Where the text names custom properties, their count follows it, aligned, and
+ // the first name follows the count.
+ unsafe {
+ let count = self
+ .base()
+ .add(Self::table_offset(self.length as usize, self.units_are_latin1))
+ .cast::<u32>();
+ (count.add(1), count.read())
+ }
+ } else {
+ (std::ptr::null(), 0)
+ };
+ std::iter::from_fn(move || {
+ if remaining == 0 {
+ return None;
+ }
+ remaining -= 1;
+ // SAFETY: Each name is its length followed by its units, aligned to 4 bytes; the next
+ // one follows it.
+ unsafe {
+ let length = entry.read() as usize;
+ let units = entry.add(1).cast::<u16>();
+ entry = units.cast::<u8>().add(Self::name_units_bytes(length)).cast::<u32>();
+ Some(ak::slice_from_raw_parts(units, length))
+ }
+ })
+ }
+
+ /// Whether every custom property the text references is among [`Self::references()`]; one
+ /// that is named by anything but a plain identifier is not.
+ pub(crate) fn references_visible(&self) -> bool {
+ self.facts.0 & UnresolvedFacts::HIDES_A_REFERENCE == 0
+ }
+
+ fn base(&self) -> *const u8 {
+ std::ptr::from_ref(self).cast::<u8>()
+ }
+
+ fn text_end(length: usize, units_are_latin1: bool) -> usize {
+ let unit = if units_are_latin1 { 1 } else { size_of::<u16>() };
+ length
+ .checked_mul(unit)
+ .and_then(|bytes| bytes.checked_add(size_of::<Self>()))
+ .expect("unresolved value text too long")
+ }
+
+ fn table_offset(length: usize, units_are_latin1: bool) -> usize {
+ Self::text_end(length, units_are_latin1).next_multiple_of(align_of::<u32>())
+ }
+
+ fn name_units_bytes(length: usize) -> usize {
+ (length * size_of::<u16>()).next_multiple_of(align_of::<u32>())
+ }
+
+ fn table_bytes<'a>(names: impl Iterator<Item = &'a [u16]>) -> usize {
+ names.fold(size_of::<u32>(), |bytes, name| {
+ bytes + size_of::<u32>() + Self::name_units_bytes(name.len())
+ })
+ }
+
+ /// The bytes of the allocation the payload starts.
+ fn allocation_size(&self) -> usize {
+ let length = self.length as usize;
+ if self.facts.names_custom_properties() {
+ Self::table_offset(length, self.units_are_latin1) + Self::table_bytes(self.references())
+ } else {
+ Self::text_end(length, self.units_are_latin1)
+ }
+ }
+
+ fn layout(bytes: usize) -> std::alloc::Layout {
+ std::alloc::Layout::from_size_align(bytes, align_of::<Self>()).expect("unresolved value text too long")
+ }
+}
+
+/// The components `text` tokenizes to, whose comments tokenize as `comments` says: as whitespace
+/// in text an author wrote, as nothing in text the engine serialized from components with
+/// [`ComponentSerializationMode::Retokenize`], which tokenizes back to them.
+pub(crate) fn components_of_text(
+ text: TokenizerInput<'_>,
+ comments: crate::css::css_tokenizer::Comments,
+) -> Result<ComponentValueList, ()> {
+ crate::css::parser::component_value::consume_a_counted_list_of_component_values(
+ crate::css::css_tokenizer::tokenize_for_parser_with_comments(text, comments),
+ )
+}
+
+/// The box of an unresolved value's payload and text, laid out as one pointer C++ reads the
+/// payload through.
+#[repr(C)]
+pub struct UnresolvedBox {
+ pointer: std::ptr::NonNull<UnresolvedPayload>,
+}
+
+// SAFETY: The box owns its payload, whose fields are `Send + Sync`, and its immutable text.
+unsafe impl Send for UnresolvedBox {}
+unsafe impl Sync for UnresolvedBox {}
+
+/// What an unresolved value is made of, which it does not keep: the components its text, as an
+/// author wrote it, tokenizes to, or the components the engine serialized its text from with
+/// [`ComponentSerializationMode::Retokenize`], which the text tokenizes back to with its comments
+/// keeping tokens apart.
+pub(crate) enum UnresolvedValueComponents<'a> {
+ OfText(&'a [ComponentValue]),
+ OfSerialization(&'a [ComponentValue]),
+}
+
+/// The fields of a payload its text and names, written first, say.
+struct UnresolvedTextShape {
+ units_are_latin1: bool,
+ facts: UnresolvedFacts,
+ length: u32,
+}
+
+impl UnresolvedBox {
+ /// The payload of a value written as `source_text`, which need not be well-formed UTF-16, and
+ /// made of `components`, which uses the substitution functions `presence` says.
+ pub(crate) fn new(
+ source_text: TokenizerInput<'_>,
+ components: UnresolvedValueComponents<'_>,
+ presence: SubstitutionFunctionsPresence,
+ contains_attr_tainted_values: bool,
+ parsed_value: RetainedStyleValueData,
+ ) -> Self {
+ let (values, serialized) = match components {
+ UnresolvedValueComponents::OfText(values) => (values, false),
+ UnresolvedValueComponents::OfSerialization(values) => (values, true),
+ };
+ let mut facts = UnresolvedFacts::of(values, presence);
+ if serialized {
+ facts.0 |= UnresolvedFacts::SERIALIZED_BY_THE_ENGINE;
+ }
+ let (base, shape) = Self::allocate(source_text, facts, &CustomPropertyReferences::scan(values));
+ Self::finish(base, shape, contains_attr_tainted_values, parsed_value)
+ }
+
+ /// An allocation holding `source_text` and the names of `references`, whose payload is still
+ /// to be written.
+ fn allocate(
+ source_text: TokenizerInput<'_>,
+ facts: UnresolvedFacts,
+ references: &CustomPropertyReferences<'_>,
+ ) -> (std::ptr::NonNull<u8>, UnresolvedTextShape) {
+ let units_are_latin1 = match source_text {
+ TokenizerInput::Latin1(_) => true,
+ TokenizerInput::Utf16(units) => units.iter().all(|unit| *unit <= 0x7f),
+ };
+ let length = source_text.len();
+ let facts = facts.with_references(references);
+ let table_offset = UnresolvedPayload::table_offset(length, units_are_latin1);
+ let bytes = if facts.names_custom_properties() {
+ table_offset + UnresolvedPayload::table_bytes(references.names.iter().copied())
+ } else {
+ UnresolvedPayload::text_end(length, units_are_latin1)
+ };
+ let layout = UnresolvedPayload::layout(bytes);
+ // SAFETY: The layout is nonzero and covers the payload, its text and its names, each unit
+ // of which is written once.
+ unsafe {
+ let base = std::alloc::alloc(layout);
+ if base.is_null() {
+ std::alloc::handle_alloc_error(layout);
+ }
+ let text = base.add(size_of::<UnresolvedPayload>());
+ match source_text {
+ TokenizerInput::Latin1(bytes) => std::ptr::copy_nonoverlapping(bytes.as_ptr(), text, length),
+ TokenizerInput::Utf16(units) if units_are_latin1 => {
+ for (index, unit) in units.iter().enumerate() {
+ text.add(index).write(*unit as u8);
+ }
+ }
+ TokenizerInput::Utf16(units) => {
+ std::ptr::copy_nonoverlapping(units.as_ptr(), text.cast::<u16>(), length);
+ }
+ }
+ if facts.names_custom_properties() {
+ // NB: Every name is part of the text, so neither the count nor a length can exceed
+ // the text's, which fits in a u32.
+ let count = base.add(table_offset).cast::<u32>();
+ count.write(references.names.len() as u32);
+ let mut entry = count.add(1);
+ for name in &references.names {
+ entry.write(name.len() as u32);
+ let units = entry.add(1).cast::<u16>();
+ std::ptr::copy_nonoverlapping(name.as_ptr(), units, name.len());
+ entry = units
+ .cast::<u8>()
+ .add(UnresolvedPayload::name_units_bytes(name.len()))
+ .cast::<u32>();
+ }
+ }
+ let shape = UnresolvedTextShape {
+ units_are_latin1,
+ facts,
+ length: u32::try_from(length).expect("unresolved value text too long"),
+ };
+ (std::ptr::NonNull::new_unchecked(base), shape)
+ }
+ }
+
+ /// The box of the allocation `allocate` made, its payload written now.
+ fn finish(
+ base: std::ptr::NonNull<u8>,
+ shape: UnresolvedTextShape,
+ contains_attr_tainted_values: bool,
+ parsed_value: RetainedStyleValueData,
+ ) -> Self {
+ let pointer = base.cast::<UnresolvedPayload>();
+ // SAFETY: The allocation starts with room for the payload, written once here.
+ unsafe {
+ pointer.write(UnresolvedPayload {
+ parsed_value,
+ contains_attr_tainted_values,
+ units_are_latin1: shape.units_are_latin1,
+ facts: shape.facts,
+ length: shape.length,
+ });
+ }
+ Self { pointer }
+ }
+
+ /// This payload, written as `source_text`.
+ fn copy_with_text(&self, source_text: TokenizerInput<'_>) -> Self {
+ let references = CustomPropertyReferences {
+ names: self.references().collect(),
+ all_visible: self.references_visible(),
+ };
+ let (base, shape) = Self::allocate(source_text, self.facts, &references);
+ Self::finish(
+ base,
+ shape,
+ self.contains_attr_tainted_values,
+ self.parsed_value.clone(),
+ )
+ }
+
+ /// The payload, to change what it holds beside its text.
+ pub(crate) fn payload_mut(&mut self) -> &mut UnresolvedPayload {
+ // SAFETY: The box owns a live payload, which this borrow alone reaches.
+ unsafe { self.pointer.as_mut() }
+ }
+
+ /// This payload, written as `source_text` instead.
+ pub(crate) fn with_source_text(&self, source_text: TokenizerInput<'_>) -> Self {
+ self.copy_with_text(source_text)
+ }
+}
+
+impl std::ops::Deref for UnresolvedBox {
+ type Target = UnresolvedPayload;
+
+ fn deref(&self) -> &UnresolvedPayload {
+ // SAFETY: The box owns a live payload.
+ unsafe { self.pointer.as_ref() }
+ }
+}
+
+impl Clone for UnresolvedBox {
+ fn clone(&self) -> Self {
+ self.copy_with_text(self.source_text())
+ }
+}
+
+impl PartialEq for UnresolvedBox {
+ fn eq(&self, other: &Self) -> bool {
+ let same_text = match (self.source_text(), other.source_text()) {
+ (TokenizerInput::Latin1(first), TokenizerInput::Latin1(second)) => first == second,
+ (TokenizerInput::Utf16(first), TokenizerInput::Utf16(second)) => first == second,
+ // NB: Text up to U+00FF may be kept as bytes or as UTF-16, whichever it arrived as.
+ (TokenizerInput::Latin1(bytes), TokenizerInput::Utf16(units))
+ | (TokenizerInput::Utf16(units), TokenizerInput::Latin1(bytes)) => {
+ bytes.iter().copied().map(u16::from).eq(units.iter().copied())
+ }
+ };
+ same_text
+ && self.facts == other.facts
+ && self.contains_attr_tainted_values == other.contains_attr_tainted_values
+ && self.parsed_value == other.parsed_value
+ }
+}
+
+impl Drop for UnresolvedBox {
+ fn drop(&mut self) {
+ let layout = UnresolvedPayload::layout(self.allocation_size());
+ // SAFETY: The box owns the payload and the allocation `new` made.
+ unsafe {
+ std::ptr::drop_in_place(self.pointer.as_ptr());
+ std::alloc::dealloc(self.pointer.as_ptr().cast(), layout);
+ }
+ }
+}
+
+/// What a [`StyleValueData::Url`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct UrlPayload {
+ pub url: RetainedString,
+ pub url_type: u8,
+ pub modifiers: RetainedRequestUrlModifierList,
+}
+
+/// What a [`StyleValueData::FontSource`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct FontSourcePayload {
+ pub is_local: bool,
+ pub url_type: u8,
+ pub has_format: bool,
+ pub local_name: RetainedStyleValueData,
+ pub url: RetainedString,
+ pub url_modifiers: RetainedRequestUrlModifierList,
+ pub format: CssString,
+ pub tech: RetainedByteList,
+}
+
+/// What a [`StyleValueData::RadialSize`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct RadialSizePayload {
+ pub component_count: u8,
+ pub is_extent_0: bool,
+ pub extent_0: u8,
+ pub value_0: RetainedStyleValueData,
+ pub is_extent_1: bool,
+ pub extent_1: u8,
+ pub value_1: RetainedStyleValueData,
+}
+
+/// What a [`StyleValueData::Transformation`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct TransformationPayload {
+ pub property: u16,
+ pub transform_function: u8,
+ pub values: RetainedStyleValueDataList,
+ /// Matrix-only arguments preserving literal angle precision across canonicalization.
+ /// Empty when the canonical arguments lower to the same matrix inputs.
+ pub matrix_values: RetainedStyleValueDataList,
+}
+
+/// What a [`StyleValueData::Shorthand`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct ShorthandPayload {
+ pub shorthand_property: u16,
+ pub sub_properties: RetainedPropertyIdList,
+ pub values: RetainedStyleValueDataList,
+}
+
+/// What a [`StyleValueData::BorderRadiusRect`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct BorderRadiusRectPayload {
+ pub top_left: RetainedStyleValueData,
+ pub top_right: RetainedStyleValueData,
+ pub bottom_right: RetainedStyleValueData,
+ pub bottom_left: RetainedStyleValueData,
+}
+
+/// What a [`StyleValueData::BorderRadius`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct BorderRadiusPayload {
+ pub is_elliptical: bool,
+ pub horizontal_radius: RetainedStyleValueData,
+ pub vertical_radius: RetainedStyleValueData,
+}
+
+/// What a [`StyleValueData::Ray`] holds, boxed so that a style value stays small.
+#[repr(C)]
+#[derive(Clone, PartialEq)]
+pub struct RayPayload {
+ pub size: u16,
+ pub contain: bool,
+ pub angle: RetainedStyleValueData,
+ pub position: RetainedStyleValueData,
+}
+
+// The kinds of a filter style value, which are C++ enum values.
+pub(crate) const FILTER_KIND_BLUR: u8 = 0;
+pub(crate) const FILTER_KIND_DROP_SHADOW: u8 = 1;
pub(crate) const FILTER_KIND_HUE_ROTATE: u8 = 2;
pub(crate) const FILTER_KIND_COLOR: u8 = 3;
+impl StyleValueData {
+ /// The shared prefix of every color variant.
+ pub(crate) fn color_base(&self) -> Option<&ColorBase> {
+ match self {
+ Self::ContrastColor { color_base, .. } => Some(color_base),
+ Self::ColorFunction(color_function) => Some(&color_function.color_base),
+ Self::ColorMix(color_mix) => Some(&color_mix.color_base),
+ Self::LightDark(light_dark) => Some(&light_dark.color_base),
+ _ => None,
+ }
+ }
+
+ /// The bytes of the box a variant too large to hold inline keeps its payload in.
+ pub(crate) fn boxed_payload_bytes(&self) -> usize {
+ match self {
+ Self::Calculated(payload) => size_of_val::<CalculatedPayload>(payload),
+ Self::Ratio(payload) => size_of_val::<RatioPayload>(payload),
+ Self::ScrollbarColor(payload) => size_of_val::<ScrollbarColorPayload>(payload),
+ Self::Rect(payload) => size_of_val::<RectPayload>(payload),
+ Self::Function(payload) => size_of_val::<FunctionPayload>(payload),
+ Self::OpenTypeTagged(payload) => size_of_val::<OpenTypeTaggedPayload>(payload),
+ Self::BorderImageSlice(payload) => size_of_val::<BorderImageSlicePayload>(payload),
+ Self::AnchorSize(payload) => size_of_val::<AnchorSizePayload>(payload),
+ Self::Anchor(payload) => size_of_val::<AnchorPayload>(payload),
+ Self::Position(payload) => size_of_val::<PositionPayload>(payload),
+ Self::Shadow(payload) => size_of_val::<ShadowPayload>(payload),
+ Self::Content(payload) => size_of_val::<ContentPayload>(payload),
+ Self::CounterStyleSystem(payload) => size_of_val::<CounterStyleSystemPayload>(payload),
+ Self::CounterStyle(payload) => size_of_val::<CounterStylePayload>(payload),
+ Self::ColorFunction(payload) => size_of_val::<ColorFunctionPayload>(payload),
+ Self::ColorMix(payload) => size_of_val::<ColorMixPayload>(payload),
+ Self::LinearGradient(payload) => size_of_val::<LinearGradientPayload>(payload),
+ Self::ConicGradient(payload) => size_of_val::<ConicGradientPayload>(payload),
+ Self::RadialGradient(payload) => size_of_val::<RadialGradientPayload>(payload),
+ Self::Image(payload) => size_of_val::<ImagePayload>(payload),
+ Self::ImageSet(payload) => size_of_val::<ImageSetPayload>(payload),
+ Self::Easing(payload) => size_of_val::<EasingPayload>(payload),
+ Self::Cursor(payload) => size_of_val::<CursorPayload>(payload),
+ Self::GridTrackSizeList(payload) => size_of_val::<GridTrackSizeListPayload>(payload),
+ Self::GridTemplateArea(payload) => size_of_val::<GridTemplateAreaPayload>(payload),
+ Self::CounterDefinitions(payload) => size_of_val::<CounterDefinitionsPayload>(payload),
+ Self::GridTrackPlacement(payload) => size_of_val::<GridTrackPlacementPayload>(payload),
+ Self::Counter(payload) => size_of_val::<CounterPayload>(payload),
+ Self::LightDark(payload) => size_of_val::<LightDarkPayload>(payload),
+ Self::RandomValueSharing(payload) => size_of_val::<RandomValueSharingPayload>(payload),
+ Self::ColorScheme(payload) => size_of_val::<ColorSchemePayload>(payload),
+ Self::Unresolved(payload) => size_of_val::<UnresolvedPayload>(payload),
+ Self::Url(payload) => size_of_val::<UrlPayload>(payload),
+ Self::FontSource(payload) => size_of_val::<FontSourcePayload>(payload),
+ Self::RadialSize(payload) => size_of_val::<RadialSizePayload>(payload),
+ Self::Transformation(payload) => size_of_val::<TransformationPayload>(payload),
+ Self::Shorthand(payload) => size_of_val::<ShorthandPayload>(payload),
+ Self::BorderRadiusRect(payload) => size_of_val::<BorderRadiusRectPayload>(payload),
+ Self::BorderRadius(payload) => size_of_val::<BorderRadiusPayload>(payload),
+ Self::Ray(payload) => size_of_val::<RayPayload>(payload),
+ Self::BackgroundSize(payload) => size_of_val::<BackgroundSizePayload>(payload),
+ _ => 0,
+ }
+ }
+
+ /// The values a list, tuple, shorthand or transform function holds.
+ pub(crate) fn child_values(&self) -> Option<&RetainedStyleValueDataList> {
+ match self {
+ Self::ValueList { values, .. } | Self::Tuple { values } => Some(values),
+ Self::Shorthand(shorthand) => Some(&shorthand.values),
+ Self::Transformation(transformation) => Some(&transformation.values),
+ _ => None,
+ }
+ }
+
+ pub(crate) fn as_counter_style_system(&self) -> Option<&CounterStyleSystemPayload> {
+ match self {
+ Self::CounterStyleSystem(system) => Some(system),
+ _ => None,
+ }
+ }
+
+ pub(crate) fn as_counter_style(&self) -> Option<&CounterStylePayload> {
+ match self {
+ Self::CounterStyle(counter_style) => Some(counter_style),
+ _ => None,
+ }
+ }
+
+ /// Whether an anchor() or anchor-size() names its anchor, the name, and its fallback value.
+ pub(crate) fn anchor_name_and_fallback(&self) -> Option<(bool, &CssString, &RetainedStyleValueData)> {
+ match self {
+ Self::Anchor(anchor) => Some((anchor.has_anchor_name, &anchor.anchor_name, &anchor.fallback_value)),
+ Self::AnchorSize(anchor_size) => Some((
+ anchor_size.has_anchor_name,
+ &anchor_size.anchor_name,
+ &anchor_size.fallback_value,
+ )),
+ _ => None,
+ }
+ }
+}
+
pub(crate) fn is_none_keyword(value: &StyleValueData) -> bool {
matches!(value, StyleValueData::Keyword { keyword: code } if *code == crate::css::css_enums::keyword::NONE)
}
-// A larger variant would increase every scalar value's allocation as well.
-const _: () = assert!(size_of::<StyleValueData>() <= 64);
+// Every value pays for the largest variant, so a variant that does not fit beside the tag in 16
+// bytes holds its payload in a box, and a length takes 16 bytes.
+const _: () = assert!(size_of::<StyleValueData>() <= 16);
/// One entry in a computed font-family list. A generic family carries its Keyword code;
/// a named family borrows the Rust string retained by the style value.
@@ -2546,23 +3553,25 @@ impl StyleValueData {
hasher.write_u8(*fill_rule);
path.write_content_hash(hasher);
}
- Self::Calculated {
- rust_calculation: _,
- resolve_as_is_number,
- resolve_as_base,
- resolved_type: _,
- has_percentages_resolve_as,
- percentages_resolve_as,
- resolve_numbers_as_integers,
- accepted_ranges: _,
- } => {
+ StyleValueData::Calculated(calculated_payload) => {
+ let CalculatedPayload {
+ rust_calculation: _,
+ resolve_as_is_number,
+ resolve_as_base,
+ resolved_type: _,
+ has_percentages_resolve_as,
+ percentages_resolve_as,
+ resolve_numbers_as_integers,
+ accepted_ranges: _,
+ } = &**calculated_payload;
write_bool(hasher, *resolve_as_is_number);
hasher.write_u8(*resolve_as_base);
write_bool(hasher, *has_percentages_resolve_as);
hasher.write_u8(*percentages_resolve_as);
write_bool(hasher, *resolve_numbers_as_integers);
}
- Self::Ratio { numerator, denominator } => {
+ StyleValueData::Ratio(ratio_payload) => {
+ let RatioPayload { numerator, denominator } = &**ratio_payload;
write_value(hasher, numerator);
write_value(hasher, denominator);
}
@@ -2595,36 +3604,41 @@ impl StyleValueData {
Self::Superellipse { parameter } => write_value(hasher, parameter),
Self::PendingSubstitution {
original_shorthand_value,
+ ..
} => write_value(hasher, original_shorthand_value),
- Self::ScrollbarColor {
- thumb_color,
- track_color,
- } => {
+ StyleValueData::ScrollbarColor(scrollbar_color_payload) => {
+ let ScrollbarColorPayload {
+ thumb_color,
+ track_color,
+ } = &**scrollbar_color_payload;
write_value(hasher, thumb_color);
write_value(hasher, track_color);
}
- Self::Rect {
- top,
- right,
- bottom,
- left,
- } => {
+ StyleValueData::Rect(rect_payload) => {
+ let RectPayload {
+ top,
+ right,
+ bottom,
+ left,
+ } = &**rect_payload;
write_value(hasher, top);
write_value(hasher, right);
write_value(hasher, bottom);
write_value(hasher, left);
}
Self::String { string, .. } => write_fly(hasher, string),
- Self::Function { name, value } => {
+ StyleValueData::Function(function_payload) => {
+ let FunctionPayload { name, value } = &**function_payload;
write_fly(hasher, name);
write_value(hasher, value);
}
- Self::OpenTypeTagged {
- mode,
- tag_name: tag,
- packed_tag,
- value,
- } => {
+ StyleValueData::OpenTypeTagged(open_type_tagged_payload) => {
+ let OpenTypeTaggedPayload {
+ mode,
+ tag_name: tag,
+ packed_tag,
+ value,
+ } = &**open_type_tagged_payload;
hasher.write_u8(*mode);
write_fly(hasher, tag);
hasher.write_u32(*packed_tag);
@@ -2662,7 +3676,8 @@ impl StyleValueData {
hasher.write_u8(*function);
hasher.write_u8(*computed_type);
}
- Self::BackgroundSize { size_x, size_y } => {
+ StyleValueData::BackgroundSize(background_size_payload) => {
+ let BackgroundSizePayload { size_x, size_y } = &**background_size_payload;
write_value(hasher, size_x);
write_value(hasher, size_y);
}
@@ -2670,56 +3685,61 @@ impl StyleValueData {
hasher.write_u8(*repeat_x);
hasher.write_u8(*repeat_y);
}
- Self::BorderImageSlice {
- top,
- right,
- bottom,
- left,
- fill,
- } => {
+ StyleValueData::BorderImageSlice(border_image_slice_payload) => {
+ let BorderImageSlicePayload {
+ top,
+ right,
+ bottom,
+ left,
+ fill,
+ } = &**border_image_slice_payload;
write_value(hasher, top);
write_value(hasher, right);
write_value(hasher, bottom);
write_value(hasher, left);
write_bool(hasher, *fill);
}
- Self::AnchorSize {
- has_anchor_name,
- anchor_name,
- has_anchor_size,
- anchor_size,
- fallback_value,
- } => {
+ StyleValueData::AnchorSize(anchor_size_payload) => {
+ let AnchorSizePayload {
+ has_anchor_name,
+ anchor_name,
+ has_anchor_size,
+ anchor_size,
+ fallback_value,
+ } = &**anchor_size_payload;
write_bool(hasher, *has_anchor_name);
write_fly(hasher, anchor_name);
write_bool(hasher, *has_anchor_size);
hasher.write_u8(*anchor_size);
write_value(hasher, fallback_value);
}
- Self::Anchor {
- has_anchor_name,
- anchor_name,
- anchor_side,
- fallback_value,
- } => {
+ StyleValueData::Anchor(anchor_payload) => {
+ let AnchorPayload {
+ has_anchor_name,
+ anchor_name,
+ anchor_side,
+ fallback_value,
+ } = &**anchor_payload;
write_bool(hasher, *has_anchor_name);
write_fly(hasher, anchor_name);
write_value(hasher, anchor_side);
write_value(hasher, fallback_value);
}
- Self::Position { edge_x, edge_y } => {
+ StyleValueData::Position(position_payload) => {
+ let PositionPayload { edge_x, edge_y } = &**position_payload;
write_value(hasher, edge_x);
write_value(hasher, edge_y);
}
- Self::Shadow {
- shadow_type,
- color,
- offset_x,
- offset_y,
- blur_radius,
- spread_distance,
- placement,
- } => {
+ StyleValueData::Shadow(shadow_payload) => {
+ let ShadowPayload {
+ shadow_type,
+ color,
+ offset_x,
+ offset_y,
+ blur_radius,
+ spread_distance,
+ placement,
+ } = &**shadow_payload;
hasher.write_u8(*shadow_type);
write_value(hasher, color);
write_value(hasher, offset_x);
@@ -2728,27 +3748,30 @@ impl StyleValueData {
write_value(hasher, spread_distance);
hasher.write_u8(*placement);
}
- Self::Content { content, alt_text } => {
+ StyleValueData::Content(content_payload) => {
+ let ContentPayload { content, alt_text } = &**content_payload;
write_value(hasher, content);
write_value(hasher, alt_text);
}
- Self::CounterStyleSystem {
- kind,
- system,
- first_symbol,
- name,
- } => {
+ StyleValueData::CounterStyleSystem(counter_style_system_payload) => {
+ let CounterStyleSystemPayload {
+ kind,
+ system,
+ first_symbol,
+ name,
+ } = &**counter_style_system_payload;
hasher.write_u8(*kind);
hasher.write_u8(*system);
write_value(hasher, first_symbol);
write_fly(hasher, name);
}
- Self::CounterStyle {
- is_symbols,
- name,
- symbols_type,
- symbols,
- } => {
+ StyleValueData::CounterStyle(counter_style_payload) => {
+ let CounterStylePayload {
+ is_symbols,
+ name,
+ symbols_type,
+ symbols,
+ } = &**counter_style_payload;
write_bool(hasher, *is_symbols);
write_fly(hasher, name);
hasher.write_u8(*symbols_type);
@@ -2756,16 +3779,17 @@ impl StyleValueData {
write_fly(hasher, string);
}
}
- Self::ColorFunction {
- color_base,
- channel_0,
- channel_1,
- channel_2,
- alpha,
- has_name,
- name,
- origin_color,
- } => {
+ StyleValueData::ColorFunction(color_function_payload) => {
+ let ColorFunctionPayload {
+ color_base,
+ channel_0,
+ channel_1,
+ channel_2,
+ alpha,
+ has_name,
+ name,
+ origin_color,
+ } = &**color_function_payload;
// NB: Equality ignores the color syntax, and the color type and name when absent.
write_bool(hasher, color_base.has_color_type);
if color_base.has_color_type {
@@ -2781,27 +3805,29 @@ impl StyleValueData {
}
write_value(hasher, origin_color);
}
- Self::ColorMix {
- color_base,
- color_interpolation_method,
- colors,
- percentages,
- } => {
+ StyleValueData::ColorMix(color_mix_payload) => {
+ let ColorMixPayload {
+ color_base,
+ color_interpolation_method,
+ colors,
+ percentages,
+ } = &**color_mix_payload;
write_color_base(hasher, color_base);
write_value(hasher, color_interpolation_method);
write_values(hasher, colors);
write_values(hasher, percentages);
}
- Self::LinearGradient {
- has_direction_value,
- direction_value,
- side_or_corner,
- color_stop_list,
- gradient_type,
- repeating,
- color_interpolation_method,
- color_syntax,
- } => {
+ StyleValueData::LinearGradient(linear_gradient_payload) => {
+ let LinearGradientPayload {
+ has_direction_value,
+ direction_value,
+ side_or_corner,
+ color_stop_list,
+ gradient_type,
+ repeating,
+ color_interpolation_method,
+ color_syntax,
+ } = &**linear_gradient_payload;
write_bool(hasher, *has_direction_value);
write_value(hasher, direction_value);
hasher.write_u8(*side_or_corner);
@@ -2811,14 +3837,15 @@ impl StyleValueData {
write_value(hasher, color_interpolation_method);
hasher.write_u8(*color_syntax);
}
- Self::ConicGradient {
- from_angle,
- position,
- color_stop_list,
- repeating,
- color_interpolation_method,
- color_syntax,
- } => {
+ StyleValueData::ConicGradient(conic_gradient_payload) => {
+ let ConicGradientPayload {
+ from_angle,
+ position,
+ color_stop_list,
+ repeating,
+ color_interpolation_method,
+ color_syntax,
+ } = &**conic_gradient_payload;
write_value(hasher, from_angle);
write_value(hasher, position);
write_color_stops(hasher, color_stop_list);
@@ -2826,15 +3853,16 @@ impl StyleValueData {
write_value(hasher, color_interpolation_method);
hasher.write_u8(*color_syntax);
}
- Self::RadialGradient {
- ending_shape,
- size,
- position,
- color_stop_list,
- repeating,
- color_interpolation_method,
- color_syntax,
- } => {
+ StyleValueData::RadialGradient(radial_gradient_payload) => {
+ let RadialGradientPayload {
+ ending_shape,
+ size,
+ position,
+ color_stop_list,
+ repeating,
+ color_interpolation_method,
+ color_syntax,
+ } = &**radial_gradient_payload;
hasher.write_u8(*ending_shape);
write_value(hasher, size);
write_value(hasher, position);
@@ -2843,11 +3871,13 @@ impl StyleValueData {
write_value(hasher, color_interpolation_method);
hasher.write_u8(*color_syntax);
}
- Self::Image { url, url_type, .. } => {
+ StyleValueData::Image(image_payload) => {
+ let ImagePayload { url, url_type, .. } = &**image_payload;
url.hash(hasher);
hasher.write_u8(*url_type);
}
- Self::ImageSet { options } => {
+ StyleValueData::ImageSet(image_set_payload) => {
+ let ImageSetPayload { options } = &**image_set_payload;
hasher.write_usize(options.as_slice().len());
for option in options.as_slice() {
write_value(hasher, &option.image);
@@ -2856,17 +3886,18 @@ impl StyleValueData {
write_fly(hasher, &option.type_string);
}
}
- Self::Easing {
- kind,
- linear_stops,
- x1,
- y1,
- x2,
- y2,
- number_of_intervals,
- step_position,
- is_keyword,
- } => {
+ StyleValueData::Easing(easing_payload) => {
+ let EasingPayload {
+ kind,
+ linear_stops,
+ x1,
+ y1,
+ x2,
+ y2,
+ number_of_intervals,
+ step_position,
+ is_keyword,
+ } = &**easing_payload;
hasher.write_u8(*kind);
write_bool(hasher, *is_keyword);
hasher.write_usize(linear_stops.as_slice().len());
@@ -2881,25 +3912,28 @@ impl StyleValueData {
write_value(hasher, number_of_intervals);
hasher.write_u8(*step_position);
}
- Self::Cursor { image, x, y } => {
+ StyleValueData::Cursor(cursor_payload) => {
+ let CursorPayload { image, x, y } = &**cursor_payload;
write_value(hasher, image);
write_value(hasher, x);
write_value(hasher, y);
}
- Self::GridTrackSizeList {
- is_subgrid,
- preserve_line_name_sets,
- entries,
- } => {
+ StyleValueData::GridTrackSizeList(grid_track_size_list_payload) => {
+ let GridTrackSizeListPayload {
+ is_subgrid,
+ preserve_line_name_sets,
+ entries,
+ } = &**grid_track_size_list_payload;
write_bool(hasher, *is_subgrid);
write_bool(hasher, *preserve_line_name_sets);
write_grid_track_entries(hasher, entries.as_slice());
}
- Self::GridTemplateArea {
- grid_areas,
- row_count,
- column_count,
- } => {
+ StyleValueData::GridTemplateArea(grid_template_area_payload) => {
+ let GridTemplateAreaPayload {
+ grid_areas,
+ row_count,
+ column_count,
+ } = &**grid_template_area_payload;
hasher.write_usize(grid_areas.as_slice().len());
for area in grid_areas.as_slice() {
write_fly(hasher, &area.name);
@@ -2912,7 +3946,8 @@ impl StyleValueData {
hasher.write_usize(*row_count);
hasher.write_usize(*column_count);
}
- Self::CounterDefinitions { counter_definitions } => {
+ StyleValueData::CounterDefinitions(counter_definitions_payload) => {
+ let CounterDefinitionsPayload { counter_definitions } = &**counter_definitions_payload;
hasher.write_usize(counter_definitions.as_slice().len());
for definition in counter_definitions.as_slice() {
write_fly(hasher, &definition.name);
@@ -2920,46 +3955,50 @@ impl StyleValueData {
write_value(hasher, &definition.value);
}
}
- Self::GridTrackPlacement {
- kind,
- value,
- has_name,
- name,
- implicit_start_name: _,
- implicit_end_name: _,
- } => {
+ StyleValueData::GridTrackPlacement(grid_track_placement_payload) => {
+ let GridTrackPlacementPayload {
+ kind,
+ value,
+ has_name,
+ name,
+ implicit_start_name: _,
+ implicit_end_name: _,
+ } = &**grid_track_placement_payload;
hasher.write_u8(*kind);
write_value(hasher, value);
write_bool(hasher, *has_name);
write_fly(hasher, name);
}
- Self::Counter {
- function,
- counter_name,
- counter_style,
- join_string,
- } => {
+ StyleValueData::Counter(counter_payload) => {
+ let CounterPayload {
+ function,
+ counter_name,
+ counter_style,
+ join_string,
+ } = &**counter_payload;
hasher.write_u8(*function);
write_fly(hasher, counter_name);
write_value(hasher, counter_style);
write_fly(hasher, join_string);
}
- Self::LightDark {
- color_base,
- light,
- dark,
- } => {
+ StyleValueData::LightDark(light_dark_payload) => {
+ let LightDarkPayload {
+ color_base,
+ light,
+ dark,
+ } = &**light_dark_payload;
write_color_base(hasher, color_base);
write_value(hasher, light);
write_value(hasher, dark);
}
- Self::RandomValueSharing {
- fixed_value,
- is_auto,
- has_name,
- name,
- element_shared,
- } => {
+ StyleValueData::RandomValueSharing(random_value_sharing_payload) => {
+ let RandomValueSharingPayload {
+ fixed_value,
+ is_auto,
+ has_name,
+ name,
+ element_shared,
+ } = &**random_value_sharing_payload;
write_value(hasher, fixed_value);
write_bool(hasher, *is_auto);
write_bool(hasher, *has_name);
@@ -2987,30 +4026,32 @@ impl StyleValueData {
}
Self::Tuple { values } => write_values(hasher, values),
Self::Display { raw } => hasher.write_u32(*raw),
- Self::ColorScheme {
- schemes,
- scheme_codes,
- only,
- } => {
+ StyleValueData::ColorScheme(color_scheme_payload) => {
+ let ColorSchemePayload {
+ schemes,
+ scheme_codes,
+ only,
+ } = &**color_scheme_payload;
for string in schemes.as_slice() {
write_fly(hasher, string);
}
hasher.write(scheme_codes.as_slice());
write_bool(hasher, *only);
}
- Self::Unresolved {
- components: _,
- source_text,
- presence_attr,
- presence_dashed_function,
- presence_env,
- presence_if,
- presence_inherit,
- presence_var,
- contains_attr_tainted_values,
- parsed_value: _,
- } => {
- hash_string_units(hasher, TokenizerInput::from(source_text));
+ StyleValueData::Unresolved(unresolved_payload) => {
+ let unresolved_payload: &UnresolvedPayload = unresolved_payload;
+ let UnresolvedPayload {
+ contains_attr_tainted_values,
+ ..
+ } = unresolved_payload;
+ let source_text = unresolved_payload.source_text();
+ let presence_attr = &unresolved_payload.presence().attr;
+ let presence_dashed_function = &unresolved_payload.presence().dashed_function;
+ let presence_env = &unresolved_payload.presence().env;
+ let presence_if = &unresolved_payload.presence().if_;
+ let presence_inherit = &unresolved_payload.presence().inherit;
+ let presence_var = &unresolved_payload.presence().var;
+ hash_string_units(hasher, source_text);
write_bool(hasher, *presence_attr);
write_bool(hasher, *presence_dashed_function);
write_bool(hasher, *presence_env);
@@ -3019,24 +4060,26 @@ impl StyleValueData {
write_bool(hasher, *presence_var);
write_bool(hasher, *contains_attr_tainted_values);
}
- Self::Url {
- url,
- url_type,
- modifiers: _,
- } => {
+ StyleValueData::Url(url_payload) => {
+ let UrlPayload {
+ url,
+ url_type,
+ modifiers: _,
+ } = &**url_payload;
url.hash(hasher);
hasher.write_u8(*url_type);
}
- Self::FontSource {
- is_local,
- local_name,
- url,
- url_type,
- url_modifiers: _,
- has_format,
- format,
- tech,
- } => {
+ StyleValueData::FontSource(font_source_payload) => {
+ let FontSourcePayload {
+ is_local,
+ local_name,
+ url,
+ url_type,
+ url_modifiers: _,
+ has_format,
+ format,
+ tech,
+ } = &**font_source_payload;
write_bool(hasher, *is_local);
write_value(hasher, local_name);
url.hash(hasher);
@@ -3045,15 +4088,16 @@ impl StyleValueData {
write_fly(hasher, format);
hasher.write(tech.as_slice());
}
- Self::RadialSize {
- component_count,
- is_extent_0,
- extent_0,
- value_0,
- is_extent_1,
- extent_1,
- value_1,
- } => {
+ StyleValueData::RadialSize(radial_size_payload) => {
+ let RadialSizePayload {
+ component_count,
+ is_extent_0,
+ extent_0,
+ value_0,
+ is_extent_1,
+ extent_1,
+ value_1,
+ } = &**radial_size_payload;
hasher.write_u8(*component_count);
write_bool(hasher, *is_extent_0);
hasher.write_u8(*extent_0);
@@ -3062,22 +4106,24 @@ impl StyleValueData {
hasher.write_u8(*extent_1);
write_value(hasher, value_1);
}
- Self::Transformation {
- property,
- transform_function,
- values,
- matrix_values,
- } => {
+ StyleValueData::Transformation(transformation_payload) => {
+ let TransformationPayload {
+ property,
+ transform_function,
+ values,
+ matrix_values,
+ } = &**transformation_payload;
hasher.write_u16(*property);
hasher.write_u8(*transform_function);
write_values(hasher, values);
write_values(hasher, matrix_values);
}
- Self::Shorthand {
- shorthand_property,
- sub_properties,
- values,
- } => {
+ StyleValueData::Shorthand(shorthand_payload) => {
+ let ShorthandPayload {
+ shorthand_property,
+ sub_properties,
+ values,
+ } = &**shorthand_payload;
hasher.write_u16(*shorthand_property);
for id in sub_properties.as_slice() {
hasher.write_u16(*id);
@@ -3085,22 +4131,24 @@ impl StyleValueData {
write_values(hasher, values);
}
Self::CustomIdent { custom_ident } => write_fly(hasher, custom_ident),
- Self::BorderRadiusRect {
- top_left,
- top_right,
- bottom_right,
- bottom_left,
- } => {
+ StyleValueData::BorderRadiusRect(border_radius_rect_payload) => {
+ let BorderRadiusRectPayload {
+ top_left,
+ top_right,
+ bottom_right,
+ bottom_left,
+ } = &**border_radius_rect_payload;
write_value(hasher, top_left);
write_value(hasher, top_right);
write_value(hasher, bottom_right);
write_value(hasher, bottom_left);
}
- Self::BorderRadius {
- is_elliptical,
- horizontal_radius,
- vertical_radius,
- } => {
+ StyleValueData::BorderRadius(border_radius_payload) => {
+ let BorderRadiusPayload {
+ is_elliptical,
+ horizontal_radius,
+ vertical_radius,
+ } = &**border_radius_payload;
write_bool(hasher, *is_elliptical);
write_value(hasher, horizontal_radius);
write_value(hasher, vertical_radius);
@@ -3114,12 +4162,13 @@ impl StyleValueData {
hasher.write_u8(*color_operation);
write_value(hasher, value);
}
- Self::Ray {
- size,
- contain,
- angle,
- position,
- } => {
+ StyleValueData::Ray(ray_payload) => {
+ let RayPayload {
+ size,
+ contain,
+ angle,
+ position,
+ } = &**ray_payload;
hasher.write_u16(*size);
write_bool(hasher, *contain);
write_value(hasher, angle);
@@ -3131,70 +4180,72 @@ impl StyleValueData {
#[unsafe(no_mangle)]
pub extern "C" fn rust_style_value_create_keyword(keyword: u16) -> *const StyleValueData {
- Arc::into_raw(shared_style_value(StyleValueData::Keyword { keyword }))
+ StyleValueArc::into_raw(shared_style_value(StyleValueData::Keyword { keyword }))
}
#[unsafe(no_mangle)]
pub extern "C" fn rust_style_value_create_number(value: f64) -> *const StyleValueData {
- Arc::into_raw(shared_style_value(StyleValueData::Number { value }))
+ StyleValueArc::into_raw(shared_style_value(StyleValueData::Number { value }))
}
#[unsafe(no_mangle)]
pub extern "C" fn rust_style_value_create_integer(value: i32) -> *const StyleValueData {
- Arc::into_raw(shared_style_value(StyleValueData::Integer { value }))
+ StyleValueArc::into_raw(shared_style_value(StyleValueData::Integer { value }))
}
#[unsafe(no_mangle)]
pub extern "C" fn rust_style_value_create_angle(value: f64, unit: u8) -> *const StyleValueData {
- Arc::into_raw(Arc::new(StyleValueData::Angle { value, unit }))
+ StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::Angle { value, unit }))
}
#[unsafe(no_mangle)]
pub extern "C" fn rust_style_value_create_flex(value: f64, unit: u8) -> *const StyleValueData {
- Arc::into_raw(Arc::new(StyleValueData::Flex { value, unit }))
+ StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::Flex { value, unit }))
}
#[unsafe(no_mangle)]
pub extern "C" fn rust_style_value_create_frequency(value: f64, unit: u8) -> *const StyleValueData {
- Arc::into_raw(Arc::new(StyleValueData::Frequency { value, unit }))
+ StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::Frequency { value, unit }))
}
#[unsafe(no_mangle)]
pub extern "C" fn rust_style_value_create_length(value: f64, unit: u8) -> *const StyleValueData {
- Arc::into_raw(shared_style_value(StyleValueData::Length { value, unit }))
+ StyleValueArc::into_raw(shared_style_value(StyleValueData::Length { value, unit }))
}
#[unsafe(no_mangle)]
pub extern "C" fn rust_style_value_create_percentage(value: f64) -> *const StyleValueData {
- Arc::into_raw(shared_style_value(StyleValueData::Percentage { value }))
+ StyleValueArc::into_raw(shared_style_value(StyleValueData::Percentage { value }))
}
#[unsafe(no_mangle)]
pub extern "C" fn rust_style_value_create_resolution(value: f64, unit: u8) -> *const StyleValueData {
- Arc::into_raw(Arc::new(StyleValueData::Resolution { value, unit }))
+ StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::Resolution { value, unit }))
}
#[unsafe(no_mangle)]
pub extern "C" fn rust_style_value_create_time(value: f64, unit: u8) -> *const StyleValueData {
- Arc::into_raw(Arc::new(StyleValueData::Time { value, unit }))
+ StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::Time { value, unit }))
}
/// Takes ownership of one strong reference to each of the numerator and denominator.
#[unsafe(no_mangle)]
pub extern "C" fn rust_style_value_create_ratio(
- numerator: OwnedArc<StyleValueData>,
- denominator: OwnedArc<StyleValueData>,
+ numerator: OwnedStyleValue,
+ denominator: OwnedStyleValue,
) -> *const StyleValueData {
- Arc::into_raw(Arc::new(StyleValueData::Ratio {
- numerator: RetainedStyleValueData::from_arc(numerator.into_arc()),
- denominator: RetainedStyleValueData::from_arc(denominator.into_arc()),
- }))
+ StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::Ratio(StyleValueBox::new(
+ RatioPayload {
+ numerator: RetainedStyleValueData::from_arc(numerator.into_arc()),
+ denominator: RetainedStyleValueData::from_arc(denominator.into_arc()),
+ },
+ ))))
}
/// Takes ownership of one strong reference to the number, percentage or calculated value.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_style_value_create_opacity_value(value: *const StyleValueData) -> *const StyleValueData {
- Arc::into_raw(Arc::new(StyleValueData::OpacityValue {
+ StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::OpacityValue {
value: unsafe { RetainedStyleValueData::from_retained_pointer(value) },
}))
}
@@ -3206,7 +4257,7 @@ pub unsafe extern "C" fn rust_style_value_create_text_indent(
hanging: bool,
each_line: bool,
) -> *const StyleValueData {
- Arc::into_raw(Arc::new(StyleValueData::TextIndent {
+ StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::TextIndent {
length_percentage: unsafe { RetainedStyleValueData::from_retained_pointer(length_percentage) },
hanging,
each_line,
@@ -3225,26 +4276,26 @@ pub unsafe extern "C" fn rust_style_value_create_grid_track_size_list(
RetainedGridTrackEntry::retained_size(unsafe { RetainedStyleValueData::from_retained_pointer(track_size) })
})
.collect();
- Arc::into_raw(Arc::new(StyleValueData::GridTrackSizeList {
- is_subgrid: false,
- preserve_line_name_sets: false,
- entries: RetainedGridTrackEntryList::from_retained_entries(entries),
- }))
+ StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::GridTrackSizeList(
+ StyleValueBox::new(GridTrackSizeListPayload {
+ is_subgrid: false,
+ preserve_line_name_sets: false,
+ entries: RetainedGridTrackEntryList::from_retained_entries(entries),
+ }),
+ )))
}
/// The track size of a grid track size list that holds just one track size, without line names, or null. The
/// returned value is borrowed from `data`.
#[unsafe(no_mangle)]
pub extern "C" fn rust_style_value_grid_track_size_list_single_size(data: &StyleValueData) -> *const StyleValueData {
- let StyleValueData::GridTrackSizeList {
- is_subgrid: false,
- entries,
- ..
- } = data
- else {
+ let StyleValueData::GridTrackSizeList(grid_track_size_list) = data else {
return std::ptr::null();
};
- match entries.as_slice() {
+ if grid_track_size_list.is_subgrid {
+ return std::ptr::null();
+ }
+ match grid_track_size_list.entries.as_slice() {
[entry] if entry.kind == GridTrackEntryKind::Size => entry.size_value.pointer(),
_ => std::ptr::null(),
}
@@ -3252,17 +4303,7 @@ pub extern "C" fn rust_style_value_grid_track_size_list_single_size(data: &Style
#[unsafe(no_mangle)]
pub extern "C" fn rust_style_value_create_guaranteed_invalid() -> *const StyleValueData {
- Arc::into_raw(Arc::new(StyleValueData::GuaranteedInvalid))
-}
-
-/// Takes ownership of one strong reference to the original shorthand value.
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_style_value_create_pending_substitution(
- original_shorthand_value: OwnedArc<StyleValueData>,
-) -> *const StyleValueData {
- Arc::into_raw(Arc::new(StyleValueData::PendingSubstitution {
- original_shorthand_value: RetainedStyleValueData::from_arc(original_shorthand_value.into_arc()),
- }))
+ StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::GuaranteedInvalid))
}
/// Takes ownership of one strong reference to the filter's value.
@@ -3270,9 +4311,9 @@ pub extern "C" fn rust_style_value_create_pending_substitution(
pub extern "C" fn rust_style_value_create_filter(
kind: u8,
color_operation: u8,
- value: OwnedArc<StyleValueData>,
+ value: OwnedStyleValue,
) -> *const StyleValueData {
- Arc::into_raw(Arc::new(StyleValueData::Filter {
+ StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::Filter {
kind,
color_operation,
value: RetainedStyleValueData::from_arc(value.into_arc()),
@@ -3285,7 +4326,7 @@ pub extern "C" fn rust_style_value_create_filter(
/// `custom_ident` must be zero or one leaked AK::Utf16FlyString reference.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_style_value_create_custom_ident(custom_ident: usize) -> *const StyleValueData {
- Arc::into_raw(Arc::new(StyleValueData::CustomIdent {
+ StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::CustomIdent {
custom_ident: unsafe { CssString::from_leaked_raw(custom_ident) },
}))
}
@@ -3294,21 +4335,23 @@ pub unsafe extern "C" fn rust_style_value_create_custom_ident(custom_ident: usiz
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_style_value_create_function(
name: usize,
- value: OwnedArc<StyleValueData>,
+ value: OwnedStyleValue,
) -> *const StyleValueData {
- Arc::into_raw(Arc::new(StyleValueData::Function {
- name: unsafe { CssString::from_leaked_raw(name) },
- value: RetainedStyleValueData::from_arc(value.into_arc()),
- }))
+ StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::Function(StyleValueBox::new(
+ FunctionPayload {
+ name: unsafe { CssString::from_leaked_raw(name) },
+ value: RetainedStyleValueData::from_arc(value.into_arc()),
+ },
+ ))))
}
/// Takes ownership of one strong reference to the angle value data if it is non-null.
#[unsafe(no_mangle)]
pub extern "C" fn rust_style_value_create_font_style(
font_style: u8,
- angle_value: OwnedArc<StyleValueData>,
+ angle_value: OwnedStyleValue,
) -> *const StyleValueData {
- Arc::into_raw(Arc::new(StyleValueData::FontStyle {
+ StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::FontStyle {
font_style,
angle_value: RetainedStyleValueData::from_optional_arc(angle_value.into_option()),
}))
@@ -3318,22 +4361,24 @@ pub extern "C" fn rust_style_value_create_font_style(
#[unsafe(no_mangle)]
pub extern "C" fn rust_style_value_create_shadow(
shadow_type: u8,
- color: OwnedArc<StyleValueData>,
- offset_x: OwnedArc<StyleValueData>,
- offset_y: OwnedArc<StyleValueData>,
- blur_radius: OwnedArc<StyleValueData>,
- spread_distance: OwnedArc<StyleValueData>,
+ color: OwnedStyleValue,
+ offset_x: OwnedStyleValue,
+ offset_y: OwnedStyleValue,
+ blur_radius: OwnedStyleValue,
+ spread_distance: OwnedStyleValue,
placement: u8,
) -> *const StyleValueData {
- Arc::into_raw(Arc::new(StyleValueData::Shadow {
- shadow_type,
- color: RetainedStyleValueData::from_optional_arc(color.into_option()),
- offset_x: RetainedStyleValueData::from_arc(offset_x.into_arc()),
- offset_y: RetainedStyleValueData::from_arc(offset_y.into_arc()),
- blur_radius: RetainedStyleValueData::from_optional_arc(blur_radius.into_option()),
- spread_distance: RetainedStyleValueData::from_optional_arc(spread_distance.into_option()),
- placement,
- }))
+ StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::Shadow(StyleValueBox::new(
+ ShadowPayload {
+ shadow_type,
+ color: RetainedStyleValueData::from_optional_arc(color.into_option()),
+ offset_x: RetainedStyleValueData::from_arc(offset_x.into_arc()),
+ offset_y: RetainedStyleValueData::from_arc(offset_y.into_arc()),
+ blur_radius: RetainedStyleValueData::from_optional_arc(blur_radius.into_option()),
+ spread_distance: RetainedStyleValueData::from_optional_arc(spread_distance.into_option()),
+ placement,
+ },
+ ))))
}
/// Takes ownership of one strong reference to each of the `length` values.
@@ -3344,7 +4389,7 @@ pub unsafe extern "C" fn rust_style_value_create_value_list(
separator: u8,
collapsible: bool,
) -> *const StyleValueData {
- Arc::into_raw(Arc::new(StyleValueData::ValueList {
+ StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::ValueList {
values: unsafe { RetainedStyleValueDataList::from_retained_pointers(values, length) },
separator,
collapsible,
@@ -3359,12 +4404,14 @@ pub unsafe extern "C" fn rust_style_value_create_transformation(
values: *const *const StyleValueData,
length: usize,
) -> *const StyleValueData {
- Arc::into_raw(Arc::new(StyleValueData::Transformation {
- property,
- transform_function,
- values: unsafe { RetainedStyleValueDataList::from_retained_pointers(values, length) },
- matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
- }))
+ StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::Transformation(StyleValueBox::new(
+ TransformationPayload {
+ property,
+ transform_function,
+ values: unsafe { RetainedStyleValueDataList::from_retained_pointers(values, length) },
+ matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
+ },
+ ))))
}
/// Takes ownership of one strong reference to each value; the property ids are copied.
@@ -3376,16 +4423,18 @@ pub unsafe extern "C" fn rust_style_value_create_shorthand(
values: *const *const StyleValueData,
value_count: usize,
) -> *const StyleValueData {
- Arc::into_raw(Arc::new(StyleValueData::Shorthand {
- shorthand_property,
- sub_properties: unsafe { RetainedPropertyIdList::from_raw(sub_properties, sub_property_count) },
- values: unsafe { RetainedStyleValueDataList::from_retained_pointers(values, value_count) },
- }))
+ StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::Shorthand(StyleValueBox::new(
+ ShorthandPayload {
+ shorthand_property,
+ sub_properties: unsafe { RetainedPropertyIdList::from_raw(sub_properties, sub_property_count) },
+ values: unsafe { RetainedStyleValueDataList::from_retained_pointers(values, value_count) },
+ },
+ ))))
}
#[unsafe(no_mangle)]
pub extern "C" fn rust_style_value_create_display(raw: u32) -> *const StyleValueData {
- Arc::into_raw(Arc::new(StyleValueData::Display { raw }))
+ StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::Display { raw }))
}
/// Creates an unresolved value from borrowed token source, deriving its source text according to
@@ -3428,22 +4477,22 @@ pub unsafe extern "C" fn rust_style_value_create_unresolved_from_source(
} else {
&source_text
};
- let components = RetainedComponentValueList::from_source(source_text);
- if presence_attr {
- crate::css::parser::arbitrary_substitution::note_attr_names_read_by(components.as_slice());
- }
- Arc::into_raw(Arc::new(StyleValueData::Unresolved {
- components,
- source_text: CssString::from_utf16(source_text),
- presence_attr,
- presence_dashed_function,
- presence_env,
- presence_if,
- presence_inherit,
- presence_var,
+ let presence = SubstitutionFunctionsPresence {
+ attr: presence_attr,
+ dashed_function: presence_dashed_function,
+ env: presence_env,
+ if_: presence_if,
+ inherit: presence_inherit,
+ var: presence_var,
+ };
+ let payload = UnresolvedBox::new(
+ TokenizerInput::Utf16(source_text),
+ UnresolvedValueComponents::OfText(&components),
+ presence,
contains_attr_tainted_values,
- parsed_value: unsafe { RetainedStyleValueData::from_retained_optional_pointer(parsed_value) },
- }))
+ unsafe { RetainedStyleValueData::from_retained_optional_pointer(parsed_value) },
+ );
+ StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::Unresolved(payload)))
}
/// Takes ownership of the definitions' retained strings and values.
@@ -3452,20 +4501,24 @@ pub unsafe extern "C" fn rust_style_value_create_counter_definitions(
definitions: *const FfiCounterDefinition,
length: usize,
) -> *const StyleValueData {
- Arc::into_raw(Arc::new(StyleValueData::CounterDefinitions {
- counter_definitions: unsafe { RetainedCounterDefinitionList::from_raw(definitions, length) },
- }))
+ StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::CounterDefinitions(
+ StyleValueBox::new(CounterDefinitionsPayload {
+ counter_definitions: unsafe { RetainedCounterDefinitionList::from_raw(definitions, length) },
+ }),
+ )))
}
/// A counter style reference by name. Takes ownership of one leaked reference to the name.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_style_value_create_counter_style(name: usize) -> *const StyleValueData {
- Arc::into_raw(Arc::new(StyleValueData::CounterStyle {
- is_symbols: false,
- name: unsafe { CssString::from_leaked_raw(name) },
- symbols_type: 0,
- symbols: CssStringList::from_strings(Vec::new()),
- }))
+ StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::CounterStyle(StyleValueBox::new(
+ CounterStylePayload {
+ is_symbols: false,
+ name: unsafe { CssString::from_leaked_raw(name) },
+ symbols_type: 0,
+ symbols: CssStringList::from_strings(Vec::new()),
+ },
+ ))))
}
/// Takes ownership of one strong reference to each non-null value and one leaked reference to
@@ -3475,28 +4528,30 @@ pub unsafe extern "C" fn rust_style_value_create_color_function(
has_color_type: bool,
color_type: u8,
color_syntax: u8,
- channel_0: OwnedArc<StyleValueData>,
- channel_1: OwnedArc<StyleValueData>,
- channel_2: OwnedArc<StyleValueData>,
- alpha: OwnedArc<StyleValueData>,
+ channel_0: OwnedStyleValue,
+ channel_1: OwnedStyleValue,
+ channel_2: OwnedStyleValue,
+ alpha: OwnedStyleValue,
has_name: bool,
name: usize,
- origin_color: OwnedArc<StyleValueData>,
+ origin_color: OwnedStyleValue,
) -> *const StyleValueData {
- Arc::into_raw(Arc::new(StyleValueData::ColorFunction {
- color_base: ColorBase {
- has_color_type,
- color_type,
- color_syntax,
+ StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::ColorFunction(StyleValueBox::new(
+ ColorFunctionPayload {
+ color_base: ColorBase {
+ has_color_type,
+ color_type,
+ color_syntax,
+ },
+ channel_0: RetainedStyleValueData::from_arc(channel_0.into_arc()),
+ channel_1: RetainedStyleValueData::from_arc(channel_1.into_arc()),
+ channel_2: RetainedStyleValueData::from_arc(channel_2.into_arc()),
+ alpha: RetainedStyleValueData::from_optional_arc(alpha.into_option()),
+ has_name,
+ name: unsafe { CssString::from_leaked_raw(name) },
+ origin_color: RetainedStyleValueData::from_optional_arc(origin_color.into_option()),
},
- channel_0: RetainedStyleValueData::from_arc(channel_0.into_arc()),
- channel_1: RetainedStyleValueData::from_arc(channel_1.into_arc()),
- channel_2: RetainedStyleValueData::from_arc(channel_2.into_arc()),
- alpha: RetainedStyleValueData::from_optional_arc(alpha.into_option()),
- has_name,
- name: unsafe { CssString::from_leaked_raw(name) },
- origin_color: RetainedStyleValueData::from_optional_arc(origin_color.into_option()),
- }))
+ ))))
}
/// Takes ownership of one strong reference to the calculation node; the byte blob and ranges
@@ -3513,16 +4568,18 @@ pub unsafe extern "C" fn rust_style_value_create_calculated(
accepted_ranges: *const RetainedNumericRangeByType,
accepted_range_count: usize,
) -> *const StyleValueData {
- Arc::into_raw(Arc::new(StyleValueData::Calculated {
- rust_calculation: unsafe { crate::css::calc::CalcNodeHandle::from_raw(rust_calculation) },
- resolve_as_is_number,
- resolve_as_base,
- resolved_type,
- has_percentages_resolve_as,
- percentages_resolve_as,
- resolve_numbers_as_integers,
- accepted_ranges: unsafe { RetainedNumericRangeList::from_raw(accepted_ranges, accepted_range_count) },
- }))
+ StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::Calculated(StyleValueBox::new(
+ CalculatedPayload {
+ rust_calculation: unsafe { crate::css::calc::CalcNodeHandle::from_raw(rust_calculation) },
+ resolve_as_is_number,
+ resolve_as_base,
+ resolved_type,
+ has_percentages_resolve_as,
+ percentages_resolve_as,
+ resolve_numbers_as_integers,
+ accepted_ranges: unsafe { RetainedNumericRangeList::from_raw(accepted_ranges, accepted_range_count) },
+ },
+ ))))
}
/// Copies the borrowed native URL text and takes ownership of each modifier string.
@@ -3535,25 +4592,27 @@ pub unsafe extern "C" fn rust_style_value_create_image(
resource_base_url: crate::css::ffi_support::FfiUtf16View,
has_resource_base_url: bool,
) -> *const StyleValueData {
- Arc::into_raw(Arc::new(StyleValueData::Image {
- url: RetainedString::from_units(url.units().expect("invalid URL text")),
- url_type,
- url_modifiers: unsafe { RetainedRequestUrlModifierList::from_raw(url_modifiers, url_modifier_count) },
- resource_context: ImageResourceContext {
- base_url: RetainedString::from_units(resource_base_url.units().expect("invalid base URL text")),
- has_base_url: has_resource_base_url,
- has_parent_style_sheet_origin_clean: false,
- parent_style_sheet_origin_clean: false,
- should_absolutize_url_for_computed_value: false,
+ StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::Image(StyleValueBox::new(
+ ImagePayload {
+ url: RetainedString::from_units(url.units().expect("invalid URL text")),
+ url_type,
+ url_modifiers: unsafe { RetainedRequestUrlModifierList::from_raw(url_modifiers, url_modifier_count) },
+ resource_context: ImageResourceContext {
+ base_url: RetainedString::from_units(resource_base_url.units().expect("invalid base URL text")),
+ has_base_url: has_resource_base_url,
+ has_parent_style_sheet_origin_clean: false,
+ parent_style_sheet_origin_clean: false,
+ should_absolutize_url_for_computed_value: false,
+ },
},
- }))
+ ))))
}
pub(crate) unsafe fn release_style_value(value: *const StyleValueData) {
if value.is_null() {
return;
}
- unsafe { Arc::decrement_strong_count(value) };
+ unsafe { StyleValueArc::decrement_strong_count(value) };
}
#[unsafe(no_mangle)]
@@ -3591,7 +4650,10 @@ fn style_values_equal(first: &StyleValueData, second: &StyleValueData) -> bool {
}
match (first, second) {
(
- StyleValueData::ColorFunction {
+ StyleValueData::ColorFunction(color_function_payload_1),
+ StyleValueData::ColorFunction(color_function_payload_2),
+ ) => {
+ let ColorFunctionPayload {
color_base: first_base,
channel_0: first_channel_0,
channel_1: first_channel_1,
@@ -3600,8 +4662,8 @@ fn style_values_equal(first: &StyleValueData, second: &StyleValueData) -> bool {
has_name: first_has_name,
name: first_name,
origin_color: first_origin_color,
- },
- StyleValueData::ColorFunction {
+ } = &**color_function_payload_1;
+ let ColorFunctionPayload {
color_base: second_base,
channel_0: second_channel_0,
channel_1: second_channel_1,
@@ -3610,8 +4672,7 @@ fn style_values_equal(first: &StyleValueData, second: &StyleValueData) -> bool {
has_name: second_has_name,
name: second_name,
origin_color: second_origin_color,
- },
- ) => {
+ } = &**color_function_payload_2;
first_base.has_color_type == second_base.has_color_type
&& (!first_base.has_color_type || first_base.color_type == second_base.color_type)
&& first_channel_0 == second_channel_0
@@ -3632,7 +4693,7 @@ fn style_values_equal(first: &StyleValueData, second: &StyleValueData) -> bool {
/// `value` must be null or point at a live `StyleValueData` allocated by this module.
pub(crate) unsafe fn retain_style_value(value: *const StyleValueData) -> *const StyleValueData {
if !value.is_null() {
- unsafe { Arc::increment_strong_count(value) };
+ unsafe { StyleValueArc::increment_strong_count(value) };
}
value
}
@@ -3680,11 +4741,23 @@ pub extern "C" fn rust_style_value_unscaled_by_zoom(value: &StyleValueData, zoom
mod substitution_clone_tests {
use super::*;
+ #[test]
+ fn pending_substitution_retains_its_shorthand_value() {
+ let written = StyleValueArc::new(StyleValueData::Number { value: 1.0 });
+ let pending = StyleValueArc::new(StyleValueData::PendingSubstitution {
+ original_shorthand: crate::css::property_metadata::property_id::BORDER,
+ original_shorthand_value: RetainedStyleValueData::from_arc(written.clone()),
+ });
+ assert_eq!(StyleValueArc::strong_count(&written), 2);
+ drop(pending);
+ assert_eq!(StyleValueArc::strong_count(&written), 1);
+ }
+
#[test]
fn shorthand_clone_preserves_repeated_child_aliases() {
- let child = Arc::new(StyleValueData::Keyword { keyword: 1 });
+ let child = StyleValueArc::new(StyleValueData::Keyword { keyword: 1 });
let properties = [1, 2];
- let children = [Arc::into_raw(child.clone()), Arc::into_raw(child)];
+ let children = [StyleValueArc::into_raw(child.clone()), StyleValueArc::into_raw(child)];
let shorthand = unsafe {
rust_style_value_create_shorthand(
3,
@@ -3694,17 +4767,18 @@ mod substitution_clone_tests {
children.len(),
)
};
- let cloned_shorthand = Arc::into_raw(Arc::new(unsafe { (*shorthand).clone() }));
+ let cloned_shorthand = StyleValueArc::into_raw(StyleValueArc::new(unsafe { (*shorthand).clone() }));
- let StyleValueData::Shorthand { values: original, .. } = (unsafe { &*shorthand }) else {
+ let StyleValueData::Shorthand(shorthand_payload) = (unsafe { &*shorthand }) else {
unreachable!()
};
- let StyleValueData::Shorthand {
- values: cloned_values, ..
- } = (unsafe { &*cloned_shorthand })
- else {
+ let ShorthandPayload { values: original, .. } = &**shorthand_payload;
+ let StyleValueData::Shorthand(shorthand_payload) = (unsafe { &*cloned_shorthand }) else {
unreachable!()
};
+ let ShorthandPayload {
+ values: cloned_values, ..
+ } = &**shorthand_payload;
assert_eq!(original.as_slice()[0].pointer(), original.as_slice()[1].pointer());
assert_eq!(
cloned_values.as_slice()[0].pointer(),
@@ -3757,7 +4831,7 @@ mod equality_tests {
fn unresolved(source: &str) -> StyleValueData {
let values = consume_a_list_of_component_values(tokenize_for_parser(source.as_bytes())).unwrap();
- let serialized = serialize_component_values_to_utf16(&values, ComponentSerializationMode::Normalized);
+ let serialized = serialize_component_values_to_utf16(&values, ComponentSerializationMode::Retokenize);
unresolved_value(&serialized, values, Default::default())
}
@@ -3783,15 +4857,15 @@ mod equality_tests {
}
fn retained_number(value: f64) -> RetainedStyleValueData {
- RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Number { value }))
+ RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Number { value }))
}
fn retained(value: StyleValueData) -> RetainedStyleValueData {
- RetainedStyleValueData::from_arc(Arc::new(value))
+ RetainedStyleValueData::from_arc(StyleValueArc::new(value))
}
fn color_function(color_syntax: u8) -> StyleValueData {
- StyleValueData::ColorFunction {
+ StyleValueData::ColorFunction(StyleValueBox::new(ColorFunctionPayload {
color_base: ColorBase {
has_color_type: true,
color_type: 0,
@@ -3804,7 +4878,7 @@ mod equality_tests {
has_name: false,
name: CssString::none(),
origin_color: RetainedStyleValueData::none(),
- }
+ }))
}
#[test]
@@ -3818,7 +4892,7 @@ mod equality_tests {
#[test]
fn color_equality_rejects_different_variants() {
let color = color_function(0);
- let light_dark = StyleValueData::LightDark {
+ let light_dark = StyleValueData::LightDark(StyleValueBox::new(LightDarkPayload {
color_base: ColorBase {
has_color_type: false,
color_type: 0,
@@ -3826,7 +4900,7 @@ mod equality_tests {
},
light: retained(color_function(0)),
dark: retained(color_function(0)),
- };
+ }));
assert!(!style_values_equal(&color, &light_dark));
assert!(!style_values_equal(&light_dark, &color));
}
@@ -3841,16 +4915,31 @@ pub(crate) fn value_depends_on_current_color(value: &StyleValueData) -> bool {
let list_depends = |values: &RetainedStyleValueDataList| values.as_slice().iter().any(retained_data_depends);
match value {
StyleValueData::Keyword { keyword } => *keyword == crate::css::style_compute::keyword::CURRENTCOLOR,
- StyleValueData::ColorFunction { origin_color, .. } => retained_data_depends(origin_color),
- StyleValueData::ColorMix { colors, .. } => colors.as_slice().iter().any(retained_data_depends),
+ StyleValueData::ColorFunction(color_function_payload) => {
+ let ColorFunctionPayload { origin_color, .. } = &**color_function_payload;
+ retained_data_depends(origin_color)
+ }
+ StyleValueData::ColorMix(color_mix_payload) => {
+ let ColorMixPayload { colors, .. } = &**color_mix_payload;
+ colors.as_slice().iter().any(retained_data_depends)
+ }
StyleValueData::ContrastColor { color, .. } => retained_data_depends(color),
- StyleValueData::LightDark { light, dark, .. } => retained_data_depends(light) || retained_data_depends(dark),
- StyleValueData::Shadow { color, .. } => retained_data_depends(color),
+ StyleValueData::LightDark(light_dark_payload) => {
+ let LightDarkPayload { light, dark, .. } = &**light_dark_payload;
+ retained_data_depends(light) || retained_data_depends(dark)
+ }
+ StyleValueData::Shadow(shadow_payload) => {
+ let ShadowPayload { color, .. } = &**shadow_payload;
+ retained_data_depends(color)
+ }
StyleValueData::Filter { value, .. } => retained_data_depends(value),
- StyleValueData::ScrollbarColor {
- thumb_color,
- track_color,
- } => retained_data_depends(thumb_color) || retained_data_depends(track_color),
+ StyleValueData::ScrollbarColor(scrollbar_color_payload) => {
+ let ScrollbarColorPayload {
+ thumb_color,
+ track_color,
+ } = &**scrollbar_color_payload;
+ retained_data_depends(thumb_color) || retained_data_depends(track_color)
+ }
StyleValueData::ValueList { values, .. } => list_depends(values),
_ => false,
}
@@ -3865,10 +4954,14 @@ pub(crate) fn value_depends_on_color_scheme(value: &StyleValueData) -> bool {
*keyword != crate::css::style_compute::keyword::CURRENTCOLOR
&& crate::css::style_compute::keyword_is_color(*keyword)
}
- StyleValueData::ColorFunction { origin_color, .. } => {
+ StyleValueData::ColorFunction(color_function_payload) => {
+ let ColorFunctionPayload { origin_color, .. } = &**color_function_payload;
origin_color.optional_data().is_some_and(value_depends_on_color_scheme)
}
- StyleValueData::ColorMix { colors, .. } => colors.as_slice().iter().any(retained_data_depends),
+ StyleValueData::ColorMix(color_mix_payload) => {
+ let ColorMixPayload { colors, .. } = &**color_mix_payload;
+ colors.as_slice().iter().any(retained_data_depends)
+ }
StyleValueData::ContrastColor { color, .. } => retained_data_depends(color),
StyleValueData::LightDark { .. } => true,
_ => false,
@@ -3891,14 +4984,6 @@ pub(crate) fn retained_value_depends_on_current_color(value: &RetainedStyleValue
style_value_dependency_flags(value.data()) & 1 != 0
}
-pub(crate) fn retained_value_depends_on_color_scheme(value: &RetainedStyleValueData) -> bool {
- style_value_dependency_flags(value.data()) & 2 != 0
-}
-
-pub(crate) fn retained_value_may_depend_on_font_metrics(value: &RetainedStyleValueData) -> bool {
- style_value_dependency_flags(value.data()) & 4 != 0
-}
-
#[unsafe(no_mangle)]
pub extern "C" fn rust_style_value_depends_on_current_color(data: &StyleValueData) -> bool {
value_depends_on_current_color(data)
diff --git a/Libraries/LibWeb/Rust/src/css/style_value_arc.rs b/Libraries/LibWeb/Rust/src/css/style_value_arc.rs
new file mode 100644
index 00000000000..af1e9c46014
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style_value_arc.rs
@@ -0,0 +1,273 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The one counted reference style values are shared through: the count in the word before the
+//! value, and no weak count, which nothing takes of a value. C++ holds the same pointer at the
+//! value and retains and releases it through the functions here.
+
+use crate::css::style_value::StyleValueData;
+use std::ptr::NonNull;
+use std::sync::atomic::{AtomicUsize, Ordering, fence};
+
+#[repr(C)]
+struct StyleValueAllocation {
+ references: AtomicUsize,
+ data: StyleValueData,
+}
+
+const _: () = assert!(size_of::<StyleValueAllocation>() == 24);
+
+/// One counted reference to an immutable style value, pointing at the value with its count in the
+/// word before it.
+#[repr(transparent)]
+pub(crate) struct StyleValueArc {
+ pointer: NonNull<StyleValueData>,
+}
+
+const _: () = assert!(size_of::<StyleValueArc>() == 8);
+const _: () = assert!(size_of::<Option<StyleValueArc>>() == 8);
+
+// SAFETY: The value is immutable while shared, and its count is atomic.
+unsafe impl Send for StyleValueArc where StyleValueData: Send + Sync {}
+unsafe impl Sync for StyleValueArc where StyleValueData: Send + Sync {}
+
+/// The most references a value may have, beyond which counting aborts, as std's `Arc` does.
+const MAXIMUM_REFERENCES: usize = isize::MAX as usize;
+
+impl StyleValueArc {
+ const DATA_OFFSET: usize = std::mem::offset_of!(StyleValueAllocation, data);
+
+ pub(crate) fn new(data: StyleValueData) -> Self {
+ let allocation = Box::new(StyleValueAllocation {
+ references: AtomicUsize::new(1),
+ data,
+ });
+ let allocation = Box::into_raw(allocation);
+ // SAFETY: The allocation is live; its data field is a valid, non-null pointer.
+ Self {
+ pointer: unsafe { NonNull::new_unchecked(&raw mut (*allocation).data) },
+ }
+ }
+
+ fn allocation(pointer: *const StyleValueData) -> *mut StyleValueAllocation {
+ // SAFETY: Every pointer handed out points at the data field of a live allocation.
+ unsafe { pointer.cast::<u8>().sub(Self::DATA_OFFSET).cast_mut().cast() }
+ }
+
+ fn references(pointer: *const StyleValueData) -> &'static AtomicUsize {
+ // SAFETY: The count lives as long as some reference does, which the caller holds.
+ unsafe { &(*Self::allocation(pointer)).references }
+ }
+
+ pub(crate) fn as_ptr(this: &Self) -> *const StyleValueData {
+ this.pointer.as_ptr()
+ }
+
+ pub(crate) fn ptr_eq(first: &Self, second: &Self) -> bool {
+ first.pointer == second.pointer
+ }
+
+ /// Hands the reference over as a pointer at the value, which `from_raw` takes back.
+ pub(crate) fn into_raw(this: Self) -> *const StyleValueData {
+ let pointer = this.pointer.as_ptr();
+ std::mem::forget(this);
+ pointer
+ }
+
+ /// Takes back a reference `into_raw` handed over.
+ ///
+ /// # Safety
+ /// `pointer` must come from `into_raw`, or carry a reference `increment_strong_count` added.
+ pub(crate) unsafe fn from_raw(pointer: *const StyleValueData) -> Self {
+ Self {
+ // SAFETY: The pointer is non-null, as every value's is.
+ pointer: unsafe { NonNull::new_unchecked(pointer.cast_mut()) },
+ }
+ }
+
+ /// # Safety
+ /// `pointer` must point at a live value.
+ pub(crate) unsafe fn increment_strong_count(pointer: *const StyleValueData) {
+ let previous = Self::references(pointer).fetch_add(1, Ordering::Relaxed);
+ if previous > MAXIMUM_REFERENCES {
+ std::process::abort();
+ }
+ }
+
+ /// # Safety
+ /// `pointer` must point at a live value, one of whose references the caller gives up.
+ pub(crate) unsafe fn decrement_strong_count(pointer: *const StyleValueData) {
+ drop(unsafe { Self::from_raw(pointer) });
+ }
+
+ /// The value, moved out where this is its only reference, else cloned.
+ pub(crate) fn unwrap_or_clone(this: Self) -> StyleValueData {
+ if Self::is_unique(&this) {
+ return Self::into_inner(this).expect("no other reference can appear beside the only one");
+ }
+ (*this).clone()
+ }
+
+ /// The value, where this is its only reference.
+ pub(crate) fn into_inner(this: Self) -> Option<StyleValueData> {
+ let pointer = Self::into_raw(this);
+ if Self::references(pointer).fetch_sub(1, Ordering::Release) != 1 {
+ return None;
+ }
+ fence(Ordering::Acquire);
+ // SAFETY: This was the last reference, which owns the allocation `new` made.
+ let allocation = unsafe { Box::from_raw(Self::allocation(pointer)) };
+ Some(allocation.data)
+ }
+
+ /// Whether this is the only reference to the value.
+ pub(crate) fn is_unique(this: &Self) -> bool {
+ Self::references(this.pointer.as_ptr()).load(Ordering::Acquire) == 1
+ }
+
+ #[cfg(test)]
+ pub(crate) fn strong_count(this: &Self) -> usize {
+ Self::references(this.pointer.as_ptr()).load(Ordering::Relaxed)
+ }
+}
+
+impl Clone for StyleValueArc {
+ fn clone(&self) -> Self {
+ // SAFETY: This reference keeps the value alive.
+ unsafe { Self::increment_strong_count(self.pointer.as_ptr()) };
+ Self { pointer: self.pointer }
+ }
+}
+
+impl Drop for StyleValueArc {
+ fn drop(&mut self) {
+ if Self::references(self.pointer.as_ptr()).fetch_sub(1, Ordering::Release) != 1 {
+ return;
+ }
+ fence(Ordering::Acquire);
+ // SAFETY: The last reference frees the allocation `new` made.
+ drop(unsafe { Box::from_raw(Self::allocation(self.pointer.as_ptr())) });
+ }
+}
+
+impl std::ops::Deref for StyleValueArc {
+ type Target = StyleValueData;
+
+ fn deref(&self) -> &StyleValueData {
+ // SAFETY: The reference keeps the value alive.
+ unsafe { self.pointer.as_ref() }
+ }
+}
+
+impl AsRef<StyleValueData> for StyleValueArc {
+ fn as_ref(&self) -> &StyleValueData {
+ self
+ }
+}
+
+impl PartialEq for StyleValueArc {
+ fn eq(&self, other: &Self) -> bool {
+ Self::ptr_eq(self, other) || **self == **other
+ }
+}
+
+impl std::fmt::Debug for StyleValueArc {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter.write_str("StyleValueArc")
+ }
+}
+
+/// A reference C++ hands back through a pointer `StyleValueArc::into_raw()` gave it, or null.
+#[repr(transparent)]
+pub struct OwnedStyleValue {
+ pointer: *const StyleValueData,
+}
+
+impl OwnedStyleValue {
+ fn take(&mut self) -> Option<StyleValueArc> {
+ let pointer = std::mem::replace(&mut self.pointer, std::ptr::null());
+ // SAFETY: A non-null pointer carries a reference that is this handle's own.
+ (!pointer.is_null()).then(|| unsafe { StyleValueArc::from_raw(pointer) })
+ }
+
+ /// The reference, which must not be null.
+ pub(crate) fn into_arc(mut self) -> StyleValueArc {
+ self.take().expect("C++ hands over a live value")
+ }
+
+ /// The reference, or none where C++ handed over null.
+ pub(crate) fn into_option(mut self) -> Option<StyleValueArc> {
+ self.take()
+ }
+}
+
+impl Drop for OwnedStyleValue {
+ fn drop(&mut self) {
+ drop(self.take());
+ }
+}
+
+/// A value C++ lends through the pointer `StyleValueArc::into_raw()` gave it.
+#[repr(transparent)]
+pub struct StyleValueRef<'a> {
+ pointer: *const StyleValueData,
+ lent: std::marker::PhantomData<&'a StyleValueData>,
+}
+
+impl StyleValueRef<'_> {
+ /// A reference of Rust's own to the value.
+ pub(crate) fn to_arc(&self) -> StyleValueArc {
+ assert!(!self.pointer.is_null(), "C++ lends a live value");
+ // SAFETY: The value is live while it is lent.
+ unsafe {
+ StyleValueArc::increment_strong_count(self.pointer);
+ StyleValueArc::from_raw(self.pointer)
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::StyleValueArc;
+ use crate::css::style_value::{RatioPayload, RetainedStyleValueData, StyleValueBox, StyleValueData};
+
+ #[test]
+ fn unwrap_or_clone_clones_only_a_shared_value() {
+ let number = |value| RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Number { value }));
+ let ratio = StyleValueArc::new(StyleValueData::Ratio(StyleValueBox::new(RatioPayload {
+ numerator: number(1.0),
+ denominator: number(2.0),
+ })));
+ let payload_of = |data: &StyleValueData| match data {
+ StyleValueData::Ratio(payload) => std::ptr::from_ref::<RatioPayload>(payload),
+ _ => unreachable!(),
+ };
+ let payload = payload_of(&ratio);
+
+ let cloned = StyleValueArc::unwrap_or_clone(ratio.clone());
+ assert_ne!(payload_of(&cloned), payload);
+ assert_eq!(StyleValueArc::strong_count(&ratio), 1);
+
+ let moved_out = StyleValueArc::unwrap_or_clone(ratio);
+ assert_eq!(payload_of(&moved_out), payload);
+ }
+
+ #[test]
+ fn counts_references_through_raw_pointers() {
+ let value = StyleValueArc::new(StyleValueData::Number { value: 1.5 });
+ let raw = StyleValueArc::into_raw(value.clone());
+ assert_eq!(StyleValueArc::strong_count(&value), 2);
+ unsafe { StyleValueArc::increment_strong_count(raw) };
+ assert_eq!(StyleValueArc::strong_count(&value), 3);
+ unsafe { StyleValueArc::decrement_strong_count(raw) };
+ drop(unsafe { StyleValueArc::from_raw(raw) });
+ assert_eq!(StyleValueArc::strong_count(&value), 1);
+ let copy = StyleValueArc::new(StyleValueData::Number { value: 2.5 });
+ assert!(!StyleValueArc::ptr_eq(&value, &copy));
+ assert!(matches!(StyleValueArc::unwrap_or_clone(copy), StyleValueData::Number { value } if value == 2.5));
+ assert!(matches!(*value, StyleValueData::Number { value } if value == 1.5));
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/table_group_builder.rs b/Libraries/LibWeb/Rust/src/css/table_group_builder.rs
index 602aea37df9..023450efd6d 100644
--- a/Libraries/LibWeb/Rust/src/css/table_group_builder.rs
+++ b/Libraries/LibWeb/Rust/src/css/table_group_builder.rs
@@ -12,16 +12,21 @@
//! the table (with a sparse override span for effective values the table does
//! not hold, like the animated overlay), resolves the color and opacity
//! sidecars natively, and runs the existing group builders, so the sharing
-//! rules - adopt the parent's payload on equality, fall back to the immortal
+//! rules - adopt the parent's payload on equality, fall back to the process's
//! default payload - are exactly the ones the marshalled calls used.
+use crate::css::style::ViewLonghands;
+use crate::css::style_value::{
+ BorderRadiusPayload, CalculatedPayload, ColorSchemePayload, GridTemplateAreaPayload, GridTrackPlacementPayload,
+ GridTrackSizeListPayload, PositionPayload, RatioPayload, RectPayload, ScrollbarColorPayload, ShadowPayload,
+ TransformationPayload,
+};
use std::collections::HashMap;
use std::ffi::c_void;
use crate::css::animated_overlay::AnimatedOverlay;
use crate::css::calc::{resolve_calculated_flex_without_context, resolve_calculated_integer_without_context};
use crate::css::color_resolution::{ColorResolutionInput, PREFERRED_COLOR_SCHEME_DARK, Rgba, accent_color, to_color};
-use crate::css::computed_longhand_table::ComputedLonghandTable;
use crate::css::computed_value_types::{
AnchorValues, AnimationValues, BackgroundValues, BorderValues, ComputedClipEdge, ComputedColorOrAuto,
ComputedCursor, ComputedFilter, ComputedFilterOperation, ComputedGridArea, ComputedGridPlacement,
@@ -30,15 +35,16 @@ use crate::css::computed_value_types::{
ComputedOverflowClipMarginSide, ComputedPositionTryFallback, ComputedResolvedTransform, ComputedScrollbarColor,
ComputedShadow, ComputedSize, ComputedSizeKind, ComputedStyleValueHandle, ComputedSvgDash, ComputedSvgPaint,
ComputedTextIndent, ComputedTextUnderlineOffset, ComputedTextUnderlinePosition, ContentValues, EffectsValues,
- FontValues, GRID_NO_INDEX, GridValues, InheritedListValues, InheritedSVGValues, InheritedTextValues,
- InheritedUIValues, MaskValues, MiscResetValues, RetainedComputedCursorList, RetainedComputedFilterOperationList,
- RetainedComputedResolvedTransformList, RetainedComputedShadowList, RetainedComputedSvgDashList,
- RetainedGridAreaList, RetainedGridNameIndexList, RetainedGridTrackEntryList, RetainedPositionAreaList,
- RetainedPositionTryFallbackList, RetainedWillChangePropertyList, SVGResetValues, TransformValues,
+ FontValues, GRID_NO_INDEX, GridValues, InheritedListTableValues, InheritedSVGValues, InheritedTextValues,
+ InheritedUIValues, MaskValues, MiscInteractionValues, MiscLayoutValues, RetainedComputedCursorList,
+ RetainedComputedFilterOperationList, RetainedComputedResolvedTransformList, RetainedComputedShadowList,
+ RetainedComputedSvgDashList, RetainedGridAreaList, RetainedGridNameIndexList, RetainedGridTrackEntryList,
+ RetainedPositionAreaList, RetainedPositionTryFallbackList, RetainedWillChangePropertyList, SVGResetValues,
+ StyleColor, TransformValues,
};
use crate::css::computed_values::{
- GroupFieldKind, GroupPayloadRef, GroupValueEntry, MAX_GROUP_FIELD_COUNT, build_inherited_box_group,
- build_inherited_table_group, build_sizing_group, build_style_group, build_svg_reset_group_payload,
+ GroupFieldKind, GroupReads, GroupShares, GroupValueEntry, GroupValueLayout, GroupValues, LonghandID,
+ MAX_GROUP_FIELD_COUNT, build_sizing_group, build_style_group, build_svg_reset_group_payload,
group_field_descriptors, rust_build_alignment_group, rust_build_grid_group, rust_build_surround_group,
rust_build_text_reset_group,
};
@@ -48,46 +54,44 @@ use crate::css::property_metadata::property_id;
use crate::css::retained_fly_string::{RetainedUtf16FlyString, RetainedUtf16FlyStringList};
use crate::css::style_value::{GridTrackEntryKind, RetainedGridTrackEntry, RetainedStyleValueData, StyleValueData};
-/// Mirror of the C++ StyleGroupIndex numbering; ComputedValues.cpp
-/// static-asserts these values against the enum, and the entry point asserts
-/// the caller's group count.
+/// The style groups' indices, which `computed_value_types` exports to the host: the C++
+/// StyleGroupIndex numbering, which the host static-asserts these against.
pub(crate) mod group_index {
- pub const INHERITED_TABLE: usize = 0;
- pub const INHERITED_LIST: usize = 1;
- pub const INHERITED_UI: usize = 2;
- pub const INHERITED_SVG: usize = 3;
- pub const INHERITED_TEXT: usize = 4;
- pub const INHERITED_BOX: usize = 5;
- pub const FONT: usize = 6;
- pub const ANIMATION: usize = 7;
- pub const SVG_RESET: usize = 8;
- pub const GRID: usize = 9;
- pub const ANCHOR: usize = 10;
- pub const EFFECTS: usize = 11;
- pub const MASK: usize = 12;
- pub const TEXT_RESET: usize = 13;
- pub const CONTENT: usize = 14;
- pub const TRANSFORM: usize = 15;
- pub const BACKGROUND: usize = 16;
- pub const BORDER: usize = 17;
- pub const ALIGNMENT: usize = 18;
- pub const MISC_RESET: usize = 19;
- pub const SIZING: usize = 20;
- pub const SURROUND: usize = 21;
- pub const BOX: usize = 22;
- pub const COUNT: usize = 23;
+ pub const INHERITED_LIST_TABLE: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_INHERITED_LIST_TABLE;
+ pub const INHERITED_UI: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_INHERITED_UI;
+ pub const INHERITED_SVG: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_INHERITED_SVG;
+ pub const INHERITED_TEXT: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_INHERITED_TEXT;
+ pub const FONT: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_FONT;
+ pub const ANIMATION: usize = 5;
+ pub const SVG_RESET: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_SVG_RESET;
+ pub const GRID: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_GRID;
+ pub const ANCHOR: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_ANCHOR;
+ pub const EFFECTS: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_EFFECTS;
+ pub const MASK: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_MASK;
+ pub const TEXT_RESET: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_TEXT_RESET;
+ pub const CONTENT: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_CONTENT;
+ pub const TRANSFORM: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_TRANSFORM;
+ pub const BACKGROUND: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_BACKGROUND;
+ pub const BORDER: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_BORDER;
+ pub const ALIGNMENT: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_ALIGNMENT;
+ pub const MISC_LAYOUT: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_MISC_LAYOUT;
+ pub const MISC_INTERACTION: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_MISC_INTERACTION;
+ pub const SIZING: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_SIZING;
+ pub const SURROUND: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_SURROUND;
+ pub const BOX: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_BOX;
+ pub const COUNT: usize = 22;
}
/// What one table-driven group build reads beside the table: the color resolution input (whose current color is the
/// element's own resolved color), the used color-scheme, the animated overlay over the table, and platform font data.
-pub(crate) struct TableGroupBuildInputs<'a> {
+pub(crate) struct GroupBuildInputs<'a> {
pub color_input: &'a ColorResolutionInput<'a>,
/// The used color-scheme code (PreferredColorScheme underlying value).
pub used_color_scheme: u8,
- pub animated_overlay: Option<&'a AnimatedOverlay>,
/// The raw bits of the Display value before the box type transformation, which the table does not hold.
pub box_display_before_transformation_raw: u32,
pub font: Option<&'a FfiFontGroupBuildInputs>,
+ pub defaults: &'a crate::css::computed_values::DefaultGroups,
}
/// Platform font resources and derived facts supplied to the Rust-owned font
@@ -111,26 +115,103 @@ pub struct FfiFontGroupBuildInputs {
pub math_depth: i32,
}
-/// The longhand table joined with the effective-value overrides: exactly the
-/// values `ComputedStyleWorkingSet::property()` returns during a group build.
-struct EffectiveValues<'a> {
- table: &'a ComputedLonghandTable,
- animated_overlay: Option<&'a AnimatedOverlay>,
+/// Where a group build reads an element's computed longhand values from: exactly the values
+/// `ComputedStyleWorkingSet::property()` returns during a group build.
+pub(crate) enum LonghandSource<'a> {
+ /// An element's longhands, of a table or of a record, joined with their effective-value
+ /// overrides: the animated overlay where its values win, and the recorded
+ /// currentcolor-dependent specified values.
+ Longhands {
+ longhands: ViewLonghands<'a>,
+ animated_overlay: Option<&'a AnimatedOverlay>,
+ },
+ /// The element's computed values by group, before its groups are built.
+ Values {
+ values: &'a GroupValues<'a>,
+ /// Where known, the values the build may read, which its group's cache key covers: a read
+ /// of another value aborts.
+ reads: Option<&'a GroupReads>,
+ },
}
/// The gathered entries of one group, which has at most `MAX_GROUP_FIELD_COUNT` fields.
type GroupValueEntries<'a> = smallvec::SmallVec<[GroupValueEntry<'a>; MAX_GROUP_FIELD_COUNT]>;
-impl<'a> EffectiveValues<'a> {
+impl<'a> LonghandSource<'a> {
fn handle(&self, property_id: u16) -> &'a RetainedStyleValueData {
- self.table
- .effective_value_handle(self.animated_overlay, property_id, true)
- .0
+ match self {
+ Self::Longhands {
+ longhands,
+ animated_overlay,
+ } => longhands.effective_value(*animated_overlay, property_id),
+ Self::Values { values, reads } => {
+ // NB: A build reads the element's color to resolve `currentcolor`, which the key
+ // covers as the resolved current color.
+ if let Some(reads) = reads
+ && property_id != property_id::COLOR
+ && !GroupValueLayout::reads(reads, GroupValueLayout::get().place(LonghandID::new(property_id)))
+ {
+ eprintln!("a style group build reads longhand {property_id}, which its key does not cover");
+ std::process::abort();
+ }
+ values.effective_value(property_id)
+ }
+ }
}
fn value(&self, property_id: u16) -> Option<&'a StyleValueData> {
self.handle(property_id).optional_data()
}
+
+ fn animated_overlay(&self) -> Option<&'a AnimatedOverlay> {
+ match self {
+ Self::Longhands { animated_overlay, .. } => *animated_overlay,
+ Self::Values { .. } => None,
+ }
+ }
+
+ fn effective_zoom(&self) -> f32 {
+ match self {
+ Self::Longhands { longhands, .. } => longhands.effective_zoom(),
+ Self::Values { values, .. } => values.facts().effective_zoom(),
+ }
+ }
+
+ /// What a style holding these values holds as bits beside its groups.
+ pub(crate) fn style_bits(&self) -> crate::css::computed_value_types::StyleBits {
+ match self {
+ Self::Longhands { .. } => crate::css::computed_value_types::StyleBits::of_values(
+ |property| self.handle(property),
+ self.effective_zoom(),
+ ),
+ Self::Values { values, .. } => values.style_bits(),
+ }
+ }
+
+ fn display_before_box_type_transformation(&self) -> u32 {
+ match self {
+ Self::Longhands { longhands, .. } => longhands.display_before_box_type_transformation(),
+ Self::Values { values, .. } => values.facts().display_before_box_type_transformation(),
+ }
+ }
+
+ fn effective_color_scheme(&self) -> i16 {
+ match self {
+ Self::Longhands { longhands, .. } => longhands.effective_color_scheme(),
+ Self::Values { values, .. } => values.facts().effective_color_scheme(),
+ }
+ }
+
+ /// https://drafts.csswg.org/css-ui/#appearance-disabling-properties
+ /// Whether an author declaration disables the element's native appearance.
+ fn native_appearance_disabled(&self) -> bool {
+ match self {
+ Self::Longhands { longhands, .. } => {
+ longhands.dependency_flags() & crate::css::computed_longhand_table::NATIVE_APPEARANCE_DISABLED != 0
+ }
+ Self::Values { values, .. } => values.facts().native_appearance_disabled(),
+ }
+ }
}
/// The C++ Color::value() bit layout.
@@ -138,6 +219,67 @@ fn packed_color(color: Rgba) -> u32 {
(u32::from(color.a) << 24) | (u32::from(color.r) << 16) | (u32::from(color.g) << 8) | u32::from(color.b)
}
+/// The groups that hold plain `currentcolor` as a [`StyleColor`] wherever they hold a color, which
+/// depend on the element's color only through a value whose color is more than plain `currentcolor`.
+pub(crate) const GROUPS_HOLDING_CURRENT_COLOR_FOR_THEIR_READER: u32 = (1 << group_index::BORDER)
+ | (1 << group_index::MISC_LAYOUT)
+ | (1 << group_index::TEXT_RESET)
+ | (1 << group_index::BACKGROUND)
+ | (1 << group_index::SVG_RESET)
+ | (1 << group_index::INHERITED_UI)
+ | (1 << group_index::INHERITED_SVG)
+ | (1 << group_index::EFFECTS);
+
+/// Whether a group holds `property`'s value `data` as `currentcolor` for its reader to resolve,
+/// rather than resolving it against the element's color.
+pub(crate) fn group_holds_current_color_for_its_reader(property: u16, data: Option<&StyleValueData>) -> bool {
+ // A shadow without a color is `currentcolor` too, and a layer whose color reads no
+ // `currentcolor` reads nothing of the element's color.
+ if property == property_id::BOX_SHADOW {
+ return match data {
+ Some(StyleValueData::ValueList { values, .. }) => {
+ values.as_slice().iter().all(|layer| match layer.data() {
+ StyleValueData::Shadow(shadow) => match shadow.color.optional_data() {
+ None => true,
+ Some(StyleValueData::Keyword { keyword }) if *keyword == keyword::CURRENTCOLOR => true,
+ Some(color) => !crate::css::style_value::value_depends_on_current_color(color),
+ },
+ _ => false,
+ })
+ }
+ _ => false,
+ };
+ }
+ matches!(
+ property,
+ property_id::BORDER_TOP_COLOR
+ | property_id::BORDER_RIGHT_COLOR
+ | property_id::BORDER_BOTTOM_COLOR
+ | property_id::BORDER_LEFT_COLOR
+ | property_id::OUTLINE_COLOR
+ | property_id::COLUMN_RULE_COLOR
+ | property_id::TEXT_DECORATION_COLOR
+ | property_id::BACKGROUND_COLOR
+ | property_id::STOP_COLOR
+ | property_id::FLOOD_COLOR
+ | property_id::CARET_COLOR
+ | property_id::ACCENT_COLOR
+ | property_id::FILL
+ | property_id::STROKE
+ ) && matches!(data, Some(StyleValueData::Keyword { keyword }) if *keyword == keyword::CURRENTCOLOR)
+}
+
+/// 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> {
+ if let StyleValueData::Keyword { keyword: code } = data
+ && *code == keyword::CURRENTCOLOR
+ {
+ return Some(StyleColor::CURRENT_COLOR);
+ }
+ to_color(data, input).map(|color| StyleColor::rgba(packed_color(color)))
+}
+
/// The resolved color the C++ sidecar loops produced for one color-kind
/// field, or None when the value needs the C++ path.
fn resolved_color(input: &ColorResolutionInput, property: u16, data: &StyleValueData) -> Option<u32> {
@@ -147,11 +289,7 @@ fn resolved_color(input: &ColorResolutionInput, property: u16, data: &StyleValue
return input.current_color.map(packed_color);
}
if let StyleValueData::Keyword { keyword: code } = data {
- // An auto caret-color is the element's own color; an auto
- // accent-color is the system accent color for the used scheme.
- if property == property_id::CARET_COLOR && *code == keyword::AUTO {
- return input.current_color.map(packed_color);
- }
+ // An auto accent-color is the system accent color for the used scheme.
if property == property_id::ACCENT_COLOR && *code == keyword::AUTO {
return Some(packed_color(accent_color(
input.scheme == Some(PREFERRED_COLOR_SCHEME_DARK),
@@ -182,7 +320,7 @@ fn resolved_wrapped_number(data: &StyleValueData) -> Option<f64> {
/// color and number sidecars the descriptor kinds ask for.
fn gather_group_entries<'a>(
group_index: usize,
- values: &EffectiveValues<'a>,
+ values: &LonghandSource<'a>,
input: &ColorResolutionInput,
used_color_scheme: u8,
) -> Option<GroupValueEntries<'a>> {
@@ -200,7 +338,7 @@ fn gather_group_entries<'a>(
has_resolved_number: false,
};
match descriptor.kind {
- GroupFieldKind::Color | GroupFieldKind::ColorOrKeyword(_) => {
+ GroupFieldKind::Color | GroupFieldKind::HeldColor | GroupFieldKind::HeldColorOrKeyword(_) => {
if let Some(color) = resolved_color(input, descriptor.property_id, data) {
entry.resolved_color = color;
entry.has_resolved_color = true;
@@ -228,10 +366,10 @@ fn gather_group_entries<'a>(
/// gathering the entries from the table instead of a marshalled span.
fn build_generic_group(
group_index: usize,
- values: &EffectiveValues,
+ values: &LonghandSource,
input: &ColorResolutionInput,
used_color_scheme: u8,
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
) -> *const c_void {
let Some(entries) = gather_group_entries(group_index, values, input, used_color_scheme) else {
return std::ptr::null();
@@ -239,7 +377,7 @@ fn build_generic_group(
build_style_group(group_index, &entries, parent)
}
-fn build_surround_group(values: &EffectiveValues, parent: Option<GroupPayloadRef<'_>>) -> *const c_void {
+fn build_surround_group(values: &LonghandSource, parent: GroupShares<'_>) -> *const c_void {
let position_anchor = match values.value(property_id::POSITION_ANCHOR) {
Some(StyleValueData::CustomIdent { .. }) => Some(values.handle(property_id::POSITION_ANCHOR)),
_ => None,
@@ -263,7 +401,7 @@ fn build_surround_group(values: &EffectiveValues, parent: Option<GroupPayloadRef
)
}
-fn build_alignment_group(values: &EffectiveValues, parent: Option<GroupPayloadRef<'_>>) -> *const c_void {
+fn build_alignment_group(values: &LonghandSource, parent: GroupShares<'_>) -> *const c_void {
let number = |property: u16| required_number(values.value(property).expect("the table holds the flex factor"));
let flex_grow = number(property_id::FLEX_GROW);
let flex_shrink = number(property_id::FLEX_SHRINK);
@@ -290,18 +428,16 @@ fn build_alignment_group(values: &EffectiveValues, parent: Option<GroupPayloadRe
}
fn build_svg_reset_group(
- values: &EffectiveValues,
+ values: &LonghandSource,
input: &ColorResolutionInput,
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
) -> *const c_void {
let color = |property: u16| {
- packed_color(
- to_color(
- values.value(property).expect("the table holds the computed color"),
- input,
- )
- .expect("a computed SVG reset color resolves in the Rust color context"),
+ style_color(
+ values.value(property).expect("the table holds the computed color"),
+ input,
)
+ .expect("a computed SVG reset color resolves in the Rust color context")
};
let opacity = |property: u16| {
resolved_wrapped_number(values.value(property).expect("the table holds the computed opacity"))
@@ -512,17 +648,17 @@ fn build_grid_track_list(
}
fn build_grid_placement(data: &StyleValueData, arena: &mut GridGroupArena) -> Option<ComputedGridPlacement> {
- let StyleValueData::GridTrackPlacement {
+ let StyleValueData::GridTrackPlacement(grid_track_placement_payload) = data else {
+ return None;
+ };
+ let GridTrackPlacementPayload {
kind,
value,
has_name,
name,
implicit_start_name,
implicit_end_name,
- } = data
- else {
- return None;
- };
+ } = &**grid_track_placement_payload;
let mut result = ComputedGridPlacement {
kind: ComputedGridPlacementKind::Auto as u8,
has_line_number: false,
@@ -563,8 +699,8 @@ fn build_grid_placement(data: &StyleValueData, arena: &mut GridGroupArena) -> Op
/// Builds the grid group payload from the table's computed track lists,
/// template areas and placements, in the C++ marshalled build's interning
/// order so the arena layout stays deterministic.
-fn build_grid_group(values: &EffectiveValues, parent: Option<GroupPayloadRef<'_>>) -> *const c_void {
- // An all-initial grid shares the immortal default payload directly, with
+fn build_grid_group(values: &LonghandSource, parent: GroupShares<'_>) -> *const c_void {
+ // An all-initial grid shares the default payload directly, with
// its empty style value handles, exactly as the descriptor constraints
// used to. A value is initial by what it holds, so that equal tables build
// equal payloads.
@@ -593,11 +729,14 @@ fn build_grid_group(values: &EffectiveValues, parent: Option<GroupPayloadRef<'_>
let track_list = |arena: &mut GridGroupArena, property: u16| -> Option<ComputedGridTrackList> {
match values.value(property)? {
- StyleValueData::GridTrackSizeList {
- is_subgrid,
- preserve_line_name_sets,
- entries,
- } => build_grid_track_list(*is_subgrid, *preserve_line_name_sets, entries.as_slice(), arena),
+ StyleValueData::GridTrackSizeList(grid_track_size_list_payload) => {
+ let GridTrackSizeListPayload {
+ is_subgrid,
+ preserve_line_name_sets,
+ entries,
+ } = &**grid_track_size_list_payload;
+ build_grid_track_list(*is_subgrid, *preserve_line_name_sets, entries.as_slice(), arena)
+ }
_ => None,
}
};
@@ -614,10 +753,12 @@ fn build_grid_group(values: &EffectiveValues, parent: Option<GroupPayloadRef<'_>
return std::ptr::null();
};
- let Some(StyleValueData::GridTemplateArea { grid_areas, .. }) = values.value(property_id::GRID_TEMPLATE_AREAS)
+ let Some(StyleValueData::GridTemplateArea(grid_template_area_payload)) =
+ values.value(property_id::GRID_TEMPLATE_AREAS)
else {
return std::ptr::null();
};
+ let GridTemplateAreaPayload { grid_areas, .. } = &**grid_template_area_payload;
for area in grid_areas.as_slice() {
let [row_start, row_end, column_start, column_end] = area.grid_lines();
let name_index = arena.intern_borrowed(area.name());
@@ -807,7 +948,10 @@ fn transform_number(data: &StyleValueData) -> f64 {
fn value_contains_percentage(data: &StyleValueData) -> bool {
match data {
StyleValueData::Percentage { .. } => true,
- StyleValueData::Calculated { rust_calculation, .. } => rust_calculation.node().contains_percentage(),
+ StyleValueData::Calculated(calculated_payload) => {
+ let CalculatedPayload { rust_calculation, .. } = &**calculated_payload;
+ rust_calculation.node().contains_percentage()
+ }
_ => false,
}
}
@@ -1072,15 +1216,15 @@ pub extern "C" fn rust_transform_list_to_abstract_matrix(
.map(|function| function.data())
.chain(single_function)
{
- let StyleValueData::Transformation {
+ let StyleValueData::Transformation(transformation_payload) = function else {
+ return false;
+ };
+ let TransformationPayload {
transform_function,
values,
matrix_values,
..
- } = function
- else {
- return false;
- };
+ } = &**transformation_payload;
let values = if matrix_values.as_slice().is_empty() {
values.as_slice()
} else {
@@ -1155,15 +1299,15 @@ fn baked_matrix_entry(matrix: [f32; 16]) -> ComputedResolvedTransform {
fn lower_transformation(data: &StyleValueData) -> ComputedResolvedTransform {
use crate::css::serialize::transform_function as functions;
- let StyleValueData::Transformation {
+ let StyleValueData::Transformation(transformation_payload) = data else {
+ unreachable!("a computed transform function is a transformation value");
+ };
+ let TransformationPayload {
transform_function,
values,
matrix_values,
..
- } = data
- else {
- unreachable!("a computed transform function is a transformation value");
- };
+ } = &**transformation_payload;
let function = *transform_function;
let values = if matrix_values.as_slice().is_empty() {
values.as_slice()
@@ -1231,10 +1375,10 @@ fn lower_transformation(data: &StyleValueData) -> ComputedResolvedTransform {
/// Builds the complete transform payload in Rust, including paint-ready
/// matrices and retained computed-value handles.
fn build_transform_group(
- values: &EffectiveValues,
+ values: &LonghandSource,
input: &ColorResolutionInput,
used_color_scheme: u8,
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
) -> *const c_void {
let Some(entries) = gather_group_entries(group_index::TRANSFORM, values, input, used_color_scheme) else {
return std::ptr::null();
@@ -1292,9 +1436,10 @@ fn build_transform_group(
None => (false, 0),
};
- let Some(StyleValueData::Position { edge_x, edge_y }) = values.value(property_id::PERSPECTIVE_ORIGIN) else {
+ let Some(StyleValueData::Position(position_payload)) = values.value(property_id::PERSPECTIVE_ORIGIN) else {
unreachable!("computed perspective-origin is a position value");
};
+ let PositionPayload { edge_x, edge_y } = &**position_payload;
let position_offset = |edge: &crate::css::style_value::RetainedStyleValueData| {
let StyleValueData::Edge { offset, .. } = edge.data() else {
unreachable!("computed position component is an edge value");
@@ -1337,13 +1482,7 @@ fn build_transform_group(
/// The shared prefix of every color style value variant.
fn color_base_of(data: &StyleValueData) -> Option<&crate::css::style_value::ColorBase> {
- match data {
- StyleValueData::ColorFunction { color_base, .. }
- | StyleValueData::ColorMix { color_base, .. }
- | StyleValueData::LightDark { color_base, .. }
- | StyleValueData::ContrastColor { color_base, .. } => Some(color_base),
- _ => None,
- }
+ data.color_base()
}
/// The C++ shadow color-syntax classification: non-color values are legacy,
@@ -1370,7 +1509,7 @@ fn shadow_color_syntax(color: Option<&StyleValueData>) -> u8 {
/// Returns the operations plus the retained list handle; a value that is not
/// a filter list lowers to none, as the C++ extractor did.
fn lower_filter_operations(
- values: &EffectiveValues,
+ values: &LonghandSource,
property: u16,
input: &ColorResolutionInput,
) -> (Vec<ComputedFilterOperation>, ComputedStyleValueHandle) {
@@ -1435,16 +1574,16 @@ fn lower_filter_operations(
});
}
FILTER_KIND_DROP_SHADOW => {
- let StyleValueData::Shadow {
+ let StyleValueData::Shadow(shadow_payload) = filter_value.data() else {
+ unreachable!("a computed drop-shadow filter holds a shadow value");
+ };
+ let ShadowPayload {
color,
offset_x,
offset_y,
blur_radius,
..
- } = filter_value.data()
- else {
- unreachable!("a computed drop-shadow filter holds a shadow value");
- };
+ } = &**shadow_payload;
let fallback = input.current_color.unwrap_or(Rgba {
r: 0,
g: 0,
@@ -1494,14 +1633,17 @@ fn lower_filter_operations(
)
}
-fn lower_shadow_layers(values: &EffectiveValues, property: u16, input: &ColorResolutionInput) -> Vec<ComputedShadow> {
+fn lower_shadow_layers(values: &LonghandSource, property: u16, input: &ColorResolutionInput) -> Vec<ComputedShadow> {
let Some(StyleValueData::ValueList { values: list, .. }) = values.value(property) else {
// A computed shadow list is the none keyword or a value list.
return Vec::new();
};
let mut shadows = Vec::with_capacity(list.as_slice().len());
for value in list.as_slice() {
- let StyleValueData::Shadow {
+ let StyleValueData::Shadow(shadow_payload) = value.data() else {
+ unreachable!("a computed box-shadow layer is a shadow value");
+ };
+ let ShadowPayload {
color,
offset_x,
offset_y,
@@ -1509,15 +1651,11 @@ fn lower_shadow_layers(values: &EffectiveValues, property: u16, input: &ColorRes
spread_distance,
placement,
..
- } = value.data()
- else {
- unreachable!("a computed box-shadow layer is a shadow value");
- };
- // A missing color is the element's own color, matching the
- // currentcolor default the C++ accessor materialized.
- let resolved_color = match color.optional_data() {
- Some(color) => to_color(color, input).expect("a computed shadow color resolves"),
- None => input.current_color.expect("the build input carries the element color"),
+ } = &**shadow_payload;
+ // A missing color is `currentcolor`, which the shadow's reader resolves.
+ let held_color = match color.optional_data() {
+ Some(color) => style_color(color, input).expect("a computed shadow color resolves"),
+ None => StyleColor::CURRENT_COLOR,
};
shadows.push(ComputedShadow {
offset_x: length_to_css_pixels(offset_x.data()).raw_value(),
@@ -1528,7 +1666,7 @@ fn lower_shadow_layers(values: &EffectiveValues, property: u16, input: &ColorRes
spread_distance: spread_distance
.optional_data()
.map_or(0, |spread| length_to_css_pixels(spread).raw_value()),
- color: packed_color(resolved_color),
+ color: held_color,
color_syntax: shadow_color_syntax(color.optional_data()),
placement: u32::from(*placement),
});
@@ -1560,10 +1698,10 @@ fn lower_clip_edge(data: &StyleValueData) -> ComputedClipEdge {
/// Builds the complete effects payload in Rust.
fn build_effects_group(
- values: &EffectiveValues,
+ values: &LonghandSource,
input: &ColorResolutionInput,
used_color_scheme: u8,
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
) -> *const c_void {
let Some(entries) = gather_group_entries(group_index::EFFECTS, values, input, used_color_scheme) else {
return std::ptr::null();
@@ -1579,20 +1717,23 @@ fn build_effects_group(
unit: crate::css::style_compute::px_length_unit(),
};
let (clip_is_rect, clip_edges) = match values.value(property_id::CLIP) {
- Some(StyleValueData::Rect {
- top,
- right,
- bottom,
- left,
- }) => (
- true,
- [
- lower_clip_edge(top.data()),
- lower_clip_edge(right.data()),
- lower_clip_edge(bottom.data()),
- lower_clip_edge(left.data()),
- ],
- ),
+ Some(StyleValueData::Rect(rect_payload)) => {
+ let RectPayload {
+ top,
+ right,
+ bottom,
+ left,
+ } = &**rect_payload;
+ (
+ true,
+ [
+ lower_clip_edge(top.data()),
+ lower_clip_edge(right.data()),
+ lower_clip_edge(bottom.data()),
+ lower_clip_edge(left.data()),
+ ],
+ )
+ }
_ => (false, [auto_edge(), auto_edge(), auto_edge(), auto_edge()]),
};
@@ -1637,7 +1778,7 @@ fn build_effects_group(
/// The comma-separated computed items of a repeatable-list property: the
/// list's elements, or the single value itself.
-fn repeatable_items<'a>(values: &EffectiveValues<'a>, property: u16) -> Vec<&'a RetainedStyleValueData> {
+fn repeatable_items<'a>(values: &LonghandSource<'a>, property: u16) -> Vec<&'a RetainedStyleValueData> {
match values.value(property) {
Some(StyleValueData::ValueList { values: list, .. }) => list.as_slice().iter().collect(),
_ => vec![values.handle(property)],
@@ -1652,35 +1793,34 @@ fn keyword_of(data: &StyleValueData) -> Option<u16> {
}
fn border_radius_is_initial(data: &StyleValueData) -> bool {
- let StyleValueData::BorderRadius {
+ let StyleValueData::BorderRadius(border_radius_payload) = data else {
+ return false;
+ };
+ let BorderRadiusPayload {
horizontal_radius,
vertical_radius,
..
- } = data
- else {
- return false;
- };
+ } = &**border_radius_payload;
let is_zero_px = |radius: &crate::css::style_value::RetainedStyleValueData| matches!(radius.data(), StyleValueData::Length { value, unit } if *value == 0.0 && *unit == crate::css::style_compute::px_length_unit());
is_zero_px(horizontal_radius) && is_zero_px(vertical_radius)
}
/// Builds the background group from retained canonical computed values.
fn build_background_group(
- values: &EffectiveValues,
+ values: &LonghandSource,
input: &ColorResolutionInput,
used_color_scheme: u8,
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
) -> *const c_void {
let Some(entries) = gather_group_entries(group_index::BACKGROUND, values, input, used_color_scheme) else {
return std::ptr::null();
};
let retained = |property| ComputedStyleValueHandle::from_retained(values.handle(property));
- let background_color = resolved_color(
- input,
- property_id::BACKGROUND_COLOR,
+ let background_color = style_color(
values
.value(property_id::BACKGROUND_COLOR)
.expect("background-color has a computed value"),
+ input,
)
.expect("a computed background-color resolves in Rust");
let image_items = repeatable_items(values, property_id::BACKGROUND_IMAGE);
@@ -1713,10 +1853,10 @@ fn build_background_group(
/// Builds the mask group from retained canonical computed values.
fn build_mask_group(
- values: &EffectiveValues,
+ values: &LonghandSource,
input: &ColorResolutionInput,
used_color_scheme: u8,
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
) -> *const c_void {
let Some(entries) = gather_group_entries(group_index::MASK, values, input, used_color_scheme) else {
return std::ptr::null();
@@ -1744,10 +1884,10 @@ fn build_mask_group(
/// Builds the border group from layout-facing side facts and retained
/// canonical values for the C++ presentation views.
fn build_border_group(
- values: &EffectiveValues,
+ values: &LonghandSource,
input: &ColorResolutionInput,
used_color_scheme: u8,
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
) -> *const c_void {
let generic = build_generic_group(group_index::BORDER, values, input, used_color_scheme, parent);
if !generic.is_null() {
@@ -1778,12 +1918,11 @@ fn build_border_group(
.expect("a computed border width has a value"),
);
crate::css::computed_value_types::ComputedBorderSide {
- color: resolved_color(
- input,
- color_property,
+ color: style_color(
values
.value(color_property)
.expect("a computed border color has a value"),
+ input,
)
.expect("a computed border color resolves in Rust"),
line_style,
@@ -1865,13 +2004,12 @@ fn build_border_group(
use crate::css::computed_value_types::{SVG_PAINT_COLOR, SVG_PAINT_NONE, SVG_PAINT_URL};
use crate::css::value_codes::*;
-fn lower_svg_paint(values: &EffectiveValues, property: u16, input: &ColorResolutionInput) -> ComputedSvgPaint {
+fn lower_svg_paint(values: &LonghandSource, property: u16, input: &ColorResolutionInput) -> ComputedSvgPaint {
let mut paint = ComputedSvgPaint {
kind: SVG_PAINT_NONE,
url: ComputedStyleValueHandle::empty(),
has_color: false,
- color: 0,
- color_is_currentcolor: false,
+ color: StyleColor::rgba(0),
};
let data = values.value(property).expect("the table holds the paint property");
match data {
@@ -1884,28 +2022,22 @@ fn lower_svg_paint(values: &EffectiveValues, property: u16, input: &ColorResolut
StyleValueData::EmptyOptional => paint,
StyleValueData::Keyword { keyword: code } if *code == keyword::NONE => paint,
fallback => {
- let color = to_color(fallback, input).expect("a computed SVG paint fallback is a color");
paint.has_color = true;
- paint.color = packed_color(color);
- paint.color_is_currentcolor =
- matches!(fallback, StyleValueData::Keyword { keyword: code } if *code == keyword::CURRENTCOLOR);
+ paint.color = style_color(fallback, input).expect("a computed SVG paint fallback is a color");
paint
}
}
}
_ => {
- let color = to_color(data, input).expect("a computed SVG paint is none, a color, or a URL paint");
paint.kind = SVG_PAINT_COLOR;
paint.has_color = true;
- paint.color = packed_color(color);
- paint.color_is_currentcolor =
- matches!(data, StyleValueData::Keyword { keyword: code } if *code == keyword::CURRENTCOLOR);
+ paint.color = style_color(data, input).expect("a computed SVG paint is none, a color, or a URL paint");
paint
}
}
}
-fn lower_svg_length_percentage_or_number(values: &EffectiveValues, property: u16) -> ComputedStyleValueHandle {
+fn lower_svg_length_percentage_or_number(values: &LonghandSource, property: u16) -> ComputedStyleValueHandle {
let data = values.value(property).expect("the table holds the property");
let number = match data {
StyleValueData::Number { value } => Some(*value),
@@ -1922,10 +2054,10 @@ fn lower_svg_length_percentage_or_number(values: &EffectiveValues, property: u16
/// Builds the complete inherited SVG payload in Rust.
fn build_inherited_svg_group(
- values: &EffectiveValues,
+ values: &LonghandSource,
input: &ColorResolutionInput,
used_color_scheme: u8,
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
) -> *const c_void {
let Some(entries) = gather_group_entries(group_index::INHERITED_SVG, values, input, used_color_scheme) else {
return std::ptr::null();
@@ -2025,33 +2157,50 @@ fn build_inherited_svg_group(
/// Builds the inherited list group from canonical values without leaving
/// Rust. Counter-style scope resolution remains a consumer-side operation.
-fn build_inherited_list_group(
- values: &EffectiveValues,
+fn build_inherited_list_table_group(
+ values: &LonghandSource,
input: &ColorResolutionInput,
used_color_scheme: u8,
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
) -> *const c_void {
- let generic = build_generic_group(group_index::INHERITED_LIST, values, input, used_color_scheme, parent);
+ let generic = build_generic_group(
+ group_index::INHERITED_LIST_TABLE,
+ values,
+ input,
+ used_color_scheme,
+ parent,
+ );
if !generic.is_null() {
return generic;
}
- let Some(entries) = gather_group_entries(group_index::INHERITED_LIST, values, input, used_color_scheme) else {
+ let Some(entries) = gather_group_entries(group_index::INHERITED_LIST_TABLE, values, input, used_color_scheme)
+ else {
return std::ptr::null();
};
crate::css::computed_values::build_group_payload_with_rust_fill(
- group_index::INHERITED_LIST,
+ group_index::INHERITED_LIST_TABLE,
&entries,
- |payload: &mut InheritedListValues| {
+ |payload: &mut InheritedListTableValues| {
let retained = |property| ComputedStyleValueHandle::from_retained(values.handle(property));
payload.list_style_type = retained(property_id::LIST_STYLE_TYPE);
- payload.list_style_position = values
- .value(property_id::LIST_STYLE_POSITION)
- .and_then(keyword_of)
- .and_then(crate::css::css_enums::keyword_to_list_style_position)
- .expect("a computed list-style-position maps to its enum");
payload.list_style_image = retained(property_id::LIST_STYLE_IMAGE);
payload.quotes = retained(property_id::QUOTES);
+ // NB: Computed border-spacing is a pair of absolute pixel lengths.
+ let spacing_component = |data: &StyleValueData| -> i32 {
+ match data {
+ StyleValueData::Length { value, unit } if *unit == crate::css::style_compute::px_length_unit() => {
+ crate::css::css_pixels::CssPixels::nearest_value_for(*value).raw_value()
+ }
+ _ => panic!("computed border-spacing component is not an absolute pixel length"),
+ }
+ };
+ let components = match values.value(property_id::BORDER_SPACING) {
+ Some(StyleValueData::ValueList { values, .. }) if values.as_slice().len() == 2 => values.as_slice(),
+ _ => panic!("computed border-spacing is not a pair"),
+ };
+ payload.border_spacing_horizontal = spacing_component(components[0].data());
+ payload.border_spacing_vertical = spacing_component(components[1].data());
},
parent,
)
@@ -2059,10 +2208,10 @@ fn build_inherited_list_group(
/// Builds the content group from its canonical values without leaving Rust.
fn build_content_group(
- values: &EffectiveValues,
+ values: &LonghandSource,
input: &ColorResolutionInput,
used_color_scheme: u8,
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
) -> *const c_void {
let generic = build_generic_group(group_index::CONTENT, values, input, used_color_scheme, parent);
if !generic.is_null() {
@@ -2090,27 +2239,35 @@ fn build_content_group(
/// Builds the complete inherited UI payload in Rust.
fn build_inherited_ui_group(
- values: &EffectiveValues,
+ values: &LonghandSource,
input: &ColorResolutionInput,
used_color_scheme: u8,
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
) -> *const c_void {
let Some(entries) = gather_group_entries(group_index::INHERITED_UI, values, input, used_color_scheme) else {
return std::ptr::null();
};
- let color_or_auto = |property: u16| -> ComputedColorOrAuto {
+ // An auto caret-color is the element's own color, which its reader resolves like
+ // `currentcolor`; an auto accent-color is the system accent color for the used scheme.
+ let color_or_auto = |property: u16, auto: StyleColor| -> ComputedColorOrAuto {
let data = values.value(property).expect("the table holds the color property");
let is_auto = matches!(data, StyleValueData::Keyword { keyword: code } if *code == keyword::AUTO);
- let used_color = resolved_color(input, property, data).expect("computed UI colors are resolvable in Rust");
ComputedColorOrAuto {
is_auto,
- computed_color: used_color,
- used_color,
+ color: match is_auto {
+ true => auto,
+ false => style_color(data, input).expect("computed UI colors are resolvable in Rust"),
+ },
}
};
- let caret_color = color_or_auto(property_id::CARET_COLOR);
- let accent_color = color_or_auto(property_id::ACCENT_COLOR);
+ let caret_color = color_or_auto(property_id::CARET_COLOR, StyleColor::CURRENT_COLOR);
+ let accent_color = color_or_auto(
+ property_id::ACCENT_COLOR,
+ StyleColor::rgba(packed_color(accent_color(
+ input.scheme == Some(PREFERRED_COLOR_SCHEME_DARK),
+ ))),
+ );
// The cursor list, with the extractor's rules: unmappable keywords are
// skipped, and an empty result is the predefined auto cursor.
@@ -2148,11 +2305,13 @@ fn build_inherited_ui_group(
});
}
- let scrollbar_color = if let Some(StyleValueData::ScrollbarColor {
- thumb_color,
- track_color,
- }) = values.value(property_id::SCROLLBAR_COLOR)
+ let scrollbar_color = if let Some(StyleValueData::ScrollbarColor(scrollbar_color_payload)) =
+ values.value(property_id::SCROLLBAR_COLOR)
{
+ let ScrollbarColorPayload {
+ thumb_color,
+ track_color,
+ } = &**scrollbar_color_payload;
ComputedScrollbarColor {
thumb_color: packed_color(
to_color(thumb_color.data(), input).expect("computed scrollbar colors are resolvable in Rust"),
@@ -2170,9 +2329,10 @@ fn build_inherited_ui_group(
}
};
- let Some(StyleValueData::ColorScheme { schemes, only, .. }) = values.value(property_id::COLOR_SCHEME) else {
+ let Some(StyleValueData::ColorScheme(color_scheme_payload)) = values.value(property_id::COLOR_SCHEME) else {
unreachable!("a computed color-scheme is a color-scheme value");
};
+ let ColorSchemePayload { schemes, only, .. } = &**color_scheme_payload;
let color_schemes = RetainedUtf16FlyStringList::from_retained_strings(
schemes.as_slice().iter().map(|name| name.to_fly_string()).collect(),
);
@@ -2216,10 +2376,10 @@ fn font_relative_length_to_css_pixels(data: &StyleValueData, input: &ColorResolu
/// Builds the complete inherited text payload in Rust.
fn build_inherited_text_group(
- values: &EffectiveValues,
+ values: &LonghandSource,
input: &ColorResolutionInput,
used_color_scheme: u8,
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
) -> *const c_void {
let Some(entries) = gather_group_entries(group_index::INHERITED_TEXT, values, input, used_color_scheme) else {
return std::ptr::null();
@@ -2311,28 +2471,24 @@ fn build_inherited_text_group(
)
}
-/// Builds the misc reset group entirely from Rust-owned canonical values.
-fn build_misc_reset_group(
- values: &EffectiveValues,
+/// Builds the misc layout group entirely from Rust-owned canonical values.
+fn build_misc_layout_group(
+ values: &LonghandSource,
input: &ColorResolutionInput,
used_color_scheme: u8,
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
) -> *const c_void {
- let implicit_will_change = values
- .animated_overlay
- .map_or(&[][..], |overlay| overlay.implicit_will_change.as_slice());
- let native_appearance_disabled =
- values.table.dependency_flags() & crate::css::computed_longhand_table::NATIVE_APPEARANCE_DISABLED != 0;
+ let native_appearance_disabled = values.native_appearance_disabled();
// NB: The generic builder only decodes property values, which leaves native_appearance_disabled at its default.
- if implicit_will_change.is_empty() && !native_appearance_disabled {
- let generic = build_generic_group(group_index::MISC_RESET, values, input, used_color_scheme, parent);
+ if !native_appearance_disabled {
+ let generic = build_generic_group(group_index::MISC_LAYOUT, values, input, used_color_scheme, parent);
if !generic.is_null() {
return generic;
}
}
- let Some(entries) = gather_group_entries(group_index::MISC_RESET, values, input, used_color_scheme) else {
+ let Some(entries) = gather_group_entries(group_index::MISC_LAYOUT, values, input, used_color_scheme) else {
return std::ptr::null();
};
@@ -2390,9 +2546,10 @@ fn build_misc_reset_group(
other => other,
};
- let Some(StyleValueData::Position { edge_x, edge_y }) = values.value(property_id::OBJECT_POSITION) else {
+ let Some(StyleValueData::Position(position_payload)) = values.value(property_id::OBJECT_POSITION) else {
unreachable!("a computed object-position is a position value");
};
+ let PositionPayload { edge_x, edge_y } = &**position_payload;
let position_offset = |edge: &crate::css::style_value::RetainedStyleValueData| -> ComputedStyleValueHandle {
let StyleValueData::Edge { offset, .. } = edge.data() else {
unreachable!("a computed position component is an edge value");
@@ -2400,6 +2557,70 @@ fn build_misc_reset_group(
ComputedStyleValueHandle::from_retained(offset)
};
+ let outline_offset_data = values
+ .value(property_id::OUTLINE_OFFSET)
+ .expect("the table holds outline-offset");
+ let Some(outline_offset) = resolve_length(outline_offset_data) else {
+ return std::ptr::null();
+ };
+ let group_color = |property| {
+ style_color(values.value(property).expect("the table holds the color"), input)
+ .expect("a computed color resolves in the Rust color context")
+ };
+ let outline_color = group_color(property_id::OUTLINE_COLOR);
+ let column_rule_color = group_color(property_id::COLUMN_RULE_COLOR);
+
+ crate::css::computed_values::build_group_payload_with_rust_fill(
+ group_index::MISC_LAYOUT,
+ &entries,
+ |payload: &mut MiscLayoutValues| {
+ let retained = |property| ComputedStyleValueHandle::from_retained(values.handle(property));
+ payload.outline_offset_style_value = retained(property_id::OUTLINE_OFFSET);
+ payload.outline_offset = outline_offset;
+ payload.overflow_clip_margin = ComputedOverflowClipMargin {
+ left: overflow_clip_margin_side(property_id::OVERFLOW_CLIP_MARGIN_LEFT),
+ top: overflow_clip_margin_side(property_id::OVERFLOW_CLIP_MARGIN_TOP),
+ right: overflow_clip_margin_side(property_id::OVERFLOW_CLIP_MARGIN_RIGHT),
+ bottom: overflow_clip_margin_side(property_id::OVERFLOW_CLIP_MARGIN_BOTTOM),
+ };
+ payload.appearance = normalized_appearance;
+ payload.computed_appearance = computed_appearance;
+ payload.native_appearance_disabled = native_appearance_disabled;
+ payload.column_height = ComputedSize::from_data(values.handle(property_id::COLUMN_HEIGHT));
+ payload.outline_color = outline_color;
+ payload.column_rule_color = column_rule_color;
+ payload.object_position_x = position_offset(edge_x);
+ payload.object_position_y = position_offset(edge_y);
+ payload.shape_margin = retained(property_id::SHAPE_MARGIN);
+ payload.shape_outside = retained(property_id::SHAPE_OUTSIDE);
+ },
+ parent,
+ )
+}
+
+/// Builds the misc interaction group entirely from Rust-owned canonical values.
+fn build_misc_interaction_group(
+ values: &LonghandSource,
+ input: &ColorResolutionInput,
+ used_color_scheme: u8,
+ parent: GroupShares<'_>,
+) -> *const c_void {
+ let implicit_will_change = values
+ .animated_overlay()
+ .map_or(&[][..], |overlay| overlay.implicit_will_change.as_slice());
+
+ // NB: The generic builder only decodes property values, which leaves implicit_will_change empty.
+ if implicit_will_change.is_empty() {
+ let generic = build_generic_group(group_index::MISC_INTERACTION, values, input, used_color_scheme, parent);
+ if !generic.is_null() {
+ return generic;
+ }
+ }
+
+ let Some(entries) = gather_group_entries(group_index::MISC_INTERACTION, values, input, used_color_scheme) else {
+ return std::ptr::null();
+ };
+
let Some(StyleValueData::ScrollbarGutter {
value: scrollbar_gutter,
}) = values.value(property_id::SCROLLBAR_GUTTER)
@@ -2453,29 +2674,11 @@ fn build_misc_reset_group(
None => unreachable!("the table holds scroll-snap-type"),
};
- let outline_offset_data = values
- .value(property_id::OUTLINE_OFFSET)
- .expect("the table holds outline-offset");
- let Some(outline_offset) = resolve_length(outline_offset_data) else {
- return std::ptr::null();
- };
- let outline_color = packed_color(
- to_color(
- values
- .value(property_id::OUTLINE_COLOR)
- .expect("the table holds outline-color"),
- input,
- )
- .expect("a computed outline-color resolves in the Rust color context"),
- );
-
crate::css::computed_values::build_group_payload_with_rust_fill(
- group_index::MISC_RESET,
+ group_index::MISC_INTERACTION,
&entries,
- |payload: &mut MiscResetValues| {
+ |payload: &mut MiscInteractionValues| {
let retained = |property| ComputedStyleValueHandle::from_retained(values.handle(property));
- payload.outline_offset_style_value = retained(property_id::OUTLINE_OFFSET);
- payload.outline_offset = outline_offset;
payload.scroll_margin = ComputedLengthBox::from_data(
values.handle(property_id::SCROLL_MARGIN_TOP),
values.handle(property_id::SCROLL_MARGIN_RIGHT),
@@ -2490,27 +2693,12 @@ fn build_misc_reset_group(
values.handle(property_id::SCROLL_PADDING_LEFT),
true,
);
- payload.overflow_clip_margin = ComputedOverflowClipMargin {
- left: overflow_clip_margin_side(property_id::OVERFLOW_CLIP_MARGIN_LEFT),
- top: overflow_clip_margin_side(property_id::OVERFLOW_CLIP_MARGIN_TOP),
- right: overflow_clip_margin_side(property_id::OVERFLOW_CLIP_MARGIN_RIGHT),
- bottom: overflow_clip_margin_side(property_id::OVERFLOW_CLIP_MARGIN_BOTTOM),
- };
- payload.appearance = normalized_appearance;
- payload.computed_appearance = computed_appearance;
- payload.native_appearance_disabled = native_appearance_disabled;
- payload.column_height = ComputedSize::from_data(values.handle(property_id::COLUMN_HEIGHT));
- payload.outline_color = outline_color;
- payload.object_position_x = position_offset(edge_x);
- payload.object_position_y = position_offset(edge_y);
payload.view_transition_name = retained(property_id::VIEW_TRANSITION_NAME);
payload.scroll_snap_align_block = scroll_snap_align_block;
payload.scroll_snap_align_inline = scroll_snap_align_inline;
payload.scroll_snap_axis = scroll_snap_axis;
payload.scroll_snap_strictness = scroll_snap_strictness;
payload.scrollbar_gutter = *scrollbar_gutter;
- payload.shape_margin = retained(property_id::SHAPE_MARGIN);
- payload.shape_outside = retained(property_id::SHAPE_OUTSIDE);
payload.will_change = retained(property_id::WILL_CHANGE);
payload.implicit_will_change = RetainedWillChangePropertyList::from_vec(implicit_will_change.to_vec());
},
@@ -2524,9 +2712,9 @@ const SEPARATOR_COMMA: u8 = 1;
/// Builds the complete text reset group in Rust.
fn build_text_reset_group(
- values: &EffectiveValues,
+ values: &LonghandSource,
input: &ColorResolutionInput,
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
) -> *const c_void {
let mut text_decoration_lines: Vec<u8> = Vec::new();
match values.value(property_id::TEXT_DECORATION_LINE) {
@@ -2577,15 +2765,13 @@ fn build_text_reset_group(
)
.and_then(crate::css::css_enums::keyword_to_text_decoration_style)
.expect("a computed text-decoration-style maps to its enum");
- let text_decoration_color = packed_color(
- to_color(
- values
- .value(property_id::TEXT_DECORATION_COLOR)
- .expect("the table holds text-decoration-color"),
- input,
- )
- .expect("a computed text-decoration-color resolves in the Rust color context"),
- );
+ let text_decoration_color = style_color(
+ values
+ .value(property_id::TEXT_DECORATION_COLOR)
+ .expect("the table holds text-decoration-color"),
+ input,
+ )
+ .expect("a computed text-decoration-color resolves in the Rust color context");
rust_build_text_reset_group(
group_index::TEXT_RESET,
@@ -2623,10 +2809,10 @@ fn position_area_codes(data: &StyleValueData) -> Vec<u8> {
/// Builds the complete anchor-positioning payload in Rust.
fn build_anchor_group(
- values: &EffectiveValues,
+ values: &LonghandSource,
input: &ColorResolutionInput,
used_color_scheme: u8,
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
) -> *const c_void {
let generic = build_generic_group(group_index::ANCHOR, values, input, used_color_scheme, parent);
if !generic.is_null() {
@@ -2795,7 +2981,7 @@ fn build_anchor_group(
}
/// The keyword code of a slot that must hold an enum keyword.
-fn required_keyword_code(values: &EffectiveValues, property: u16, map: fn(u16) -> Option<u8>) -> u8 {
+fn required_keyword_code(values: &LonghandSource, property: u16, map: fn(u16) -> Option<u8>) -> u8 {
values
.value(property)
.and_then(keyword_of)
@@ -2830,17 +3016,16 @@ fn required_number(data: &StyleValueData) -> f64 {
/// holds the transformed value; only the pre-transformation display is a
/// C++-side member and arrives through the build inputs.
fn build_box_group(
- values: &EffectiveValues,
+ values: &LonghandSource,
display_before_transformation_raw: u32,
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
) -> *const c_void {
use crate::css::computed_value_types::{
BoxValues, ComputedAspectRatio, ComputedContainIntrinsicSize, ComputedVerticalAlign,
};
use crate::css::css_enums::{
- keyword_to_baseline_source, keyword_to_box_sizing, keyword_to_clear, keyword_to_continue_value,
- keyword_to_field_sizing, keyword_to_float, keyword_to_overflow, keyword_to_positioning, keyword_to_resize,
- keyword_to_table_layout, keyword_to_text_overflow, keyword_to_unicode_bidi, keyword_to_vertical_align,
+ keyword_to_baseline_source, keyword_to_continue_value, keyword_to_field_sizing, keyword_to_resize,
+ keyword_to_text_overflow, keyword_to_vertical_align,
};
let display = match values.value(property_id::DISPLAY) {
@@ -2882,9 +3067,10 @@ fn build_box_group(
// aspect-ratio, with the extractor's degenerate-ratio handling; absent
// ratios keep zeroed components so payload equality stays field-wise.
let resolved_ratio = |data: &StyleValueData| -> (f64, f64) {
- let StyleValueData::Ratio { numerator, denominator } = data else {
+ let StyleValueData::Ratio(ratio_payload) = data else {
unreachable!("a computed aspect-ratio component is a ratio");
};
+ let RatioPayload { numerator, denominator } = &**ratio_payload;
(required_number(numerator.data()), required_number(denominator.data()))
};
let ratio_is_degenerate = |(numerator, denominator): (f64, f64)| {
@@ -3067,18 +3253,10 @@ fn build_box_group(
display_before_box_type_transformation: crate::css::display::FfiDisplay::from_raw(
display_before_transformation_raw,
),
- float_: required_keyword_code(values, property_id::FLOAT, keyword_to_float),
- clear: required_keyword_code(values, property_id::CLEAR, keyword_to_clear),
- position: required_keyword_code(values, property_id::POSITION, keyword_to_positioning),
- overflow_x: required_keyword_code(values, property_id::OVERFLOW_X, keyword_to_overflow),
- overflow_y: required_keyword_code(values, property_id::OVERFLOW_Y, keyword_to_overflow),
- box_sizing: required_keyword_code(values, property_id::BOX_SIZING, keyword_to_box_sizing),
field_sizing: required_keyword_code(values, property_id::FIELD_SIZING, keyword_to_field_sizing),
baseline_source: required_keyword_code(values, property_id::BASELINE_SOURCE, keyword_to_baseline_source),
resize: required_keyword_code(values, property_id::RESIZE, keyword_to_resize),
text_overflow: required_keyword_code(values, property_id::TEXT_OVERFLOW, keyword_to_text_overflow),
- unicode_bidi: required_keyword_code(values, property_id::UNICODE_BIDI, keyword_to_unicode_bidi),
- table_layout: required_keyword_code(values, property_id::TABLE_LAYOUT, keyword_to_table_layout),
grid_auto_flow_row: grid_auto_flow.0,
grid_auto_flow_dense: grid_auto_flow.1,
column_width: ComputedSize::from_data(values.handle(property_id::COLUMN_WIDTH)),
@@ -3112,9 +3290,9 @@ fn build_box_group(
/// Builds the inherited font group from canonical Rust longhands and the
/// platform font resources supplied by C++.
unsafe fn build_font_group(
- values: &EffectiveValues,
+ values: &LonghandSource,
inputs: &FfiFontGroupBuildInputs,
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
) -> *const c_void {
use crate::css::css_pixels::CssPixels;
@@ -3123,13 +3301,13 @@ unsafe fn build_font_group(
let retained = |property| ComputedStyleValueHandle::from_retained(values.handle(property));
let built = FontValues {
font_size: CssPixels::from_raw(inputs.font_size_raw),
- line_height_used: CssPixels::from_raw(inputs.line_height_used_raw),
+ resolved_line_height_used: CssPixels::from_raw(inputs.line_height_used_raw),
font_variant_emoji: inputs.font_variant_emoji,
- font_ascent: inputs.font_ascent,
- font_descent: inputs.font_descent,
- font_x_height: inputs.font_x_height,
- font_zero_advance: inputs.font_zero_advance,
- first_available_font: inputs.first_available_font,
+ resolved_font_ascent: inputs.font_ascent,
+ resolved_font_descent: inputs.font_descent,
+ resolved_font_x_height: inputs.font_x_height,
+ resolved_font_zero_advance: inputs.font_zero_advance,
+ resolved_first_available_font: inputs.first_available_font,
// SAFETY: The non-null check above and the caller's guarantee make the
// list live for the call; the handle keeps it live afterwards.
font_cascade_list: unsafe { libgfx_rust::font::FontCascadeListHandle::retain(inputs.font_cascade_list) },
@@ -3171,10 +3349,10 @@ unsafe fn build_font_group(
/// Builds the animation group from the canonical Rust longhand values.
fn build_animation_group(
- values: &EffectiveValues,
+ values: &LonghandSource,
input: &ColorResolutionInput,
used_color_scheme: u8,
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
) -> *const c_void {
let Some(entries) = gather_group_entries(group_index::ANIMATION, values, input, used_color_scheme) else {
return std::ptr::null();
@@ -3224,34 +3402,13 @@ fn build_animation_group(
)
}
-/// Rebuilds the font group from the table and the platform font inputs the engine resolved.
-///
-/// # Safety
-/// `table` must be a valid frozen table and `parent` a valid font payload or null.
-pub(crate) unsafe fn rebuild_font_group_from_table(
- table: &ComputedLonghandTable,
- inputs: &FfiFontGroupBuildInputs,
- parent: Option<GroupPayloadRef<'_>>,
-) -> Option<*const c_void> {
- let values = EffectiveValues {
- table,
- animated_overlay: None,
- };
- let payload = unsafe { build_font_group(&values, inputs, parent) };
- (!payload.is_null()).then_some(payload)
-}
-
-/// The element's own resolved color as the group builders consume it: the table's computed
-/// `color`, resolved against the initial color the way the C++ build seeds its context.
-pub(crate) fn own_color_from_table(
- table: &ComputedLonghandTable,
+/// The element's own resolved color as the group builders consume it: the computed `color` of
+/// `values`, resolved against the initial color the way the C++ build seeds its context.
+fn own_color_from_source(
+ values: &LonghandSource<'_>,
used_color_scheme: u8,
length: Option<&crate::css::style_compute::FfiLengthResolutionContext>,
) -> Option<u32> {
- let values = EffectiveValues {
- table,
- animated_overlay: None,
- };
let input = ColorResolutionInput {
scheme: Some(used_color_scheme),
current_color: Some(Rgba {
@@ -3267,105 +3424,106 @@ pub(crate) fn own_color_from_table(
to_color(values.value(property_id::COLOR)?, &input).map(packed_color)
}
-/// The used color scheme and the element's own resolved `color` a record assembled from a
-/// driven table builds its groups with. A drive always computes both; a table that somehow holds
-/// neither assembles against the browser's default light scheme and opaque black rather than
-/// publishing no record.
-pub(crate) fn assembly_color_inputs(
- table: &ComputedLonghandTable,
+/// The used color scheme and the element's own resolved `color`, as [`assembly_color_inputs`]
+/// answers them, from the values `values` holds.
+pub(crate) fn assembly_color_inputs_from_source(
+ values: &LonghandSource<'_>,
length: &crate::css::style_compute::FfiLengthResolutionContext,
) -> (u8, u32) {
- let used_color_scheme = u8::try_from(table.effective_color_scheme()).unwrap_or_else(|_| {
+ let used_color_scheme = u8::try_from(values.effective_color_scheme()).unwrap_or_else(|_| {
debug_assert!(false, "a driven table without a used color scheme");
crate::css::color_resolution::PREFERRED_COLOR_SCHEME_LIGHT
});
- let current_color = own_color_from_table(table, used_color_scheme, Some(length)).unwrap_or_else(|| {
+ let current_color = own_color_from_source(values, used_color_scheme, Some(length)).unwrap_or_else(|| {
debug_assert!(false, "a driven table whose color does not resolve");
0xff00_0000
});
(used_color_scheme, current_color)
}
-/// One group's payload for a record assembled from a driven table: the font group from the
-/// resolved font, which only a font group assembly needs, every other group from the table, the element's own color and its used color
-/// scheme. A driven table holds a value every builder encodes; a group whose builder declines one
-/// anyway publishes the group's defaults rather than no record.
+/// One group's payload for a record assembled as [`assemble_group_from_table`] does, but from the
+/// values `values` holds.
///
/// # Safety
-/// `table` must be a valid frozen table and `parent` a valid payload of the group or null.
-pub(crate) unsafe fn assemble_group_from_table(
- table: &ComputedLonghandTable,
+/// `parent` must be a valid payload of the group or null.
+pub(crate) unsafe fn assemble_group_from_source(
+ values: &LonghandSource<'_>,
group: usize,
font: Option<&FfiFontGroupBuildInputs>,
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
(used_color_scheme, current_color): (u8, u32),
length: &crate::css::style_compute::FfiLengthResolutionContext,
) -> *const c_void {
- let payload = unsafe {
- if group == group_index::FONT {
- font.and_then(|font| rebuild_font_group_from_table(table, font, parent))
- } else {
- rebuild_group_from_table(table, group, parent, current_color, used_color_scheme, Some(length))
- }
+ let payload = if group == group_index::FONT {
+ // SAFETY: The caller passes a valid parent payload or null.
+ font.map(|font| unsafe { build_font_group(values, font, parent) })
+ .filter(|payload| !payload.is_null())
+ } else {
+ rebuild_group_from_source(values, group, parent, current_color, used_color_scheme, Some(length))
};
payload.unwrap_or_else(|| {
debug_assert!(false, "style group {group} declined a driven table");
- crate::css::computed_values::default_group_payload(group)
+ parent.default_retained()
})
}
-/// Rebuilds one non-inherited group whose specified values read the newly
-/// inherited `color`. These groups need no DOM, layout, or font input.
-pub(crate) fn rebuild_group_for_inherited_current_color(
- table: &ComputedLonghandTable,
- group: usize,
- parent: Option<GroupPayloadRef<'_>>,
- current_color: u32,
- used_color_scheme: u8,
-) -> Option<*const c_void> {
- if !matches!(
- group,
- group_index::SVG_RESET
- | group_index::EFFECTS
- | group_index::TEXT_RESET
- | group_index::BACKGROUND
- | group_index::BORDER
- | group_index::MISC_RESET
- ) {
- return None;
+/// The engine: the background group `source` holds, but with the background color `values` holds,
+/// which is all an element whose other background longhands hold the values of `source`'s needs.
+/// The payload carries one reference for the caller.
+///
+/// # Safety
+/// `source` must be a live background group payload.
+pub(crate) unsafe fn patch_background_color(
+ values: &LonghandSource<'_>,
+ source: *const c_void,
+ parent: GroupShares<'_>,
+ (used_color_scheme, current_color): (u8, u32),
+ length: &crate::css::style_compute::FfiLengthResolutionContext,
+) -> *const c_void {
+ let input = ColorResolutionInput {
+ scheme: Some(used_color_scheme),
+ current_color: Some(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: values.value(property_id::COLOR),
+ length: Some(length),
+ channels: None,
+ };
+ let background_color = style_color(
+ values
+ .value(property_id::BACKGROUND_COLOR)
+ .expect("background-color has a computed value"),
+ &input,
+ )
+ .expect("a computed background-color resolves in Rust");
+ let style_value = ComputedStyleValueHandle::from_retained(values.handle(property_id::BACKGROUND_COLOR));
+ // SAFETY: The caller passes a live background group payload.
+ unsafe {
+ crate::css::computed_values::patch_group_payload(
+ group_index::BACKGROUND,
+ source,
+ |payload: &mut BackgroundValues| {
+ payload.background_color = background_color;
+ payload.background_color_style_value = style_value;
+ },
+ parent,
+ )
}
- rebuild_group_from_table(table, group, parent, current_color, used_color_scheme, None)
-}
-
-/// Rebuilds one of the groups whose payload is a function of the longhand table, the element's
-/// own `color` and its used color scheme alone. `parent` is the group's previous payload,
-/// returned retained when the rebuilt values equal it.
-pub(crate) fn rebuild_group_from_table(
- table: &ComputedLonghandTable,
- group: usize,
- parent: Option<GroupPayloadRef<'_>>,
- current_color: u32,
- used_color_scheme: u8,
- length: Option<&crate::css::style_compute::FfiLengthResolutionContext>,
-) -> Option<*const c_void> {
- rebuild_group_from_table_and_overlay(table, None, group, parent, current_color, used_color_scheme, length)
}
-/// Rebuilds one group as [`rebuild_group_from_table`] does, with the values `animated_overlay` samples over the table
-/// where they win over it.
-pub(crate) fn rebuild_group_from_table_and_overlay(
- table: &ComputedLonghandTable,
- animated_overlay: Option<&crate::css::animated_overlay::AnimatedOverlay>,
+/// Rebuilds one of the groups whose payload is a function of the element's computed longhand values, its own `color`
+/// and its used color scheme alone, reading the values from `values`.
+pub(crate) fn rebuild_group_from_source(
+ values: &LonghandSource<'_>,
group: usize,
- parent: Option<GroupPayloadRef<'_>>,
+ parent: GroupShares<'_>,
current_color: u32,
used_color_scheme: u8,
length: Option<&crate::css::style_compute::FfiLengthResolutionContext>,
) -> Option<*const c_void> {
- let values = EffectiveValues {
- table,
- animated_overlay,
- };
let input = ColorResolutionInput {
scheme: Some(used_color_scheme),
current_color: Some(Rgba {
@@ -3381,26 +3539,7 @@ pub(crate) fn rebuild_group_from_table_and_overlay(
let payload = match group {
// The font group needs platform font resources the table does not hold.
group_index::FONT => return None,
- group_index::BOX => build_box_group(&values, table.display_before_box_type_transformation(), parent),
- group_index::INHERITED_TABLE => build_inherited_table_group(
- group,
- values.handle(property_id::BORDER_COLLAPSE),
- values.handle(property_id::CAPTION_SIDE),
- values.handle(property_id::EMPTY_CELLS),
- values.handle(property_id::BORDER_SPACING),
- parent,
- ),
- group_index::INHERITED_BOX => build_inherited_box_group(
- group,
- values.handle(property_id::VISIBILITY),
- values.handle(property_id::DIRECTION),
- values.handle(property_id::WRITING_MODE),
- values.handle(property_id::CONTENT_VISIBILITY),
- values.handle(property_id::IMAGE_RENDERING),
- values.handle(property_id::TEXT_ORIENTATION),
- table.effective_zoom(),
- parent,
- ),
+ group_index::BOX => build_box_group(values, values.display_before_box_type_transformation(), parent),
group_index::SIZING => build_sizing_group(
group,
values.handle(property_id::WIDTH),
@@ -3411,45 +3550,43 @@ pub(crate) fn rebuild_group_from_table_and_overlay(
values.handle(property_id::MAX_HEIGHT),
parent,
),
- group_index::SURROUND => build_surround_group(&values, parent),
- group_index::ANIMATION => build_animation_group(&values, &input, used_color_scheme, parent),
- group_index::ANCHOR => build_anchor_group(&values, &input, used_color_scheme, parent),
- group_index::TEXT_RESET => build_text_reset_group(&values, &input, parent),
- group_index::ALIGNMENT => build_alignment_group(&values, parent),
- group_index::SVG_RESET => build_svg_reset_group(&values, &input, parent),
- group_index::GRID => build_grid_group(&values, parent),
- group_index::TRANSFORM => build_transform_group(&values, &input, used_color_scheme, parent),
- group_index::EFFECTS => build_effects_group(&values, &input, used_color_scheme, parent),
- group_index::INHERITED_UI => build_inherited_ui_group(&values, &input, used_color_scheme, parent),
- group_index::INHERITED_TEXT => build_inherited_text_group(&values, &input, used_color_scheme, parent),
- group_index::MISC_RESET => build_misc_reset_group(&values, &input, used_color_scheme, parent),
- group_index::INHERITED_SVG => build_inherited_svg_group(&values, &input, used_color_scheme, parent),
- group_index::INHERITED_LIST => build_inherited_list_group(&values, &input, used_color_scheme, parent),
- group_index::CONTENT => build_content_group(&values, &input, used_color_scheme, parent),
- group_index::MASK => build_mask_group(&values, &input, used_color_scheme, parent),
- group_index::BACKGROUND => build_background_group(&values, &input, used_color_scheme, parent),
- group_index::BORDER => build_border_group(&values, &input, used_color_scheme, parent),
+ group_index::SURROUND => build_surround_group(values, parent),
+ group_index::ANIMATION => build_animation_group(values, &input, used_color_scheme, parent),
+ group_index::ANCHOR => build_anchor_group(values, &input, used_color_scheme, parent),
+ group_index::TEXT_RESET => build_text_reset_group(values, &input, parent),
+ group_index::ALIGNMENT => build_alignment_group(values, parent),
+ group_index::SVG_RESET => build_svg_reset_group(values, &input, parent),
+ group_index::GRID => build_grid_group(values, parent),
+ group_index::TRANSFORM => build_transform_group(values, &input, used_color_scheme, parent),
+ group_index::EFFECTS => build_effects_group(values, &input, used_color_scheme, parent),
+ group_index::INHERITED_UI => build_inherited_ui_group(values, &input, used_color_scheme, parent),
+ group_index::INHERITED_TEXT => build_inherited_text_group(values, &input, used_color_scheme, parent),
+ group_index::MISC_LAYOUT => build_misc_layout_group(values, &input, used_color_scheme, parent),
+ group_index::MISC_INTERACTION => build_misc_interaction_group(values, &input, used_color_scheme, parent),
+ group_index::INHERITED_SVG => build_inherited_svg_group(values, &input, used_color_scheme, parent),
+ group_index::INHERITED_LIST_TABLE => {
+ build_inherited_list_table_group(values, &input, used_color_scheme, parent)
+ }
+ group_index::CONTENT => build_content_group(values, &input, used_color_scheme, parent),
+ group_index::MASK => build_mask_group(values, &input, used_color_scheme, parent),
+ group_index::BACKGROUND => build_background_group(values, &input, used_color_scheme, parent),
+ group_index::BORDER => build_border_group(values, &input, used_color_scheme, parent),
_ => return None,
};
(!payload.is_null()).then_some(payload)
}
-/// Builds every applied group's payload from the longhand table, writing one payload per applied group into `out`
-/// and null for every other group. Each payload carries one reference for the caller.
+/// Builds every applied group's payload from `values`, writing one payload per applied group into `out` and null for
+/// every other group. Each payload carries one reference for the caller.
///
/// # Safety
-/// `table` must be a valid frozen table holding the style's computed values, and the pointers `inputs` borrow must
-/// stay live across the call.
-pub(crate) unsafe fn build_group_payloads_from_table(
- table: &ComputedLonghandTable,
+/// The pointers `inputs` borrow must stay live across the call.
+pub(crate) unsafe fn build_group_payloads(
+ values: &LonghandSource<'_>,
groups_to_apply: u32,
- inputs: &TableGroupBuildInputs<'_>,
+ inputs: &GroupBuildInputs<'_>,
out: &mut [*const c_void; group_index::COUNT],
) {
- let values = EffectiveValues {
- table,
- animated_overlay: inputs.animated_overlay,
- };
let input = *inputs.color_input;
for (group, out_payload) in out.iter_mut().enumerate() {
@@ -3457,35 +3594,16 @@ pub(crate) unsafe fn build_group_payloads_from_table(
if (groups_to_apply >> group) & 1 == 0 {
continue;
}
- let parent = None;
+ let parent = GroupShares::new(inputs.defaults, group, None);
// SAFETY: Gathered pointers name live table or override data.
let payload = unsafe {
match group {
group_index::FONT => build_font_group(
- &values,
+ values,
inputs.font.expect("an applied font group has platform font inputs"),
parent,
),
- group_index::BOX => build_box_group(&values, inputs.box_display_before_transformation_raw, parent),
- group_index::INHERITED_TABLE => build_inherited_table_group(
- group,
- values.handle(property_id::BORDER_COLLAPSE),
- values.handle(property_id::CAPTION_SIDE),
- values.handle(property_id::EMPTY_CELLS),
- values.handle(property_id::BORDER_SPACING),
- parent,
- ),
- group_index::INHERITED_BOX => build_inherited_box_group(
- group,
- values.handle(property_id::VISIBILITY),
- values.handle(property_id::DIRECTION),
- values.handle(property_id::WRITING_MODE),
- values.handle(property_id::CONTENT_VISIBILITY),
- values.handle(property_id::IMAGE_RENDERING),
- values.handle(property_id::TEXT_ORIENTATION),
- table.effective_zoom(),
- parent,
- ),
+ group_index::BOX => build_box_group(values, inputs.box_display_before_transformation_raw, parent),
group_index::SIZING => build_sizing_group(
group,
values.handle(property_id::WIDTH),
@@ -3496,33 +3614,34 @@ pub(crate) unsafe fn build_group_payloads_from_table(
values.handle(property_id::MAX_HEIGHT),
parent,
),
- group_index::SURROUND => build_surround_group(&values, parent),
- group_index::ANIMATION => build_animation_group(&values, &input, inputs.used_color_scheme, parent),
- group_index::ANCHOR => build_anchor_group(&values, &input, inputs.used_color_scheme, parent),
- group_index::TEXT_RESET => build_text_reset_group(&values, &input, parent),
- group_index::ALIGNMENT => build_alignment_group(&values, parent),
- group_index::SVG_RESET => build_svg_reset_group(&values, &input, parent),
- group_index::GRID => build_grid_group(&values, parent),
- group_index::TRANSFORM => build_transform_group(&values, &input, inputs.used_color_scheme, parent),
- group_index::EFFECTS => build_effects_group(&values, &input, inputs.used_color_scheme, parent),
- group_index::INHERITED_UI => {
- build_inherited_ui_group(&values, &input, inputs.used_color_scheme, parent)
- }
+ group_index::SURROUND => build_surround_group(values, parent),
+ group_index::ANIMATION => build_animation_group(values, &input, inputs.used_color_scheme, parent),
+ group_index::ANCHOR => build_anchor_group(values, &input, inputs.used_color_scheme, parent),
+ group_index::TEXT_RESET => build_text_reset_group(values, &input, parent),
+ group_index::ALIGNMENT => build_alignment_group(values, parent),
+ group_index::SVG_RESET => build_svg_reset_group(values, &input, parent),
+ group_index::GRID => build_grid_group(values, parent),
+ group_index::TRANSFORM => build_transform_group(values, &input, inputs.used_color_scheme, parent),
+ group_index::EFFECTS => build_effects_group(values, &input, inputs.used_color_scheme, parent),
+ group_index::INHERITED_UI => build_inherited_ui_group(values, &input, inputs.used_color_scheme, parent),
group_index::INHERITED_TEXT => {
- build_inherited_text_group(&values, &input, inputs.used_color_scheme, parent)
+ build_inherited_text_group(values, &input, inputs.used_color_scheme, parent)
+ }
+ group_index::MISC_LAYOUT => build_misc_layout_group(values, &input, inputs.used_color_scheme, parent),
+ group_index::MISC_INTERACTION => {
+ build_misc_interaction_group(values, &input, inputs.used_color_scheme, parent)
}
- group_index::MISC_RESET => build_misc_reset_group(&values, &input, inputs.used_color_scheme, parent),
group_index::INHERITED_SVG => {
- build_inherited_svg_group(&values, &input, inputs.used_color_scheme, parent)
+ build_inherited_svg_group(values, &input, inputs.used_color_scheme, parent)
}
- group_index::INHERITED_LIST => {
- build_inherited_list_group(&values, &input, inputs.used_color_scheme, parent)
+ group_index::INHERITED_LIST_TABLE => {
+ build_inherited_list_table_group(values, &input, inputs.used_color_scheme, parent)
}
- group_index::CONTENT => build_content_group(&values, &input, inputs.used_color_scheme, parent),
- group_index::BACKGROUND => build_background_group(&values, &input, inputs.used_color_scheme, parent),
- group_index::MASK => build_mask_group(&values, &input, inputs.used_color_scheme, parent),
- group_index::BORDER => build_border_group(&values, &input, inputs.used_color_scheme, parent),
- _ => build_generic_group(group, &values, &input, inputs.used_color_scheme, parent),
+ group_index::CONTENT => build_content_group(values, &input, inputs.used_color_scheme, parent),
+ group_index::BACKGROUND => build_background_group(values, &input, inputs.used_color_scheme, parent),
+ group_index::MASK => build_mask_group(values, &input, inputs.used_color_scheme, parent),
+ group_index::BORDER => build_border_group(values, &input, inputs.used_color_scheme, parent),
+ _ => build_generic_group(group, values, &input, inputs.used_color_scheme, parent),
}
};
assert!(!payload.is_null(), "computed group build returned null");
@@ -3533,6 +3652,8 @@ pub(crate) unsafe fn build_group_payloads_from_table(
#[cfg(test)]
mod transform_angle_tests {
use super::*;
+ use crate::css::style_value::StyleValueBox;
+ use crate::css::style_value_arc::StyleValueArc;
fn literal(value: f64, unit: &str) -> StyleValueData {
StyleValueData::Angle {
@@ -3588,26 +3709,26 @@ mod transform_angle_tests {
fn canonical_arguments_and_serialization_survive_precise_matrix_inputs() {
let value = computed_transform("rotate(1e30turn)");
let transform = first_transform(&value);
- let StyleValueData::Transformation {
+ let StyleValueData::Transformation(transformation_payload) = transform else {
+ panic!("transform function");
+ };
+ let TransformationPayload {
property,
transform_function,
values,
matrix_values,
- } = transform
- else {
- panic!("transform function");
- };
+ } = &**transformation_payload;
assert!(!matrix_values.as_slice().is_empty());
assert!(
matches!(values.as_slice()[0].data(), StyleValueData::Angle { value, unit }
if *value == 1e30 * 360.0 && *unit as usize == angle_unit_index("deg"))
);
- let without_matrix_inputs = StyleValueData::Transformation {
+ let without_matrix_inputs = StyleValueData::Transformation(StyleValueBox::new(TransformationPayload {
property: *property,
transform_function: *transform_function,
values: values.clone(),
matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
- };
+ }));
assert_eq!(
crate::css::serialize::serialize_style_value_to_utf16(transform),
crate::css::serialize::serialize_style_value_to_utf16(&without_matrix_inputs)
@@ -3644,14 +3765,14 @@ mod transform_angle_tests {
#[test]
fn mapped_matrix_inputs_follow_axes_and_drop_replaced_angles() {
let value = computed_transform("rotate3d(0, 0, 1, 1e30turn)");
- let StyleValueData::Transformation {
- values, matrix_values, ..
- } = first_transform(&value)
- else {
+ let StyleValueData::Transformation(transformation_payload) = first_transform(&value) else {
panic!("transform function");
};
+ let TransformationPayload {
+ values, matrix_values, ..
+ } = &**transformation_payload;
let mut mapped = values.as_slice().to_vec();
- mapped[0] = RetainedStyleValueData::from_arc(std::sync::Arc::new(StyleValueData::Number { value: 1.0 }));
+ mapped[0] = RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Number { value: 1.0 }));
let retained =
crate::css::style_value::map_transform_matrix_values(values.as_slice(), &mapped, matrix_values.as_slice());
assert!(retained.as_slice()[0].data() == mapped[0].data());
@@ -3659,7 +3780,7 @@ mod transform_angle_tests {
matches!(retained.as_slice()[3].data(), StyleValueData::Angle { value, unit }
if *value == 1e30 && *unit as usize == angle_unit_index("turn"))
);
- mapped[3] = RetainedStyleValueData::from_arc(std::sync::Arc::new(literal(90.0, "deg")));
+ mapped[3] = RetainedStyleValueData::from_arc(StyleValueArc::new(literal(90.0, "deg")));
let retained =
crate::css::style_value::map_transform_matrix_values(values.as_slice(), &mapped, matrix_values.as_slice());
assert!(retained.as_slice().is_empty());
@@ -3699,7 +3820,7 @@ mod transform_angle_tests {
value: 450.0,
unit: angle_unit_index("deg") as u8,
}));
- let value = StyleValueData::Calculated {
+ let value = StyleValueData::Calculated(StyleValueBox::new(CalculatedPayload {
resolved_type: FfiNumericType::from_calc(node.numeric_type(&CalcNumericType::default())),
rust_calculation: CalcNodeHandle::from_arc(node),
resolve_as_is_number: false,
@@ -3708,7 +3829,7 @@ mod transform_angle_tests {
percentages_resolve_as: 0,
resolve_numbers_as_integers: false,
accepted_ranges: crate::css::style_value::RetainedNumericRangeList::empty(),
- };
+ }));
assert_eq!(angle_degrees(&value), Some(450.0));
assert!((transform_angle_radians(&value) - std::f64::consts::FRAC_PI_2).abs() < 1e-14);
assert_eq!(angle_degrees(&value), Some(450.0));
diff --git a/Libraries/LibWeb/Rust/src/css/thin_slice.rs b/Libraries/LibWeb/Rust/src/css/thin_slice.rs
new file mode 100644
index 00000000000..b533640ee27
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/thin_slice.rs
@@ -0,0 +1,218 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! A slice held by one pointer, with its length in the word before its first element, which takes
+//! no allocation when empty. It suits arrays that are written once and read many times, which need
+//! their count but no capacity.
+
+use std::alloc::{Layout, alloc, dealloc, handle_alloc_error, realloc};
+use std::ptr::NonNull;
+
+pub(crate) struct ThinSlice<T> {
+ /// The first element, after the length; dangling when empty.
+ pointer: NonNull<T>,
+}
+
+// SAFETY: The slice owns its elements as a `Box<[T]>` would.
+unsafe impl<T: Send> Send for ThinSlice<T> {}
+unsafe impl<T: Sync> Sync for ThinSlice<T> {}
+
+impl<T> ThinSlice<T> {
+ /// The bytes before the first element: the length, padded to the elements' alignment.
+ const HEADER: usize = {
+ assert!(align_of::<T>() <= align_of::<usize>());
+ size_of::<usize>()
+ };
+
+ fn layout(length: usize) -> Layout {
+ let bytes = length
+ .checked_mul(size_of::<T>())
+ .and_then(|bytes| bytes.checked_add(Self::HEADER))
+ .expect("thin slice too long");
+ Layout::from_size_align(bytes, align_of::<usize>()).expect("thin slice too long")
+ }
+
+ pub(crate) const fn new() -> Self {
+ Self {
+ pointer: NonNull::dangling(),
+ }
+ }
+
+ fn base(&self) -> *mut u8 {
+ // SAFETY: Only called on a non-empty slice, whose pointer follows the length.
+ unsafe { self.pointer.as_ptr().cast::<u8>().sub(Self::HEADER) }
+ }
+
+ pub(crate) fn len(&self) -> usize {
+ if self.pointer == NonNull::dangling() {
+ return 0;
+ }
+ // SAFETY: A non-empty slice's length is in the word before its first element.
+ unsafe { self.base().cast::<usize>().read() }
+ }
+
+ /// Resizes the allocation to hold `length` elements, keeping the first ones.
+ ///
+ /// # Safety
+ /// The elements beyond `length` must already have been moved out or dropped, and the ones
+ /// beyond the current length must be written before they are read.
+ unsafe fn resize(&mut self, length: usize) {
+ let old_length = self.len();
+ let base = if length == 0 {
+ if old_length != 0 {
+ unsafe { dealloc(self.base(), Self::layout(old_length)) };
+ }
+ self.pointer = NonNull::dangling();
+ return;
+ } else if old_length == 0 {
+ unsafe { alloc(Self::layout(length)) }
+ } else {
+ unsafe { realloc(self.base(), Self::layout(old_length), Self::layout(length).size()) }
+ };
+ if base.is_null() {
+ handle_alloc_error(Self::layout(length));
+ }
+ unsafe {
+ base.cast::<usize>().write(length);
+ self.pointer = NonNull::new_unchecked(base.add(Self::HEADER).cast::<T>());
+ }
+ }
+
+ pub(crate) fn push(&mut self, value: T) {
+ let length = self.len();
+ // SAFETY: The new last element is written at once.
+ unsafe {
+ self.resize(length + 1);
+ self.pointer.as_ptr().add(length).write(value);
+ }
+ }
+
+ pub(crate) fn remove(&mut self, index: usize) -> T {
+ let length = self.len();
+ assert!(index < length, "thin slice index out of bounds");
+ // SAFETY: The removed element is moved out and the ones after it moved down before the
+ // allocation shrinks.
+ unsafe {
+ let element = self.pointer.as_ptr().add(index);
+ let removed = element.read();
+ std::ptr::copy(element.add(1), element, length - index - 1);
+ self.resize(length - 1);
+ removed
+ }
+ }
+}
+
+impl<T> ThinSlice<T> {
+ /// The bytes of the allocation, with the length before the elements; none when empty.
+ pub(crate) fn heap_bytes(&self) -> usize {
+ match self.len() {
+ 0 => 0,
+ length => Self::layout(length).size(),
+ }
+ }
+
+ pub(crate) fn as_slice(&self) -> &[T] {
+ self
+ }
+}
+
+impl<'a, T> IntoIterator for &'a ThinSlice<T> {
+ type Item = &'a T;
+ type IntoIter = std::slice::Iter<'a, T>;
+
+ fn into_iter(self) -> Self::IntoIter {
+ self.iter()
+ }
+}
+
+impl<T> Default for ThinSlice<T> {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl<T> std::ops::Deref for ThinSlice<T> {
+ type Target = [T];
+
+ fn deref(&self) -> &[T] {
+ // SAFETY: The pointer is aligned and, when not dangling, points at `len()` elements.
+ unsafe { ak::slice_from_raw_parts(self.pointer.as_ptr(), self.len()) }
+ }
+}
+
+impl<T> std::ops::DerefMut for ThinSlice<T> {
+ fn deref_mut(&mut self) -> &mut [T] {
+ // SAFETY: As in `deref`, borrowed exclusively.
+ unsafe { ak::slice_from_raw_parts_mut(self.pointer.as_ptr(), self.len()) }
+ }
+}
+
+impl<T> FromIterator<T> for ThinSlice<T> {
+ fn from_iter<I: IntoIterator<Item = T>>(iterator: I) -> Self {
+ let values: Vec<T> = iterator.into_iter().collect();
+ let mut slice = Self::new();
+ // SAFETY: Each of the new elements is written at once, and the vector forgets them.
+ unsafe {
+ slice.resize(values.len());
+ let mut values = std::mem::ManuallyDrop::new(values);
+ std::ptr::copy_nonoverlapping(values.as_ptr(), slice.pointer.as_ptr(), values.len());
+ values.set_len(0);
+ std::mem::ManuallyDrop::drop(&mut values);
+ }
+ slice
+ }
+}
+
+impl<T: Clone> Clone for ThinSlice<T> {
+ fn clone(&self) -> Self {
+ self.iter().cloned().collect()
+ }
+}
+
+impl<T: PartialEq> PartialEq for ThinSlice<T> {
+ fn eq(&self, other: &Self) -> bool {
+ self.as_slice() == other.as_slice()
+ }
+}
+
+impl<T> Drop for ThinSlice<T> {
+ fn drop(&mut self) {
+ let length = self.len();
+ if length == 0 {
+ return;
+ }
+ // SAFETY: The slice owns its elements and the allocation they are in.
+ unsafe {
+ std::ptr::drop_in_place(std::ptr::slice_from_raw_parts_mut(self.pointer.as_ptr(), length));
+ dealloc(self.base(), Self::layout(length));
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::ThinSlice;
+
+ #[test]
+ fn grows_shrinks_and_drops_its_elements() {
+ let mut slice: ThinSlice<String> = ThinSlice::new();
+ assert!(slice.is_empty());
+ for index in 0..5 {
+ slice.push(index.to_string());
+ }
+ assert_eq!(&*slice, ["0", "1", "2", "3", "4"]);
+ assert_eq!(slice.remove(1), "1");
+ assert_eq!(&*slice, ["0", "2", "3", "4"]);
+ let copy = slice.clone();
+ while !slice.is_empty() {
+ slice.remove(0);
+ }
+ assert_eq!(copy.len(), 4);
+ let collected: ThinSlice<String> = copy.iter().rev().cloned().collect();
+ assert_eq!(&*collected, ["4", "3", "2", "0"]);
+ assert_eq!(size_of::<ThinSlice<String>>(), size_of::<usize>());
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/transition.rs b/Libraries/LibWeb/Rust/src/css/transition.rs
index 21f3c335884..32eba671c4b 100644
--- a/Libraries/LibWeb/Rust/src/css/transition.rs
+++ b/Libraries/LibWeb/Rust/src/css/transition.rs
@@ -346,17 +346,13 @@ fn value_is_current_color(value: *const StyleValueData) -> bool {
}
fn computed_value(
- table: &crate::css::computed_longhand_table::ComputedLonghandTable,
+ longhands: crate::css::style::ViewLonghands<'_>,
overlay: Option<&crate::css::animated_overlay::AnimatedOverlay>,
property_id: u16,
) -> *const StyleValueData {
- if let Some(entry) = overlay.and_then(|overlay| overlay.get(property_id))
- && crate::css::animated_overlay::overlay_wins(entry, table.is_important(property_id))
- {
- return entry.value_pointer();
- }
- table
- .get(property_id)
+ longhands
+ .overlay_value(overlay, property_id)
+ .or_else(|| longhands.handle(property_id))
.expect("a transition property must have a computed value")
.pointer()
}
@@ -370,8 +366,7 @@ pub(crate) fn records_compute_differently(
) -> bool {
let value = |record| {
let view = engine.style_record_view(record)?;
- let table = view.longhand_table?;
- Some(table.get(property_id)?.pointer())
+ Some(view.longhands().handle(property_id)?.pointer())
};
match (value(first), value(second)) {
(Some(first), Some(second)) => !values_equal(first, second),
@@ -379,31 +374,27 @@ pub(crate) fn records_compute_differently(
}
}
-fn originates_from_current_color(
- table: &crate::css::computed_longhand_table::ComputedLonghandTable,
- property_id: u16,
-) -> bool {
- let value = table
- .retained_inheritance_dependent_values()
- .find_map(|(property, value)| (property == property_id).then_some(value))
+fn originates_from_current_color(longhands: crate::css::style::ViewLonghands<'_>, property_id: u16) -> bool {
+ let value = longhands
+ .inheritance_dependent_value(property_id)
.filter(|value| crate::css::style_value::retained_value_depends_on_current_color(value))
- .or_else(|| table.get(property_id))
+ .or_else(|| longhands.handle(property_id))
.expect("a transition property must have a computed value");
crate::css::style_value::retained_value_depends_on_current_color(value)
}
fn prepare_transition_values(
before_style: (
- &crate::css::computed_longhand_table::ComputedLonghandTable,
+ crate::css::style::ViewLonghands<'_>,
Option<&crate::css::animated_overlay::AnimatedOverlay>,
),
- after_table: &crate::css::computed_longhand_table::ComputedLonghandTable,
+ after_longhands: crate::css::style::ViewLonghands<'_>,
after_overlay: Option<&crate::css::animated_overlay::AnimatedOverlay>,
inherited_animation: Option<crate::css::style::InheritedAnimatedValue<'_>>,
property: &mut TransitionProperty,
) -> Option<bool> {
- let (before_table, before_overlay) = before_style;
- property.before_change_value = computed_value(before_table, before_overlay, property.property_id);
+ let (before_longhands, before_overlay) = before_style;
+ property.before_change_value = computed_value(before_longhands, before_overlay, property.property_id);
if !property.has_matching_transition {
return Some(false);
}
@@ -422,17 +413,17 @@ fn prepare_transition_values(
property.after_change_value = entry.value_pointer();
let originates_from_current_color = value_is_current_color(entry.value_pointer());
if property.has_running_transition {
- property.current_value = computed_value(after_table, after_overlay, property.property_id);
+ property.current_value = computed_value(after_longhands, after_overlay, property.property_id);
}
return Some(originates_from_current_color);
} else if let Some(crate::css::style::InheritedAnimatedValue::BeneathTransitions(base_value)) = inherited_animation
{
property.after_change_value = std::ptr::from_ref(base_value);
} else {
- property.after_change_value = computed_value(after_table, None, property.property_id);
+ property.after_change_value = computed_value(after_longhands, None, property.property_id);
}
if property.has_running_transition {
- property.current_value = computed_value(after_table, after_overlay, property.property_id);
+ property.current_value = computed_value(after_longhands, after_overlay, property.property_id);
}
// NB: Whether the table values originate from currentColor matters only where they differ, which the caller
// knows once the before-change value is final.
@@ -443,8 +434,8 @@ fn prepare_transition_values(
/// changes from the record `before` to the record `after`, the record the target installed. The transitions resolve
/// their lengths against `after`.
pub(crate) struct TransitionDecision {
- pub(crate) before: u64,
- pub(crate) after: u64,
+ pub(crate) before: std::sync::Arc<crate::css::style::pipeline::Record>,
+ pub(crate) after: std::sync::Arc<crate::css::style::pipeline::Record>,
/// The target's style node, where the target is an element: only an element's own record inherits from its
/// inheritance parent.
pub(crate) element: Option<crate::css::style::tree::StyleNodeID>,
@@ -456,31 +447,26 @@ impl TransitionDecision {
/// in that order. The transitions resolve their transforms against `reference_box`, the transform reference box of
/// the box of the target's element, where it was laid out.
pub(crate) fn decide(
- self,
+ &self,
engine: &crate::css::style::StyleEngine,
reference_box: Option<crate::css::css_pixels::CssPixelRect>,
existing: &[FfiExistingTransition],
) -> Vec<FfiTransitionAction> {
- let Some(after_table) = engine
- .style_record_view(self.after)
- .and_then(|after| after.longhand_table)
- else {
- debug_assert!(false, "the records of a transition step carry longhand tables");
- return Vec::new();
- };
+ let after_longhands = crate::css::style::StyleRecordView::of_host_record(&self.after).longhands();
// A declaration whose delay and duration are each the single value 0s starts nothing, so it matters only to a
// target holding a transition it could cancel.
- if existing.is_empty() && crate::css::style_compute::transition_delay_and_duration_are_single_zero(after_table)
+ if existing.is_empty()
+ && crate::css::style_compute::transition_delay_and_duration_are_single_zero(after_longhands)
{
return Vec::new();
}
- let entries = crate::css::style_compute::transition_entries(after_table);
+ let entries = crate::css::style_compute::transition_entries(after_longhands);
self.decide_entries(engine, reference_box, &entries, existing)
}
/// As `decide`, for the after-change style's `entries`.
fn decide_entries(
- self,
+ &self,
engine: &crate::css::style::StyleEngine,
reference_box: Option<crate::css::css_pixels::CssPixelRect>,
entries: &[TransitionEntry],
@@ -492,7 +478,7 @@ impl TransitionDecision {
/// As `decide_entries`, with `after_overlay` in place of the after-change record's overlay where it is given: the
/// current values of the target's running transitions, which the record holds none of.
fn decide_over(
- self,
+ &self,
engine: &crate::css::style::StyleEngine,
reference_box: Option<crate::css::css_pixels::CssPixelRect>,
after_overlay: Option<&crate::css::animated_overlay::AnimatedOverlay>,
@@ -500,36 +486,25 @@ impl TransitionDecision {
existing: &[FfiExistingTransition],
ended: &[u16],
) -> Vec<FfiTransitionAction> {
- let Self { before, after, element } = self;
- let length_resolution_context = engine.transition_length_resolution_context(after);
- let (Some(before), Some(after)) = (engine.style_record_view(before), engine.style_record_view(after)) else {
- debug_assert!(false, "the records a transition step decides over remain live");
- return Vec::new();
- };
- let (Some(before_table), before_overlay, Some(after_table), record_after_overlay) = (
- before.longhand_table,
- before.animated_overlay,
- after.longhand_table,
- after.animated_overlay,
- ) else {
- debug_assert!(false, "the records of a transition step carry longhand tables");
- return Vec::new();
- };
- let after_overlay = after_overlay.or(record_after_overlay);
+ let element = self.element;
+ let length_resolution_context = engine.transition_length_resolution_context(&self.after);
+ let before = crate::css::style::StyleRecordView::of_host_record(&self.before);
+ let after = crate::css::style::StyleRecordView::of_host_record(&self.after);
+ let (before_longhands, before_overlay) = (before.longhands(), before.animated_overlay);
+ let after_longhands = after.longhands();
+ let after_overlay = after_overlay.or(after.animated_overlay);
let mut context = crate::css::animation::FfiAnimationContext {
allow_discrete: false,
// The value that matters is the one in the after-change style.
allow_keyword_size_interpolation: crate::css::animation::allows_keyword_size_interpolation(
- after_table,
+ after_longhands,
after_overlay,
),
current_color: Some(
- after_table
- .effective_value_handle(after_overlay, crate::css::property_metadata::property_id::COLOR, true)
- .0,
+ after_longhands.effective_value(after_overlay, crate::css::property_metadata::property_id::COLOR),
),
- has_length_resolution_context: length_resolution_context.is_some(),
- length_resolution_context: length_resolution_context.unwrap_or_default(),
+ has_length_resolution_context: true,
+ length_resolution_context,
has_transform_reference_box: false,
transform_reference_box_width: 0.0,
transform_reference_box_height: 0.0,
@@ -555,16 +530,16 @@ impl TransitionDecision {
let mut property = TransitionProperty::new(property_id, entry, existing);
let inherited_animation = element
.filter(|&element| {
- after_table.is_inherited(property_id)
+ after_longhands.is_inherited(property_id)
&& after_overlay
.and_then(|overlay| overlay.get(property_id))
.is_none_or(|entry| !entry.inherited)
&& inherits_animated_values(element)
})
- .and_then(|element| engine.inherited_animated_value(element, after_table, property_id));
+ .and_then(|element| engine.inherited_animated_value(element, after_longhands, property_id));
let overlay_values_originate_from_current_color = prepare_transition_values(
- (before_table, before_overlay),
- after_table,
+ (before_longhands, before_overlay),
+ after_longhands,
after_overlay,
inherited_animation,
&mut property,
@@ -574,10 +549,10 @@ impl TransitionDecision {
if ended.contains(&property_id)
&& std::ptr::eq(
property.before_change_value,
- computed_value(before_table, before_overlay, property_id),
+ computed_value(before_longhands, before_overlay, property_id),
)
{
- property.before_change_value = computed_value(before_table, None, property_id);
+ property.before_change_value = computed_value(before_longhands, None, property_id);
}
// OPTIMIZATION: The values originating from currentColor only matters where they differ, and finding out
// reads both tables. A shared value differs from nothing; values compared equal leave the
@@ -585,8 +560,8 @@ impl TransitionDecision {
let values_originate_from_current_color =
overlay_values_originate_from_current_color.unwrap_or_else(|| {
!std::ptr::eq(property.before_change_value, property.after_change_value)
- && originates_from_current_color(before_table, property_id)
- && originates_from_current_color(after_table, property_id)
+ && originates_from_current_color(before_longhands, property_id)
+ && originates_from_current_color(after_longhands, property_id)
});
decide_transition(&context, &property, values_originate_from_current_color)
})
@@ -601,12 +576,13 @@ impl TransitionDecision {
}
}
-/// What the transition step a style transaction's row owes decides, where nothing but the engine's records decides it
+/// What the transition step a style update's row owes decides, where nothing but the engine's records decides it
/// (see [`DecidedTransitionStep::of_row`]).
pub(crate) struct RowTransitions {
pub(crate) node: crate::css::style::tree::StyleNodeID,
- pub(crate) before: u64,
- pub(crate) after: u64,
+ /// The records the step decided over: the before-change style, and the record the row moves the element to.
+ pub(crate) before: std::sync::Arc<crate::css::style::pipeline::Record>,
+ pub(crate) after: std::sync::Arc<crate::css::style::pipeline::Record>,
actions: Vec<FfiTransitionAction>,
/// The time of the style change event, in the document timeline's milliseconds, where the caller knew it.
at: Option<f64>,
@@ -731,7 +707,7 @@ fn transition_values(
effect: &crate::css::style::effect_descriptions::PublishedEffect,
) -> Option<(u16, *const StyleValueData, *const StyleValueData)> {
use crate::css::style::effect_descriptions::PublishedValue;
- let [start, end] = effect.keyframes.as_ref() else {
+ let [start, end] = effect.keyframes() else {
return None;
};
let value = |keyframe| match effect.declarations_of(keyframe) {
@@ -759,15 +735,25 @@ impl RowTransitions {
if !row.owes_a_transition_step || row.owes_an_animation_plan || row.pseudo_kind != u8::MAX {
return false;
}
- let before = match engine.transition_baseline(node, u8::MAX) {
- 0 => row.old_style_record,
- baseline => baseline,
- };
- engine.style_record_view(before).is_some_and(|view| {
- view.dependency_flags & crate::css::computed_longhand_table::IN_DISPLAY_NONE_SUBTREE != 0
+ Self::before_change_record(engine, node, row).is_some_and(|before| {
+ crate::css::style::StyleRecordView::of_host_record(before).dependency_flags
+ & crate::css::computed_longhand_table::IN_DISPLAY_NONE_SUBTREE
+ != 0
})
}
+ /// The before-change style of the step `row` owes its element `node`: the record the epoch keeps for it, or else
+ /// the record it held.
+ fn before_change_record<'a>(
+ engine: &'a crate::css::style::StyleEngine,
+ node: crate::css::style::tree::StyleNodeID,
+ row: &crate::css::style::bridge::FfiStyleDelta,
+ ) -> Option<&'a std::sync::Arc<crate::css::style::pipeline::Record>> {
+ engine
+ .transition_baseline(node, u8::MAX)
+ .or_else(|| engine.host_record(row.old_style_record))
+ }
+
/// Decides the step `row` owes, with the transform reference box of the element's box where one is known, or
/// answers why the host has to.
///
@@ -806,14 +792,16 @@ impl RowTransitions {
),
(None, true, None) => return Err("an element with animations"),
};
- let before = match engine.transition_baseline(node, u8::MAX) {
- 0 => row.old_style_record,
- baseline => baseline,
- };
- let after = row.new_style_record;
- let before_view = engine.style_record_view(before).ok_or("a record that is gone")?;
- let after_view = engine.style_record_view(after).ok_or("a record that is gone")?;
- let after_table = after_view.longhand_table.ok_or("a record without a table")?;
+ let before = Self::before_change_record(engine, node, row)
+ .ok_or("a record that is gone")?
+ .clone();
+ let after = engine
+ .host_record(row.new_style_record)
+ .ok_or("a record that is gone")?
+ .clone();
+ let before_view = crate::css::style::StyleRecordView::of_host_record(&before);
+ let after_view = crate::css::style::StyleRecordView::of_host_record(&after);
+ let after_longhands = after_view.longhands();
if before_view.dependency_flags & crate::css::computed_longhand_table::IN_DISPLAY_NONE_SUBTREE != 0 {
return Err("a style under display: none");
}
@@ -823,11 +811,11 @@ impl RowTransitions {
// A declaration whose delay and duration are each the single value 0s starts nothing, so it matters only to an
// element running transitions it could cancel, as `TransitionDecision::decide` has it.
let entries = if running.is_empty()
- && crate::css::style_compute::transition_delay_and_duration_are_single_zero(after_table)
+ && crate::css::style_compute::transition_delay_and_duration_are_single_zero(after_longhands)
{
Vec::new()
} else {
- crate::css::style_compute::transition_entries(after_table)
+ crate::css::style_compute::transition_entries(after_longhands)
};
// A transform interpolates against the box it transforms.
if reference_box.is_none() && entries.iter().any(|entry| entry.property_id == prop::TRANSFORM) {
@@ -835,7 +823,9 @@ impl RowTransitions {
}
// An inherited value moves with the animations of the ancestors it comes from, which the host composes. Only a
// caller that knows the time of the style change takes the values of ancestors that run none.
- if entries.iter().any(|entry| after_table.is_inherited(entry.property_id))
+ if entries
+ .iter()
+ .any(|entry| after_longhands.is_inherited(entry.property_id))
&& (at.is_none() || engine.inheritance_ancestors_animate(node))
{
return Err("a transition of an inherited value");
@@ -874,7 +864,7 @@ impl RowTransitions {
engine
.sample_over_record(
node,
- after,
+ &after,
&mut overlay,
lane_effects,
composed,
@@ -894,12 +884,12 @@ impl RowTransitions {
})
.map(|transition| transition.property_id)
.collect();
- let actions = TransitionDecision {
+ let decision = TransitionDecision {
before,
after,
element: Some(node),
- }
- .decide_over(
+ };
+ let actions = decision.decide_over(
engine,
reference_box,
after_overlay.as_deref(),
@@ -907,6 +897,7 @@ impl RowTransitions {
&existing,
&ended,
);
+ let TransitionDecision { before, after, .. } = decision;
Ok(Self {
node,
before,
@@ -938,19 +929,18 @@ pub(crate) struct LaneTransitions<'a> {
pub(crate) start_time: f64,
}
-/// The transition step a style transaction decided beside the row of an element that owes one, which the host's step
+/// The transition step a style update decided beside the row of an element that owes one, which the host's step
/// reads rather than asking where it decides over the same inputs.
pub(crate) struct DecidedTransitionStep {
node: u32,
- before: u64,
- after: u64,
+ before: std::sync::Arc<crate::css::style::pipeline::Record>,
+ after: std::sync::Arc<crate::css::style::pipeline::Record>,
actions: Box<[FfiTransitionAction]>,
/// The first sample of the transitions the step starts, until a host step that reads the decision takes it.
fresh_sample: std::cell::Cell<Option<FreshTransitionSample>>,
}
-// SAFETY: The values a decision points at live in the records it decided over, which the host keeps live across the drain
-// of the transaction that decided it, the only time it reads them.
+// SAFETY: The values a decision points at live in the records it decided over, which it holds.
unsafe impl Send for DecidedTransitionStep {}
impl DecidedTransitionStep {
@@ -971,7 +961,7 @@ impl DecidedTransitionStep {
actions,
..
} = RowTransitions::decide(engine, row, None, None, None).ok()?;
- let fresh_sample = FreshTransitionSample::of_step(engine, node, after, &actions);
+ let fresh_sample = FreshTransitionSample::of_step(engine, node, &after, &actions);
Some(Self {
node: row.style_node,
before,
@@ -992,7 +982,10 @@ impl DecidedTransitionStep {
decision: &TransitionDecision,
existing: &[FfiExistingTransition],
) -> Option<&[FfiTransitionAction]> {
- (decision.before == self.before && decision.after == self.after && existing.is_empty()).then_some(&self.actions)
+ (std::sync::Arc::ptr_eq(&decision.before, &self.before)
+ && std::sync::Arc::ptr_eq(&decision.after, &self.after)
+ && existing.is_empty())
+ .then_some(&self.actions)
}
/// The first sample of the transitions the step starts, which only the host step that read its decision samples.
@@ -1005,7 +998,7 @@ impl DecidedTransitionStep {
/// element to, which the host's sample of them reads rather than asks. Each transition has only just started, so it
/// samples at the key its delay and easing give at its start, whatever the time.
pub(crate) struct FreshTransitionSample {
- after: u64,
+ after: std::sync::Arc<crate::css::style::pipeline::Record>,
/// The key each transition the step starts samples at, in the order the step starts them.
keys: Box<[f64]>,
overlay: crate::css::animated_overlay::AnimatedOverlay,
@@ -1018,7 +1011,7 @@ impl FreshTransitionSample {
fn of_step(
engine: &mut crate::css::style::StyleEngine,
node: crate::css::style::tree::StyleNodeID,
- after: u64,
+ after: &std::sync::Arc<crate::css::style::pipeline::Record>,
actions: &[FfiTransitionAction],
) -> Option<Self> {
use crate::css::animation::{FfiAnimationPreparationEffect, FfiSampledAnimationEffect};
@@ -1053,7 +1046,7 @@ impl FreshTransitionSample {
// The preparation is keyed by the step's own effects, which the host's are not.
overlay.animation_preparation = None;
Some(Self {
- after,
+ after: after.clone(),
keys,
overlay,
result,
@@ -1071,7 +1064,12 @@ impl FreshTransitionSample {
crate::css::style_compute::FfiHostAnimationSampleResult,
crate::css::style::animations::SampledEffectTimings,
)> {
- if input.style_record != self.after || input.has_animated_overlay {
+ if !input
+ .style_record
+ .as_ref()
+ .is_some_and(|record| std::sync::Arc::ptr_eq(record, &self.after))
+ || input.has_animated_overlay
+ {
return None;
}
let effects = input.effects.as_slice();
@@ -1365,7 +1363,7 @@ impl HoverTransitions {
}
let decision = RowTransitions::decide(engine, row, reference_box, Some(at), lane)?;
let (effects, runs) = hover_transition_effects(&decision)?;
- let (node, after) = (decision.node, decision.after);
+ let (node, after) = (decision.node, row.new_style_record);
let decided_over_running = !decision.running.is_empty();
if effects.is_empty() && !decided_over_running {
return Ok(None);
@@ -1376,7 +1374,7 @@ impl HoverTransitions {
.fold(0.0, f64::max);
let properties = effects
.iter()
- .filter_map(|effect| effect.declarations_of(effect.keyframes.first()?).first())
+ .filter_map(|effect| effect.declarations_of(effect.keyframes().first()?).first())
.map(|declaration| declaration.property_id)
.collect();
// A running transition of the host's the step leaves no run of ended with the step.
@@ -1536,9 +1534,10 @@ impl HoverTransitions {
current_key,
});
}
+ let after = engine.host_record(self.after).ok_or(NeedsHost)?.clone();
engine.sample_composed_over_record(
self.node,
- self.after,
+ &after,
crate::css::animated_overlay::AnimatedOverlay::default(),
Some(&self.effects),
composed,
@@ -1564,20 +1563,16 @@ pub(crate) struct TransitionEntry {
pub(crate) behavior: u8,
}
-/// Whether the table's `transition-*` values give any longhand a matching entry, stopping at the first. A declaration
-/// whose delay and duration are each the single value `0s`, which is how nearly every element declares no transition
-/// at all, starts nothing, so it gives none unless the element `has_existing_transitions` it could still cancel.
-///
-/// # Safety
-/// `longhand_table` must point to a live computed longhand table.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_transition_has_matching_entries(
- longhand_table: *const std::ffi::c_void,
+/// Whether the `transition-*` values of `longhands` give any longhand a matching entry, stopping at the first. A
+/// declaration whose delay and duration are each the single value `0s`, which is how nearly every element declares no
+/// transition at all, starts nothing, so it gives none unless the element `has_existing_transitions` it could still
+/// cancel.
+pub(crate) fn has_matching_transition_entries(
+ longhands: crate::css::style::ViewLonghands<'_>,
has_existing_transitions: bool,
) -> bool {
- let table = unsafe { &*longhand_table.cast::<crate::css::computed_longhand_table::ComputedLonghandTable>() };
- (has_existing_transitions || !crate::css::style_compute::transition_delay_and_duration_are_single_zero(table))
- && crate::css::style_compute::has_transition_entries(table)
+ (has_existing_transitions || !crate::css::style_compute::transition_delay_and_duration_are_single_zero(longhands))
+ && crate::css::style_compute::has_transition_entries(longhands)
}
#[cfg(test)]
@@ -1659,9 +1654,9 @@ mod tests {
#[test]
fn equal_nested_values_do_not_start_a_transition() {
let nested_value = || {
- let number = crate::css::style_value::RetainedStyleValueData::from_arc(std::sync::Arc::new(
- StyleValueData::Number { value: 0.5 },
- ));
+ let number = crate::css::style_value::RetainedStyleValueData::from_arc(
+ crate::css::style_value_arc::StyleValueArc::new(StyleValueData::Number { value: 0.5 }),
+ );
StyleValueData::OpacityValue { value: number }
};
let before = nested_value();
@@ -1693,14 +1688,16 @@ mod tests {
separator: 0,
collapsible: false,
};
- let mut table = crate::css::computed_longhand_table::ComputedLonghandTable::new();
- table.set(
- by_computed_value_property(),
- crate::css::style_value::RetainedStyleValueData::from_owned(nested),
- -1,
- );
+ let nested = crate::css::style_value::RetainedStyleValueData::from_owned(nested);
+ let value_of = |property| match property == by_computed_value_property() {
+ true => nested.clone(),
+ false => crate::css::style_compute::initial_value_handle(property).clone(),
+ };
- assert!(originates_from_current_color(&table, by_computed_value_property()));
+ assert!(crate::css::style::ViewLonghands::with_test_record(
+ value_of,
+ |longhands| { originates_from_current_color(longhands, by_computed_value_property()) }
+ ));
}
#[test]
@@ -1784,10 +1781,15 @@ mod tests {
} else {
Vec::new()
};
+ let record = || {
+ std::sync::Arc::new(crate::css::style::pipeline::Record::of_test_values(|property| {
+ crate::css::style_compute::initial_value_handle(property).clone()
+ }))
+ };
let decision = RowTransitions {
node: StyleNodeID::element(1),
- before: 1,
- after: 2,
+ before: record(),
+ after: record(),
actions: vec![action],
at: Some(500.0),
running,
diff --git a/Libraries/LibWeb/Rust/src/heap_size.rs b/Libraries/LibWeb/Rust/src/heap_size.rs
new file mode 100644
index 00000000000..2b4984c87a9
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/heap_size.rs
@@ -0,0 +1,224 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Counting the heap bytes a structure holds, for a memory report by owner.
+//!
+//! A count is what the structure asked the allocator for: a vector's capacity, a hash table's
+//! buckets and control bytes, a box's pointee. It does not ask the allocator what it rounded the
+//! requests up to, so a count is the same on every allocator and every run of the same document.
+//!
+//! An allocation several owners hold, as an `Arc` is, is counted once, by the first owner that
+//! reaches it: the [`HeapSizer`] remembers the address of every shared allocation it counted.
+
+use crate::fast_hash::FastSet as HashSet;
+use smallvec::SmallVec;
+use std::sync::Arc;
+
+/// The reference counts in front of the value of an `Arc`.
+pub(crate) const ARC_HEADER_BYTES: usize = 2 * size_of::<usize>();
+/// The count before a style value, which `StyleValueArc` keeps without a weak count.
+pub(crate) const STYLE_VALUE_HEADER_BYTES: usize = size_of::<usize>();
+
+/// What a memory report has counted so far.
+#[derive(Default)]
+pub(crate) struct HeapSizer {
+ seen: HashSet<usize>,
+ /// The bytes of the style values counted so far, which belong to no one owner: every owner
+ /// holding a value shares it.
+ pub(crate) style_value_bytes: usize,
+}
+
+impl HeapSizer {
+ /// Whether the shared allocation at `pointer` is reached for the first time, which the caller
+ /// then counts. A null pointer is never counted.
+ pub(crate) fn first_sight<T: ?Sized>(&mut self, pointer: *const T) -> bool {
+ let address = pointer.cast::<()>() as usize;
+ address != 0 && self.seen.insert(address)
+ }
+
+ /// The bytes of `arc`'s allocation and what its value holds, the first time it is reached.
+ pub(crate) fn arc<T: HeapSize + ?Sized>(&mut self, arc: &Arc<T>) -> usize {
+ if !self.first_sight(Arc::as_ptr(arc)) {
+ return 0;
+ }
+ ARC_HEADER_BYTES + size_of_val::<T>(arc) + (**arc).heap_size(self)
+ }
+
+ /// The bytes of `arc`'s allocation alone, the first time it is reached, for a value whose heap
+ /// is counted elsewhere or not at all.
+ pub(crate) fn arc_shallow<T: ?Sized>(&mut self, arc: &Arc<T>) -> usize {
+ if !self.first_sight(Arc::as_ptr(arc)) {
+ return 0;
+ }
+ ARC_HEADER_BYTES + size_of_val::<T>(arc)
+ }
+}
+
+/// The heap bytes a value holds beyond its own size.
+pub(crate) trait HeapSize {
+ fn heap_size(&self, sizer: &mut HeapSizer) -> usize;
+}
+
+macro_rules! no_heap {
+ ($($type:ty),* $(,)?) => {
+ $(impl HeapSize for $type {
+ fn heap_size(&self, _: &mut HeapSizer) -> usize {
+ 0
+ }
+ })*
+ };
+}
+
+no_heap!(bool, u8, u16, u32, u64, usize, i8, i16, i32, i64, f32, f64, ());
+
+/// The bytes of a vector's buffer, whose elements hold nothing on the heap.
+pub(crate) fn vec_bytes<T>(vector: &Vec<T>) -> usize {
+ vector.capacity() * size_of::<T>()
+}
+
+/// The bytes of a small vector's buffer where it spilled to the heap, whose elements hold nothing
+/// on the heap.
+pub(crate) fn small_vec_bytes<A: smallvec::Array>(vector: &SmallVec<A>) -> usize {
+ if vector.spilled() {
+ vector.capacity() * size_of::<A::Item>()
+ } else {
+ 0
+ }
+}
+
+/// The buckets a hash table of the standard library holds for `capacity` entries.
+fn hash_table_buckets(capacity: usize) -> usize {
+ if capacity == 0 {
+ 0
+ } else if capacity < 8 {
+ (capacity + 1).next_power_of_two()
+ } else {
+ (capacity * 8 / 7).next_power_of_two()
+ }
+}
+
+/// The bytes of a hash table of `capacity` entries of `entry_size` bytes: its buckets and their
+/// control bytes.
+pub(crate) fn hash_table_bytes(capacity: usize, entry_size: usize) -> usize {
+ let buckets = hash_table_buckets(capacity);
+ if buckets == 0 {
+ return 0;
+ }
+ // NB: One control byte per bucket, and one group of them repeated past the end.
+ const GROUP_WIDTH: usize = 16;
+ buckets * entry_size + buckets + GROUP_WIDTH
+}
+
+/// The bytes of a map's table, whose keys and values hold nothing on the heap.
+pub(crate) fn map_bytes<K, V, S>(map: &std::collections::HashMap<K, V, S>) -> usize {
+ hash_table_bytes(map.capacity(), size_of::<(K, V)>())
+}
+
+/// The bytes the `len` entries of a hash table of `entry_size` bytes hold, with their control
+/// bytes, but for the room the table reserved beyond them. A table every document of the process
+/// fills reports this, so that what one document adds to it does not depend on how much room the
+/// documents before it had the table reserve.
+pub(crate) fn live_hash_table_bytes(len: usize, entry_size: usize) -> usize {
+ len * (entry_size + 1)
+}
+
+/// The bytes of a set's table, whose keys hold nothing on the heap.
+pub(crate) fn set_bytes<K, S>(set: &std::collections::HashSet<K, S>) -> usize {
+ hash_table_bytes(set.capacity(), size_of::<K>())
+}
+
+impl<T: HeapSize> HeapSize for Vec<T> {
+ fn heap_size(&self, sizer: &mut HeapSizer) -> usize {
+ vec_bytes(self) + self.iter().map(|item| item.heap_size(sizer)).sum::<usize>()
+ }
+}
+
+impl<T: HeapSize> HeapSize for [T] {
+ fn heap_size(&self, sizer: &mut HeapSizer) -> usize {
+ self.iter().map(|item| item.heap_size(sizer)).sum()
+ }
+}
+
+impl<T: HeapSize, const N: usize> HeapSize for [T; N] {
+ fn heap_size(&self, sizer: &mut HeapSizer) -> usize {
+ self.iter().map(|item| item.heap_size(sizer)).sum()
+ }
+}
+
+impl<T: HeapSize + ?Sized> HeapSize for Box<T> {
+ fn heap_size(&self, sizer: &mut HeapSizer) -> usize {
+ size_of_val::<T>(self) + (**self).heap_size(sizer)
+ }
+}
+
+impl<T: HeapSize + ?Sized> HeapSize for Arc<T> {
+ fn heap_size(&self, sizer: &mut HeapSizer) -> usize {
+ sizer.arc(self)
+ }
+}
+
+impl<T: HeapSize> HeapSize for Option<T> {
+ fn heap_size(&self, sizer: &mut HeapSizer) -> usize {
+ self.as_ref().map_or(0, |value| value.heap_size(sizer))
+ }
+}
+
+impl<A: smallvec::Array> HeapSize for SmallVec<A>
+where
+ A::Item: HeapSize,
+{
+ fn heap_size(&self, sizer: &mut HeapSizer) -> usize {
+ small_vec_bytes(self) + self.iter().map(|item| item.heap_size(sizer)).sum::<usize>()
+ }
+}
+
+impl<K: HeapSize, V: HeapSize, S> HeapSize for std::collections::HashMap<K, V, S> {
+ fn heap_size(&self, sizer: &mut HeapSizer) -> usize {
+ map_bytes(self)
+ + self
+ .iter()
+ .map(|(key, value)| key.heap_size(sizer) + value.heap_size(sizer))
+ .sum::<usize>()
+ }
+}
+
+impl<K: HeapSize, S> HeapSize for std::collections::HashSet<K, S> {
+ fn heap_size(&self, sizer: &mut HeapSizer) -> usize {
+ set_bytes(self) + self.iter().map(|key| key.heap_size(sizer)).sum::<usize>()
+ }
+}
+
+impl<A: HeapSize, B: HeapSize> HeapSize for (A, B) {
+ fn heap_size(&self, sizer: &mut HeapSizer) -> usize {
+ self.0.heap_size(sizer) + self.1.heap_size(sizer)
+ }
+}
+
+impl<A: HeapSize, B: HeapSize, C: HeapSize> HeapSize for (A, B, C) {
+ fn heap_size(&self, sizer: &mut HeapSizer) -> usize {
+ self.0.heap_size(sizer) + self.1.heap_size(sizer) + self.2.heap_size(sizer)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_shared_allocation_is_counted_once() {
+ let shared = Arc::new(vec![1u32; 4]);
+ let holders = vec![Arc::clone(&shared), Arc::clone(&shared)];
+ let mut sizer = HeapSizer::default();
+ let bytes = holders.heap_size(&mut sizer);
+ assert_eq!(
+ bytes,
+ holders.capacity() * size_of::<Arc<Vec<u32>>>()
+ + ARC_HEADER_BYTES
+ + size_of::<Vec<u32>>()
+ + shared.capacity() * size_of::<u32>()
+ );
+ }
+}
diff --git a/Meta/Linters/check_rust_style_value_arc.py b/Meta/Linters/check_rust_style_value_arc.py
new file mode 100755
index 00000000000..86de5067ede
--- /dev/null
+++ b/Meta/Linters/check_rust_style_value_arc.py
@@ -0,0 +1,48 @@
+#!/usr/bin/env python3
+
+# Copyright (c) 2026-present, the Ladybird developers.
+#
+# SPDX-License-Identifier: BSD-2-Clause
+
+"""Keeps std's `Arc` away from style values.
+
+A style value is shared through `StyleValueArc`, whose count is the one word before the value, and C++
+retains and releases a value through it. A value in a std `Arc`, which keeps two counts before the
+value, still type-checks wherever it is made and turned into a raw pointer, and releasing it as a
+`StyleValueArc` then corrupts the heap. So no std `Arc` of a `StyleValueData` may be named.
+
+The check is a line-based heuristic, not a parser: it misses an `Arc::new` of a value bound to a
+variable, which review has to catch.
+"""
+
+import pathlib
+import re
+import subprocess
+import sys
+
+ROOT = "Libraries/LibWeb/Rust/src"
+
+PATTERNS = [
+ re.compile(r"\bArc<\s*(crate::css::style_value::)?StyleValueData\s*>"),
+ re.compile(r"\bArc::<\s*(crate::css::style_value::)?StyleValueData\s*>"),
+ re.compile(r"(?<!StyleValue)\bArc::new\(\s*(crate::css::style_value::)?StyleValueData::"),
+ re.compile(r"\b(OwnedArc|ArcRef)<[^>]*StyleValueData\s*>"),
+]
+
+
+def main():
+ files = subprocess.run(
+ ["git", "ls-files", "--", f"{ROOT}/*.rs"], capture_output=True, text=True, check=True
+ ).stdout.split()
+ failures = []
+ for file in files:
+ for number, line in enumerate(pathlib.Path(file).read_text().splitlines(), 1):
+ if any(pattern.search(line) for pattern in PATTERNS):
+ failures.append(f"{file}:{number}: {line.strip()}")
+ for failure in failures:
+ print(f"std Arc of a style value, use StyleValueArc: {failure}")
+ return 1 if failures else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/Tests/LibWeb/TestCSSSyntaxParser.cpp b/Tests/LibWeb/TestCSSSyntaxParser.cpp
index 8e147ef635b..f50d33595bb 100644
--- a/Tests/LibWeb/TestCSSSyntaxParser.cpp
+++ b/Tests/LibWeb/TestCSSSyntaxParser.cpp
@@ -444,19 +444,20 @@ TEST_CASE(native_declaration_block_specified_order_and_mutation)
TEST_CASE(native_declaration_block_merges_lists_without_expanding_again)
{
auto block = parse_native_declaration_block(u"margin: var(--gap); color: red !important; --色: first; @media all { width: 999px; } margin-left: 7px; color: blue; --色: last"sv);
- EXPECT_EQ(block.properties().size(), 6u);
- EXPECT_EQ(block.properties()[0].property_id, PropertyID::Margin);
- EXPECT_EQ(block.properties()[4].property_id, PropertyID::Color);
- EXPECT_EQ(block.properties()[4].important, Important::Yes);
- EXPECT_EQ(block.properties()[5].property_id, PropertyID::MarginLeft);
- EXPECT_EQ(block.properties()[5].value->to_utf16_string(SerializationMode::Normal), u"7px"sv);
+ // NB: margin-left no longer pends the margin shorthand, so the block drops that declaration.
+ EXPECT_EQ(block.properties().size(), 5u);
+ EXPECT_EQ(block.properties()[0].property_id, PropertyID::MarginTop);
+ EXPECT_EQ(block.properties()[3].property_id, PropertyID::Color);
+ EXPECT_EQ(block.properties()[3].important, Important::Yes);
+ EXPECT_EQ(block.properties()[4].property_id, PropertyID::MarginLeft);
+ EXPECT_EQ(block.properties()[4].value->to_utf16_string(SerializationMode::Normal), u"7px"sv);
EXPECT_EQ(block.custom_properties().size(), 1u);
EXPECT_EQ(block.custom_properties().begin()->value.value->to_utf16_string(SerializationMode::Normal), u"last"sv);
auto shared = block.share();
EXPECT(block.remove(PropertyID::MarginLeft));
- EXPECT_EQ(block.properties().size(), 5u);
- EXPECT_EQ(shared.properties()[5].value->to_utf16_string(SerializationMode::Normal), u"7px"sv);
+ EXPECT_EQ(block.properties().size(), 4u);
+ EXPECT_EQ(shared.properties()[4].value->to_utf16_string(SerializationMode::Normal), u"7px"sv);
EXPECT(parse_native_declaration_block(u"@media all { width: 999px; }"sv).is_empty());
EXPECT(parse_native_declaration_block(u""sv).is_empty());
}
diff --git a/Tests/LibWeb/TestStyleStructRef.cpp b/Tests/LibWeb/TestStyleStructRef.cpp
index 371e2da8ab8..4f855b52959 100644
--- a/Tests/LibWeb/TestStyleStructRef.cpp
+++ b/Tests/LibWeb/TestStyleStructRef.cpp
@@ -13,38 +13,45 @@ namespace Web::CSS {
// the registered group vtables, so these tests also cover the FFI layout and
// lifecycle contract for real style value group types.
-using TableGroup = ComputedValues::InheritedTableValues;
+using TableGroup = ComputedValues::InheritedListTableValues;
using TextGroup = ComputedValues::InheritedTextValues;
-TEST_CASE(default_constructed_refs_share_the_default_payload)
+template<typename T>
+static StyleStructRef<T> default_ref()
{
- StyleStructRef<TableGroup> a;
- StyleStructRef<TableGroup> b;
+ StyleStructRef<T> ref;
+ ref.adopt(ComputedValuesFFI::rust_style_group_create_default(T::style_group_index));
+ return ref;
+}
+
+TEST_CASE(default_payloads_hold_the_initial_values)
+{
+ auto a = default_ref<TableGroup>();
+ auto b = default_ref<TableGroup>();
EXPECT(a.is_default());
EXPECT(b.is_default());
- EXPECT(a.ptr_equals(b));
- EXPECT_EQ(a->border_collapse, to_underlying(InitialValues::border_collapse()));
+ EXPECT_EQ(a, b);
+ EXPECT_EQ(a->border_spacing_horizontal, 0);
}
TEST_CASE(access_clones_when_shared)
{
- StyleStructRef<TableGroup> a;
- StyleStructRef<TableGroup> untouched;
+ auto a = default_ref<TableGroup>();
+ auto untouched = a;
- a.access().caption_side = to_underlying(CaptionSide::Bottom);
+ a.access().border_spacing_horizontal = 7;
EXPECT(!a.is_default());
EXPECT(!a.ptr_equals(untouched));
- EXPECT_EQ(a->caption_side, to_underlying(CaptionSide::Bottom));
+ EXPECT_EQ(a->border_spacing_horizontal, 7);
- // The default payload must be unaffected by the mutation.
+ // The shared payload must be unaffected by the mutation.
EXPECT(untouched.is_default());
- EXPECT_EQ(untouched->caption_side, to_underlying(InitialValues::caption_side()));
- EXPECT_EQ(StyleStructRef<TableGroup>::default_value().caption_side, to_underlying(InitialValues::caption_side()));
+ EXPECT_EQ(untouched->border_spacing_horizontal, 0);
}
TEST_CASE(access_does_not_clone_when_unique)
{
- StyleStructRef<TableGroup> a;
+ auto a = default_ref<TableGroup>();
auto* first = &a.access();
auto* second = &a.access();
EXPECT_EQ(first, second);
@@ -52,31 +59,31 @@ TEST_CASE(access_does_not_clone_when_unique)
TEST_CASE(copies_share_until_mutated)
{
- StyleStructRef<TextGroup> a;
- a.access().word_break = to_underlying(WordBreak::BreakAll);
+ auto a = default_ref<TextGroup>();
+ a.access().text_transform = to_underlying(TextTransform::Uppercase);
StyleStructRef<TextGroup> b(a);
EXPECT(a.ptr_equals(b));
- b.access().word_break = to_underlying(WordBreak::KeepAll);
+ b.access().text_transform = to_underlying(TextTransform::Lowercase);
EXPECT(!a.ptr_equals(b));
- EXPECT_EQ(a->word_break, to_underlying(WordBreak::BreakAll));
- EXPECT_EQ(b->word_break, to_underlying(WordBreak::KeepAll));
+ EXPECT_EQ(a->text_transform, to_underlying(TextTransform::Uppercase));
+ EXPECT_EQ(b->text_transform, to_underlying(TextTransform::Lowercase));
EXPECT_EQ(b->text_shadow_span().size(), 0u);
}
TEST_CASE(assignment_shares_and_releases_old_payload)
{
- StyleStructRef<TableGroup> a;
- a.access().caption_side = to_underlying(CaptionSide::Bottom);
+ auto a = default_ref<TableGroup>();
+ a.access().border_spacing_horizontal = 7;
- StyleStructRef<TableGroup> b;
- b.access().empty_cells = to_underlying(EmptyCells::Hide);
+ auto b = default_ref<TableGroup>();
+ b.access().border_spacing_vertical = 5;
b = a;
EXPECT(a.ptr_equals(b));
- EXPECT_EQ(b->caption_side, to_underlying(CaptionSide::Bottom));
- EXPECT_EQ(b->empty_cells, to_underlying(InitialValues::empty_cells()));
+ EXPECT_EQ(b->border_spacing_horizontal, 7);
+ EXPECT_EQ(b->border_spacing_vertical, 0);
auto& self_reference = b;
b = self_reference;
@@ -85,8 +92,8 @@ TEST_CASE(assignment_shares_and_releases_old_payload)
TEST_CASE(value_equality_across_distinct_payloads)
{
- StyleStructRef<TableGroup> a;
- StyleStructRef<TableGroup> b;
+ auto a = default_ref<TableGroup>();
+ auto b = default_ref<TableGroup>();
a.access().border_spacing_horizontal = 9;
b.access().border_spacing_horizontal = 9;
EXPECT(!a.ptr_equals(b));
@@ -98,56 +105,56 @@ TEST_CASE(value_equality_across_distinct_payloads)
TEST_CASE(empty_borrowed_reference_can_be_destroyed)
{
- StyleStructRef<TableGroup> empty { StyleGroupInitialization::Empty };
+ StyleStructRef<TableGroup> empty;
}
TEST_CASE(empty_borrowed_reference_clones_before_mutation)
{
- StyleStructRef<TableGroup> source;
- source.access().caption_side = to_underlying(CaptionSide::Bottom);
- StyleStructRef<TableGroup> borrowed { StyleGroupInitialization::Empty };
+ auto source = default_ref<TableGroup>();
+ source.access().border_spacing_horizontal = 7;
+ StyleStructRef<TableGroup> borrowed;
borrowed.borrow(&*source);
EXPECT(borrowed.ptr_equals(source));
- borrowed.access().caption_side = to_underlying(CaptionSide::Top);
+ borrowed.access().border_spacing_horizontal = 3;
EXPECT(!borrowed.ptr_equals(source));
- EXPECT_EQ(source->caption_side, to_underlying(CaptionSide::Bottom));
- EXPECT_EQ(borrowed->caption_side, to_underlying(CaptionSide::Top));
+ EXPECT_EQ(source->border_spacing_horizontal, 7);
+ EXPECT_EQ(borrowed->border_spacing_horizontal, 3);
}
TEST_CASE(copy_of_borrowed_reference_outlives_owner)
{
auto copy = [] {
- StyleStructRef<TableGroup> owner;
- owner.access().caption_side = to_underlying(CaptionSide::Bottom);
- StyleStructRef<TableGroup> borrowed { StyleGroupInitialization::Empty };
+ auto owner = default_ref<TableGroup>();
+ owner.access().border_spacing_horizontal = 7;
+ StyleStructRef<TableGroup> borrowed;
borrowed.borrow(&*owner);
return StyleStructRef<TableGroup> { borrowed };
}();
- EXPECT_EQ(copy->caption_side, to_underlying(CaptionSide::Bottom));
- copy.access().caption_side = to_underlying(CaptionSide::Top);
- EXPECT_EQ(copy->caption_side, to_underlying(CaptionSide::Top));
+ EXPECT_EQ(copy->border_spacing_horizontal, 7);
+ copy.access().border_spacing_horizontal = 3;
+ EXPECT_EQ(copy->border_spacing_horizontal, 3);
}
TEST_CASE(assignment_initializes_empty_reference_with_owned_payload)
{
- StyleStructRef<TableGroup> source;
- source.access().caption_side = to_underlying(CaptionSide::Bottom);
- StyleStructRef<TableGroup> target { StyleGroupInitialization::Empty };
+ auto source = default_ref<TableGroup>();
+ source.access().border_spacing_horizontal = 7;
+ StyleStructRef<TableGroup> target;
target = source;
EXPECT(target.ptr_equals(source));
- source.access().caption_side = to_underlying(CaptionSide::Top);
- EXPECT_EQ(target->caption_side, to_underlying(CaptionSide::Bottom));
+ source.access().border_spacing_horizontal = 3;
+ EXPECT_EQ(target->border_spacing_horizontal, 7);
}
TEST_CASE(assignment_acquires_ownership_of_same_borrowed_payload)
{
- StyleStructRef<TableGroup> owner;
- owner.access().caption_side = to_underlying(CaptionSide::Bottom);
- StyleStructRef<TableGroup> borrowed { StyleGroupInitialization::Empty };
+ auto owner = default_ref<TableGroup>();
+ owner.access().border_spacing_horizontal = 7;
+ StyleStructRef<TableGroup> borrowed;
borrowed.borrow(&*owner);
borrowed = owner;
- owner.access().caption_side = to_underlying(CaptionSide::Top);
- EXPECT_EQ(borrowed->caption_side, to_underlying(CaptionSide::Bottom));
+ owner.access().border_spacing_horizontal = 3;
+ EXPECT_EQ(borrowed->border_spacing_horizontal, 7);
}
}
diff --git a/Tests/LibWeb/TestStyleValueEquality.cpp b/Tests/LibWeb/TestStyleValueEquality.cpp
index 628bf8e971b..d71c1c5817c 100644
--- a/Tests/LibWeb/TestStyleValueEquality.cpp
+++ b/Tests/LibWeb/TestStyleValueEquality.cpp
@@ -18,7 +18,6 @@
#include <LibWeb/CSS/StyleValues/KeywordStyleValue.h>
#include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
#include <LibWeb/CSS/StyleValues/NumberStyleValue.h>
-#include <LibWeb/CSS/StyleValues/PendingSubstitutionStyleValue.h>
#include <LibWeb/CSS/StyleValues/PercentageStyleValue.h>
#include <LibWeb/CSS/StyleValues/RatioStyleValue.h>
#include <LibWeb/CSS/StyleValues/RustStyleValueHandle.h>
@@ -37,57 +36,6 @@
namespace Web::CSS {
-TEST_CASE(computed_longhand_table_publication_identity_includes_sidecars)
-{
- auto value = NumberStyleValue::create(1);
- auto* original = ComputedValuesFFI::rust_computed_longhand_table_create();
- ComputedValuesFFI::rust_computed_longhand_table_set(original, to_underlying(PropertyID::Color), value->rust_style_value_data(), -1);
-
- auto* copy = ComputedValuesFFI::rust_computed_longhand_table_create();
- ComputedValuesFFI::rust_computed_longhand_table_copy_from(copy, original);
- ComputedValuesFFI::rust_computed_longhand_table_clear_seeded_state(copy);
- ComputedValuesFFI::rust_computed_longhand_table_freeze(original);
- ComputedValuesFFI::rust_computed_longhand_table_freeze(copy);
- EXPECT(!ComputedValuesFFI::rust_computed_longhand_tables_equal_for_publication(original, copy));
- ComputedValuesFFI::rust_computed_longhand_table_release(original);
- ComputedValuesFFI::rust_computed_longhand_table_release(copy);
-
- original = ComputedValuesFFI::rust_computed_longhand_table_create();
- copy = ComputedValuesFFI::rust_computed_longhand_table_create();
- ComputedValuesFFI::rust_computed_longhand_table_metadata(copy)->display_before_box_type_transformation = 1;
- ComputedValuesFFI::rust_computed_longhand_table_freeze(original);
- ComputedValuesFFI::rust_computed_longhand_table_freeze(copy);
- EXPECT(!ComputedValuesFFI::rust_computed_longhand_tables_equal_for_publication(original, copy));
- ComputedValuesFFI::rust_computed_longhand_table_release(original);
- ComputedValuesFFI::rust_computed_longhand_table_release(copy);
-
- original = ComputedValuesFFI::rust_computed_longhand_table_create();
- copy = ComputedValuesFFI::rust_computed_longhand_table_create();
- ComputedValuesFFI::rust_computed_longhand_table_metadata(copy)->effective_color_scheme = 1;
- ComputedValuesFFI::rust_computed_longhand_table_freeze(original);
- ComputedValuesFFI::rust_computed_longhand_table_freeze(copy);
- EXPECT(!ComputedValuesFFI::rust_computed_longhand_tables_equal_for_publication(original, copy));
- ComputedValuesFFI::rust_computed_longhand_table_release(original);
- ComputedValuesFFI::rust_computed_longhand_table_release(copy);
-}
-
-TEST_CASE(computed_longhand_table_inherited_copy_refreshes_effective_color_scheme)
-{
- auto* child = ComputedValuesFFI::rust_computed_longhand_table_create();
- auto* parent = ComputedValuesFFI::rust_computed_longhand_table_create();
- ComputedValuesFFI::rust_computed_longhand_table_metadata(child)->effective_color_scheme = 0;
- ComputedValuesFFI::rust_computed_longhand_table_metadata(parent)->effective_color_scheme = 1;
- ComputedValuesFFI::rust_computed_longhand_table_freeze(child);
- ComputedValuesFFI::rust_computed_longhand_table_freeze(parent);
-
- auto* inherited = ComputedValuesFFI::rust_computed_longhand_table_create_with_inherited_values(child, parent);
- EXPECT_EQ(ComputedValuesFFI::rust_computed_longhand_table_metadata(inherited)->effective_color_scheme, 1);
-
- ComputedValuesFFI::rust_computed_longhand_table_release(child);
- ComputedValuesFFI::rust_computed_longhand_table_release(parent);
- ComputedValuesFFI::rust_computed_longhand_table_release(inherited);
-}
-
static StyleValueFFI::StyleValueData const* create_test_image(StringView url)
{
auto url_string = MUST(String::from_utf8(url));
@@ -361,20 +309,6 @@ TEST_CASE(rust_font_style_handles_retain_angle_data)
EXPECT_EQ(angle->to_string(SerializationMode::Normal), "20deg"sv);
}
-TEST_CASE(rust_pending_substitution_handles_retain_shorthand_data)
-{
- auto shorthand = NumberStyleValue::create(1);
- auto data = StyleValueFFI::rust_style_value_create_pending_substitution(
- StyleValueFFI::rust_style_value_retain(shorthand->rust_style_value_data()));
-
- shorthand = NumberStyleValue::create(2);
- auto pending = StyleValue::adopt_rust_style_value_data(data);
- EXPECT(pending->is_pending_substitution());
- RefPtr<StyleValue const> retained_shorthand = pending->as_pending_substitution().original_shorthand_value();
- pending = KeywordStyleValue::create(Keyword::None);
- EXPECT_EQ(retained_shorthand->to_string(SerializationMode::Normal), "1"sv);
-}
-
TEST_CASE(rust_shadow_handles_retain_child_data)
{
auto offset_x = LengthStyleValue::create(Length::make_px(1));
@@ -499,7 +433,7 @@ TEST_CASE(rust_color_function_handles_retain_channel_data)
auto color = StyleValue::adopt_rust_style_value_data(data);
EXPECT(color->is_color_function());
auto const* retained_channel_data = static_cast<StyleValueFFI::StyleValueData const*>(
- color->rust_style_value_data()->color_function.channel_0.pointer);
+ color->rust_style_value_data()->color_function._0->channel_0.pointer);
auto retained_channel = StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(retained_channel_data));
color = KeywordStyleValue::create(Keyword::None);
EXPECT_EQ(retained_channel->to_string(SerializationMode::Normal), "0.1"sv);
diff --git a/Tests/LibWeb/Text/expected/css/pending-substitution-cssom-serialization.txt b/Tests/LibWeb/Text/expected/css/pending-substitution-cssom-serialization.txt
new file mode 100644
index 00000000000..12e61a640f8
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/pending-substitution-cssom-serialization.txt
@@ -0,0 +1,155 @@
+background cleared:
+ attribute: --y: 7px; --z: rgb(0, 128, 0);
+ cssText: --y: 7px; --z: rgb(0, 128, 0);
+ background: "" margin: "" border: "" border-width: ""
+ computed: rgba(0, 0, 0, 0) | 0px | 0px | 0px | 0px
+ clone attribute: --y: 7px; --z: rgb(0, 128, 0);
+ clone cssText: --y: 7px; --z: rgb(0, 128, 0);
+ clone computed: rgba(0, 0, 0, 0) | 0px | 0px | 0px | 0px
+background removed:
+ attribute: --y: 7px; --z: rgb(0, 128, 0);
+ cssText: --y: 7px; --z: rgb(0, 128, 0);
+ background: "" margin: "" border: "" border-width: ""
+ computed: rgba(0, 0, 0, 0) | 0px | 0px | 0px | 0px
+ clone attribute: --y: 7px; --z: rgb(0, 128, 0);
+ clone cssText: --y: 7px; --z: rgb(0, 128, 0);
+ clone computed: rgba(0, 0, 0, 0) | 0px | 0px | 0px | 0px
+a longhand removed:
+ attribute: --y: 7px; --z: rgb(0, 128, 0); margin-right: ; margin-bottom: ; margin-left: ;
+ cssText: --y: 7px; --z: rgb(0, 128, 0); margin-right: ; margin-bottom: ; margin-left: ;
+ background: "" margin: "" border: "" border-width: ""
+ computed: rgba(0, 0, 0, 0) | 0px | 7px | 0px | 0px
+ clone attribute: --y: 7px; --z: rgb(0, 128, 0); margin-right: ; margin-bottom: ; margin-left: ;
+ clone cssText: --y: 7px; --z: rgb(0, 128, 0); margin-right: ; margin-bottom: ; margin-left: ;
+ clone computed: rgba(0, 0, 0, 0) | 0px | 7px | 0px | 0px
+replaced by a value:
+ attribute: --y: 7px; --z: rgb(0, 128, 0); margin: 1px;
+ cssText: --y: 7px; --z: rgb(0, 128, 0); margin: 1px;
+ background: "" margin: "1px" border: "" border-width: ""
+ computed: rgba(0, 0, 0, 0) | 1px | 1px | 0px | 0px
+ clone attribute: --y: 7px; --z: rgb(0, 128, 0); margin: 1px;
+ clone cssText: --y: 7px; --z: rgb(0, 128, 0); margin: 1px;
+ clone computed: rgba(0, 0, 0, 0) | 1px | 1px | 0px | 0px
+a longhand replaced:
+ attribute: --y: 7px; --z: rgb(0, 128, 0); margin-top: ; margin-right: ; margin-bottom: ; margin-left: 1px;
+ cssText: --y: 7px; --z: rgb(0, 128, 0); margin-top: ; margin-right: ; margin-bottom: ; margin-left: 1px;
+ background: "" margin: "" border: "" border-width: ""
+ computed: rgba(0, 0, 0, 0) | 7px | 1px | 0px | 0px
+ clone attribute: --y: 7px; --z: rgb(0, 128, 0); margin-top: ; margin-right: ; margin-bottom: ; margin-left: 1px;
+ clone cssText: --y: 7px; --z: rgb(0, 128, 0); margin-top: ; margin-right: ; margin-bottom: ; margin-left: 1px;
+ clone computed: rgba(0, 0, 0, 0) | 7px | 1px | 0px | 0px
+a longhand replaced and written again:
+ attribute: --y: 7px; --z: rgb(0, 128, 0); margin: var(--y);
+ cssText: --y: 7px; --z: rgb(0, 128, 0); margin: var(--y);
+ background: "" margin: "var(--y)" border: "" border-width: ""
+ computed: rgba(0, 0, 0, 0) | 7px | 7px | 0px | 0px
+ clone attribute: --y: 7px; --z: rgb(0, 128, 0); margin: var(--y);
+ clone cssText: --y: 7px; --z: rgb(0, 128, 0); margin: var(--y);
+ clone computed: rgba(0, 0, 0, 0) | 7px | 7px | 0px | 0px
+written again after clearing:
+ attribute: --y: 7px; --z: rgb(0, 128, 0); margin: var(--y);
+ cssText: --y: 7px; --z: rgb(0, 128, 0); margin: var(--y);
+ background: "" margin: "var(--y)" border: "" border-width: ""
+ computed: rgba(0, 0, 0, 0) | 7px | 7px | 0px | 0px
+ clone attribute: --y: 7px; --z: rgb(0, 128, 0); margin: var(--y);
+ clone cssText: --y: 7px; --z: rgb(0, 128, 0); margin: var(--y);
+ clone computed: rgba(0, 0, 0, 0) | 7px | 7px | 0px | 0px
+written over an earlier longhand:
+ attribute: --y: 7px; --z: rgb(0, 128, 0); margin: var(--y); color: red;
+ cssText: --y: 7px; --z: rgb(0, 128, 0); margin: var(--y); color: red;
+ background: "" margin: "var(--y)" border: "" border-width: ""
+ computed: rgba(0, 0, 0, 0) | 7px | 7px | 0px | 0px
+ clone attribute: --y: 7px; --z: rgb(0, 128, 0); margin: var(--y); color: red;
+ clone cssText: --y: 7px; --z: rgb(0, 128, 0); margin: var(--y); color: red;
+ clone computed: rgba(0, 0, 0, 0) | 7px | 7px | 0px | 0px
+nested shorthand replaced:
+ attribute: --y: 7px; --z: rgb(0, 128, 0); border-width: var(--y); border-top-style: ; border-right-style: ; border-bottom-style: ; border-left-style: ; border-top-color: ; border-right-color: ; border-bottom-color: ; border-left-color: ; border-image-source: ; border-image-slice: ; border-image-width: ; border-image-outset: ; border-image-repeat: ;
+ cssText: --y: 7px; --z: rgb(0, 128, 0); border-width: var(--y); border-top-style: ; border-right-style: ; border-bottom-style: ; border-left-style: ; border-top-color: ; border-right-color: ; border-bottom-color: ; border-left-color: ; border-image-source: ; border-image-slice: ; border-image-width: ; border-image-outset: ; border-image-repeat: ;
+ background: "" margin: "" border: "" border-width: "var(--y)"
+ computed: rgba(0, 0, 0, 0) | 0px | 0px | 7px | 7px
+ clone attribute: --y: 7px; --z: rgb(0, 128, 0); border-width: var(--y); border-top-style: ; border-right-style: ; border-bottom-style: ; border-left-style: ; border-top-color: ; border-right-color: ; border-bottom-color: ; border-left-color: ; border-image-source: ; border-image-slice: ; border-image-width: ; border-image-outset: ; border-image-repeat: ;
+ clone cssText: --y: 7px; --z: rgb(0, 128, 0); border-width: var(--y); border-top-style: ; border-right-style: ; border-bottom-style: ; border-left-style: ; border-top-color: ; border-right-color: ; border-bottom-color: ; border-left-color: ; border-image-source: ; border-image-slice: ; border-image-width: ; border-image-outset: ; border-image-repeat: ;
+ clone computed: rgba(0, 0, 0, 0) | 0px | 0px | 7px | 7px
+nested shorthand removed:
+ attribute: --y: 7px; --z: rgb(0, 128, 0); border-top-style: ; border-right-style: ; border-bottom-style: ; border-left-style: ; border-top-color: ; border-right-color: ; border-bottom-color: ; border-left-color: ; border-image-source: ; border-image-slice: ; border-image-width: ; border-image-outset: ; border-image-repeat: ;
+ cssText: --y: 7px; --z: rgb(0, 128, 0); border-top-style: ; border-right-style: ; border-bottom-style: ; border-left-style: ; border-top-color: ; border-right-color: ; border-bottom-color: ; border-left-color: ; border-image-source: ; border-image-slice: ; border-image-width: ; border-image-outset: ; border-image-repeat: ;
+ background: "" margin: "" border: "" border-width: ""
+ computed: rgba(0, 0, 0, 0) | 0px | 0px | 3px | 3px
+ clone attribute: --y: 7px; --z: rgb(0, 128, 0); border-top-style: ; border-right-style: ; border-bottom-style: ; border-left-style: ; border-top-color: ; border-right-color: ; border-bottom-color: ; border-left-color: ; border-image-source: ; border-image-slice: ; border-image-width: ; border-image-outset: ; border-image-repeat: ;
+ clone cssText: --y: 7px; --z: rgb(0, 128, 0); border-top-style: ; border-right-style: ; border-bottom-style: ; border-left-style: ; border-top-color: ; border-right-color: ; border-bottom-color: ; border-left-color: ; border-image-source: ; border-image-slice: ; border-image-width: ; border-image-outset: ; border-image-repeat: ;
+ clone computed: rgba(0, 0, 0, 0) | 0px | 0px | 3px | 3px
+nested longhand replaced:
+ attribute: --y: 7px; --z: rgb(0, 128, 0); border-top-width: 1px; border-right-width: ; border-bottom-width: ; border-left-width: ; border-top-style: ; border-right-style: ; border-bottom-style: ; border-left-style: ; border-top-color: ; border-right-color: ; border-bottom-color: ; border-left-color: ; border-image-source: ; border-image-slice: ; border-image-width: ; border-image-outset: ; border-image-repeat: ;
+ cssText: --y: 7px; --z: rgb(0, 128, 0); border-top-width: 1px; border-right-width: ; border-bottom-width: ; border-left-width: ; border-top-style: ; border-right-style: ; border-bottom-style: ; border-left-style: ; border-top-color: ; border-right-color: ; border-bottom-color: ; border-left-color: ; border-image-source: ; border-image-slice: ; border-image-width: ; border-image-outset: ; border-image-repeat: ;
+ background: "" margin: "" border: "" border-width: ""
+ computed: rgba(0, 0, 0, 0) | 0px | 0px | 1px | 7px
+ clone attribute: --y: 7px; --z: rgb(0, 128, 0); border-top-width: 1px; border-right-width: ; border-bottom-width: ; border-left-width: ; border-top-style: ; border-right-style: ; border-bottom-style: ; border-left-style: ; border-top-color: ; border-right-color: ; border-bottom-color: ; border-left-color: ; border-image-source: ; border-image-slice: ; border-image-width: ; border-image-outset: ; border-image-repeat: ;
+ clone cssText: --y: 7px; --z: rgb(0, 128, 0); border-top-width: 1px; border-right-width: ; border-bottom-width: ; border-left-width: ; border-top-style: ; border-right-style: ; border-bottom-style: ; border-left-style: ; border-top-color: ; border-right-color: ; border-bottom-color: ; border-left-color: ; border-image-source: ; border-image-slice: ; border-image-width: ; border-image-outset: ; border-image-repeat: ;
+ clone computed: rgba(0, 0, 0, 0) | 0px | 0px | 1px | 7px
+each side written the same:
+ attribute: --y: 7px; --z: rgb(0, 128, 0); border-top: var(--y); border-right: var(--y); border-bottom: var(--y); border-left: var(--y);
+ cssText: --y: 7px; --z: rgb(0, 128, 0); border-top: var(--y); border-right: var(--y); border-bottom: var(--y); border-left: var(--y);
+ background: "" margin: "" border: "" border-width: ""
+ computed: rgba(0, 0, 0, 0) | 0px | 0px | 0px | 0px
+ clone attribute: --y: 7px; --z: rgb(0, 128, 0); border-top: var(--y); border-right: var(--y); border-bottom: var(--y); border-left: var(--y);
+ clone cssText: --y: 7px; --z: rgb(0, 128, 0); border-top: var(--y); border-right: var(--y); border-bottom: var(--y); border-left: var(--y);
+ clone computed: rgba(0, 0, 0, 0) | 0px | 0px | 0px | 0px
+a side over the whole:
+ attribute: --y: 7px; --z: rgb(0, 128, 0); border-top: var(--y); border-right-width: ; border-bottom-width: ; border-left-width: ; border-right-style: ; border-bottom-style: ; border-left-style: ; border-right-color: ; border-bottom-color: ; border-left-color: ; border-image-source: ; border-image-slice: ; border-image-width: ; border-image-outset: ; border-image-repeat: ;
+ cssText: --y: 7px; --z: rgb(0, 128, 0); border-top: var(--y); border-right-width: ; border-bottom-width: ; border-left-width: ; border-right-style: ; border-bottom-style: ; border-left-style: ; border-right-color: ; border-bottom-color: ; border-left-color: ; border-image-source: ; border-image-slice: ; border-image-width: ; border-image-outset: ; border-image-repeat: ;
+ background: "" margin: "" border: "" border-width: ""
+ computed: rgba(0, 0, 0, 0) | 0px | 0px | 0px | 0px
+ clone attribute: --y: 7px; --z: rgb(0, 128, 0); border-top: var(--y); border-right-width: ; border-bottom-width: ; border-left-width: ; border-right-style: ; border-bottom-style: ; border-left-style: ; border-right-color: ; border-bottom-color: ; border-left-color: ; border-image-source: ; border-image-slice: ; border-image-width: ; border-image-outset: ; border-image-repeat: ;
+ clone cssText: --y: 7px; --z: rgb(0, 128, 0); border-top: var(--y); border-right-width: ; border-bottom-width: ; border-left-width: ; border-right-style: ; border-bottom-style: ; border-left-style: ; border-right-color: ; border-bottom-color: ; border-left-color: ; border-image-source: ; border-image-slice: ; border-image-width: ; border-image-outset: ; border-image-repeat: ;
+ clone computed: rgba(0, 0, 0, 0) | 0px | 0px | 0px | 0px
+untouched:
+ attribute: --y: 7px; --z: rgb(0, 128, 0); margin: var(--y);
+ cssText: --y: 7px; --z: rgb(0, 128, 0); margin: var(--y);
+ background: "" margin: "var(--y)" border: "" border-width: ""
+ computed: rgba(0, 0, 0, 0) | 7px | 7px | 0px | 0px
+ clone attribute: --y: 7px; --z: rgb(0, 128, 0); margin: var(--y);
+ clone cssText: --y: 7px; --z: rgb(0, 128, 0); margin: var(--y);
+ clone computed: rgba(0, 0, 0, 0) | 7px | 7px | 0px | 0px
+untouched nested:
+ attribute: --y: 7px; --z: rgb(0, 128, 0); border: var(--y) solid;
+ cssText: --y: 7px; --z: rgb(0, 128, 0); border: var(--y) solid;
+ background: "" margin: "" border: "var(--y) solid" border-width: ""
+ computed: rgba(0, 0, 0, 0) | 0px | 0px | 7px | 7px
+ clone attribute: --y: 7px; --z: rgb(0, 128, 0); border: var(--y) solid;
+ clone cssText: --y: 7px; --z: rgb(0, 128, 0); border: var(--y) solid;
+ clone computed: rgba(0, 0, 0, 0) | 0px | 0px | 7px | 7px
+attribute with a later longhand:
+ attribute: --y: 7px; margin-top: ; margin-right: ; margin-bottom: ; margin-left: 1px;
+ cssText: --y: 7px; margin-top: ; margin-right: ; margin-bottom: ; margin-left: 1px;
+ background: "" margin: "" border: "" border-width: ""
+ computed: rgba(0, 0, 0, 0) | 7px | 1px | 0px | 0px
+ clone attribute: --y: 7px; margin-top: ; margin-right: ; margin-bottom: ; margin-left: 1px;
+ clone cssText: --y: 7px; margin-top: ; margin-right: ; margin-bottom: ; margin-left: 1px;
+ clone computed: rgba(0, 0, 0, 0) | 7px | 1px | 0px | 0px
+attribute with an earlier important longhand:
+ attribute: --y: 7px; margin-left: 1px !important; margin-top: ; margin-right: ; margin-bottom: ;
+ cssText: --y: 7px; margin-left: 1px !important; margin-top: ; margin-right: ; margin-bottom: ;
+ background: "" margin: "" border: "" border-width: ""
+ computed: rgba(0, 0, 0, 0) | 7px | 1px | 0px | 0px
+ clone attribute: --y: 7px; margin-left: 1px !important; margin-top: ; margin-right: ; margin-bottom: ;
+ clone cssText: --y: 7px; margin-left: 1px !important; margin-top: ; margin-right: ; margin-bottom: ;
+ clone computed: rgba(0, 0, 0, 0) | 7px | 1px | 0px | 0px
+attribute untouched:
+ attribute: --y: 7px; margin: var(--y);
+ cssText: --y: 7px; margin: var(--y);
+ background: "" margin: "var(--y)" border: "" border-width: ""
+ computed: rgba(0, 0, 0, 0) | 7px | 7px | 0px | 0px
+ clone attribute: --y: 7px; margin: var(--y);
+ clone cssText: --y: 7px; margin: var(--y);
+ clone computed: rgba(0, 0, 0, 0) | 7px | 7px | 0px | 0px
+typed OM write over a longhand:
+ attribute: --y: 7px; margin-right: ; margin-bottom: ; margin-left: ; margin-top: 1px;
+ cssText: --y: 7px; margin-right: ; margin-bottom: ; margin-left: ; margin-top: 1px;
+ background: "" margin: "" border: "" border-width: ""
+ computed: rgba(0, 0, 0, 0) | 1px | 7px | 0px | 0px
+ clone attribute: --y: 7px; margin-right: ; margin-bottom: ; margin-left: ; margin-top: 1px;
+ clone cssText: --y: 7px; margin-right: ; margin-bottom: ; margin-left: ; margin-top: 1px;
+ clone computed: rgba(0, 0, 0, 0) | 1px | 7px | 0px | 0px
+rule: --y: 7px; margin-right: ; margin-bottom: ; margin-left: ;
+rule cleared: --y: 7px;
+rule computed: 0px
diff --git a/Tests/LibWeb/Text/input/css/pending-substitution-cssom-serialization.html b/Tests/LibWeb/Text/input/css/pending-substitution-cssom-serialization.html
new file mode 100644
index 00000000000..eba595cfc1e
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/pending-substitution-cssom-serialization.html
@@ -0,0 +1,91 @@
+<!DOCTYPE html>
+<div id="host"></div>
+<style>
+#rule-target {
+}
+</style>
+<script src="../include.js"></script>
+<script>
+ test(() => {
+ const host = document.getElementById("host");
+
+ function dump(name, element) {
+ const style = getComputedStyle(element);
+ const properties = ["background-color", "margin-top", "margin-left", "border-top-width", "border-right-width"];
+ println(`${name}:`);
+ println(` attribute: ${element.getAttribute("style")}`);
+ println(` cssText: ${element.style.cssText}`);
+ println(` background: "${element.style.background}" margin: "${element.style.margin}" border: "${element.style.border}" border-width: "${element.style.borderWidth}"`);
+ println(` computed: ${properties.map(property => style.getPropertyValue(property)).join(" | ")}`);
+ const clone = element.cloneNode();
+ host.append(clone);
+ const cloneStyle = getComputedStyle(clone);
+ println(` clone attribute: ${clone.getAttribute("style")}`);
+ println(` clone cssText: ${clone.style.cssText}`);
+ println(` clone computed: ${properties.map(property => cloneStyle.getPropertyValue(property)).join(" | ")}`);
+ clone.remove();
+ }
+
+ function writes(name, ...steps) {
+ const element = document.createElement("div");
+ element.style.cssText = "--y: 7px; --z: rgb(0, 128, 0)";
+ host.append(element);
+ for (const step of steps) {
+ step(element.style);
+ getComputedStyle(element).color;
+ }
+ dump(name, element);
+ element.remove();
+ }
+
+ function attribute(name, text) {
+ const element = document.createElement("div");
+ element.setAttribute("style", `--y: 7px; ${text}`);
+ host.append(element);
+ // NB: The attribute's own text stands until a write through CSSOM serializes the declarations.
+ element.style.setProperty("--w", "1");
+ element.style.removeProperty("--w");
+ dump(name, element);
+ element.remove();
+ }
+
+ writes("background cleared", s => (s.background = "var(--z)"), s => (s.background = ""));
+ writes("background removed", s => (s.background = "var(--z)"), s => s.removeProperty("background"));
+ writes("a longhand removed", s => (s.margin = "var(--y)"), s => s.removeProperty("margin-top"));
+ writes("replaced by a value", s => (s.margin = "var(--y)"), s => (s.margin = "1px"));
+ writes("a longhand replaced", s => (s.margin = "var(--y)"), s => (s.marginLeft = "1px"));
+ writes("a longhand replaced and written again", s => (s.margin = "var(--y)"), s => (s.marginLeft = "1px"), s => (s.margin = "var(--y)"));
+ writes("written again after clearing", s => (s.margin = "var(--y)"), s => (s.margin = ""), s => (s.margin = "var(--y)"));
+ writes("written over an earlier longhand", s => (s.marginTop = "1px"), s => (s.color = "red"), s => (s.margin = "var(--y)"));
+ writes("nested shorthand replaced", s => (s.border = "var(--y) solid"), s => (s.borderWidth = "var(--y)"));
+ writes("nested shorthand removed", s => (s.border = "var(--y) solid"), s => s.removeProperty("border-width"));
+ writes("nested longhand replaced", s => (s.border = "var(--y) solid"), s => (s.borderTopWidth = "1px"));
+ writes("each side written the same", s => (s.borderTop = "var(--y)"), s => (s.borderRight = "var(--y)"), s => (s.borderBottom = "var(--y)"), s => (s.borderLeft = "var(--y)"));
+ writes("a side over the whole", s => (s.border = "var(--y)"), s => (s.borderTop = "var(--y)"));
+ writes("untouched", s => (s.margin = "var(--y)"));
+ writes("untouched nested", s => (s.border = "var(--y) solid"));
+ attribute("attribute with a later longhand", "margin: var(--y); margin-left: 1px");
+ attribute("attribute with an earlier important longhand", "margin-left: 1px !important; margin: var(--y)");
+ attribute("attribute untouched", "margin: var(--y)");
+
+ const typed = document.createElement("div");
+ typed.style.cssText = "--y: 7px; margin: var(--y)";
+ host.append(typed);
+ typed.attributeStyleMap.set("margin-top", CSS.px(1));
+ dump("typed OM write over a longhand", typed);
+ typed.remove();
+
+ const ruleElement = document.createElement("div");
+ ruleElement.id = "rule-target";
+ host.append(ruleElement);
+ const rule = document.styleSheets[0].cssRules[0];
+ rule.style.cssText = "--y: 7px";
+ rule.style.margin = "var(--y)";
+ rule.style.removeProperty("margin-top");
+ println(`rule: ${rule.style.cssText}`);
+ rule.style.margin = "var(--y)";
+ rule.style.margin = "";
+ println(`rule cleared: ${rule.style.cssText}`);
+ println(`rule computed: ${getComputedStyle(ruleElement).marginTop}`);
+ });
+</script>
diff --git a/Tests/LibWebView/test-shared-stylesheet-memory.py b/Tests/LibWebView/test-shared-stylesheet-memory.py
index d5f40f12faa..2e5a7147ea4 100644
--- a/Tests/LibWebView/test-shared-stylesheet-memory.py
+++ b/Tests/LibWebView/test-shared-stylesheet-memory.py
@@ -20,10 +20,20 @@ helpers = runpy.run_path(str(Path(__file__).with_name("test-webdriver-delete-ses
FRAME_COUNT = 8
RULE_COUNT = 20000
-# A sheet with url() values, which resolve against the sheet's own URL. Every frame links the same sheet, from a
+# Bytes per rule of style data each further frame may add beyond an empty frame, by how it links the sheet, which a
+# change growing them has to raise. Style data is what the style engines report, each allocation once however many
+# frames share it, which unlike the RSS does not depend on what nothing has collected yet. An "own-first" frame links a
+# small sheet of its own, of a different length in each frame, before the shared one, so the frames number the shared
+# sheet's rules apart.
+PER_FRAME_BYTES_PER_RULE = {"link": 8, "print": 8, "own-first": 80}
+
+# A sheet with a url() value, which resolves against the sheet's own URL. Every frame links the same sheet, from a
# document at a URL of its own.
+#
+# NB: All the rules name one image. Each distinct image takes about 40 KB of a frame's image requests, which is no more
+# a cost per rule than it is style data.
STYLE_SHEET = "\n".join(
- f".c{i} .d{i % 97} > span.e{i % 13}:hover{{color:#{i % 4096:03x};background:url(img{i % 50}.png)}}"
+ f".c{i} .d{i % 97} > span.e{i % 13}:hover{{color:#{i % 4096:03x};background:url(img.png)}}"
for i in range(RULE_COUNT)
).encode()
@@ -33,12 +43,24 @@ class Handler(http.server.BaseHTTPRequestHandler):
if self.path.endswith("/sheet.css"):
body = STYLE_SHEET
content_type = "text/css"
+ elif self.path.endswith("/own.css"):
+ frame = int(self.path.split("/")[3])
+ body = "\n".join(f".own{frame}-{i} {{ margin-top: {i}px }}" for i in range(10 + frame)).encode()
+ content_type = "text/css"
elif self.path.startswith("/frame/"):
- body = b'<!doctype html><link rel=stylesheet href="/sheet.css"><div class=c1><div class=d1><span class=e1>x</span></div></div>'
+ kind = self.path.split("/")[2]
+ link = {
+ "link": '<link rel=stylesheet href="/sheet.css">',
+ "print": '<link rel=stylesheet media=print href="/sheet.css">',
+ "own-first": '<link rel=stylesheet href="own.css"><link rel=stylesheet href="/sheet.css">',
+ "empty": "",
+ }[kind]
+ body = f"<!doctype html>{link}<div class=c1><div class=d1><span class=e1>x</span></div></div>".encode()
content_type = "text/html"
elif self.path.startswith("/?frames="):
- count = int(self.path.rsplit("=", 1)[1])
- frames = "".join(f'<iframe src="/frame/{i}/"></iframe>' for i in range(count))
+ count, kind = self.path.split("=", 1)[1].split("&kind=")
+ count = int(count)
+ frames = "".join(f'<iframe src="/frame/{kind}/{i}/"></iframe>' for i in range(count))
body = f"<!doctype html><title>frames={count}</title>{frames}".encode()
content_type = "text/html"
else:
@@ -80,9 +102,11 @@ def web_content_resident_bytes(root_pid):
return largest
-def measure(webdriver_binary, server_port, frame_count):
+def measure(webdriver_binary, server_port, frame_count, kind="link"):
with tempfile.TemporaryDirectory(prefix="ladybird-shared-sheet-") as profile:
- process, port = helpers["launch_webdriver"](webdriver_binary, "--headless", f"--profile-path={profile}")
+ process, port = helpers["launch_webdriver"](
+ webdriver_binary, "--headless", "--expose-internals-object", f"--profile-path={profile}"
+ )
session = None
try:
session = helpers["create_session"](port)
@@ -90,31 +114,47 @@ def measure(webdriver_binary, server_port, frame_count):
port,
"POST",
f"/session/{session}/url",
- {"url": f"http://127.0.0.1:{server_port}/?frames={frame_count}"},
+ {"url": f"http://127.0.0.1:{server_port}/?frames={frame_count}&kind={kind}"},
)
assert status == 200, raw
# Every frame has applied the sheet once its document has laid out with it.
script = """
return Array.from(document.querySelectorAll("iframe")).every(frame => {
const span = frame.contentDocument && frame.contentDocument.querySelector("span");
- return span && frame.contentDocument.readyState === "complete"
- && frame.contentDocument.styleSheets.length === 1
- && frame.contentDocument.styleSheets[0].cssRules.length === arguments[0];
+ if (!span || frame.contentDocument.readyState !== "complete")
+ return false;
+ span.offsetWidth;
+ const sheets = frame.contentDocument.styleSheets;
+ if (arguments[1] === "empty")
+ return sheets.length === 0;
+ const shared = arguments[1] === "own-first" ? 1 : 0;
+ return sheets.length === shared + 1 && sheets[shared].cssRules.length === arguments[0];
});
"""
deadline = time.monotonic() + helpers["EVENT_TIMEOUT_SECONDS"]
payload = {"value": None}
while time.monotonic() < deadline:
status, payload, raw = helpers["request"](
- port, "POST", f"/session/{session}/execute/sync", {"script": script, "args": [RULE_COUNT]}
+ port,
+ "POST",
+ f"/session/{session}/execute/sync",
+ {"script": script, "args": [RULE_COUNT, kind]},
)
assert status == 200, raw
if payload["value"] is True:
break
time.sleep(0.2)
assert payload["value"] is True, f"The {frame_count} frames never finished loading the sheet"
+ status, payload, raw = helpers["request"](
+ port,
+ "POST",
+ f"/session/{session}/execute/sync",
+ {"script": "return internals.styleMemoryOfFrames();", "args": []},
+ )
+ assert status == 200, raw
+ style_bytes = payload["value"]
time.sleep(2)
- return web_content_resident_bytes(process.pid)
+ return web_content_resident_bytes(process.pid), style_bytes
finally:
try:
if session is not None:
@@ -136,15 +176,36 @@ def main():
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
try:
- one = measure(webdriver_binary, server.server_port, 1)
- many = measure(webdriver_binary, server.server_port, FRAME_COUNT)
+ measured = {
+ kind: (
+ measure(webdriver_binary, server.server_port, 1, kind),
+ measure(webdriver_binary, server.server_port, FRAME_COUNT, kind),
+ )
+ for kind in ("empty", "link", "print", "own-first")
+ }
finally:
server.shutdown()
server.server_close()
+ (one, _), (many, _) = measured["link"]
# The frames share one parse of the sheet, so the page costs little more than one frame does. Parsing the sheet
# once per frame would cost several times that.
assert many < one * 2, f"{FRAME_COUNT} frames of one sheet take {many >> 20} MiB, one frame {one >> 20} MiB"
+
+ def per_extra_frame(kind):
+ (_, one), (_, many) = measured[kind]
+ return (many - one) / (FRAME_COUNT - 1)
+
+ # What each further frame linking the sheet holds of style data beyond an empty frame, per rule: the document's own
+ # index of the sheet and whatever else it holds per rule.
+ empty = per_extra_frame("empty")
+ failures = []
+ for kind, budget in PER_FRAME_BYTES_PER_RULE.items():
+ bytes_per_rule = (per_extra_frame(kind) - empty) / RULE_COUNT
+ print(f"{kind}: {bytes_per_rule:.1f} B/rule per extra frame (budget {budget})")
+ if bytes_per_rule > budget:
+ failures.append(kind)
+ assert not failures, f"over their per-frame budgets: {failures}"
print(f"PASS: {FRAME_COUNT} frames sharing a sheet: {many >> 20} MiB, one frame: {one >> 20} MiB")