Skip to content

Truly independent web browser

LibWeb: Make rule selector accessors safe, and use them in tests

Andreas Kling8349b268746c
diff --git a/Libraries/LibWeb/Rust/src/css/declaration_block.rs b/Libraries/LibWeb/Rust/src/css/declaration_block.rs
index 40b3e0090a3..a1a71e09272 100644
--- a/Libraries/LibWeb/Rust/src/css/declaration_block.rs
+++ b/Libraries/LibWeb/Rust/src/css/declaration_block.rs
@@ -636,7 +636,7 @@ mod tests {
use crate::css::parser::syntax_parser::parse_shared_stylesheet;
use crate::css::parser::value_parser::ParseContext;
use crate::css::property_metadata::property_id;
- use crate::css::rule::{rust_rule_children, rust_rule_list_at, rust_rule_payload};
+ use crate::css::rule::rust_rule_payload;
fn parsed_declarations(text: &str) -> Arc<DeclarationBlockData> {
let units: Vec<_> = format!(".target {{ {text} }}").encode_utf16().collect();
@@ -645,7 +645,7 @@ mod tests {
let context = ParseContext::default();
let parse = unsafe { parse_shared_stylesheet(input, &context) };
let rules = crate::css::rule::NativeRuleList::from_parsed(parse);
- let rule = unsafe { &*rust_rule_list_at(&rules, 0) };
+ let rule = &rules.rule_at(0);
rule.cascade_declarations().unwrap()
}
@@ -725,10 +725,9 @@ mod tests {
let context = ParseContext::default();
let parse = unsafe { parse_shared_stylesheet(input, &context) };
let rules = crate::css::rule::NativeRuleList::from_parsed(parse);
- let rule = unsafe { &*rust_rule_list_at(&rules, 0) };
- let children = unsafe { &*rust_rule_children(rule) };
- let nested = unsafe { &*rust_rule_list_at(children, 1) };
- let block = unsafe { &*rust_rule_payload(nested).declarations };
+ let rule = rules.rule_at(0);
+ 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();
@@ -759,7 +758,7 @@ mod tests {
assert_eq!(block.data().properties.len(), 1);
assert_eq!(rust_declaration_block_revision(block), 2);
assert!(matches!(*fork.state.borrow(), DeclarationBlockState::Immutable(_)));
- drop(rules);
+ 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());
diff --git a/Libraries/LibWeb/Rust/src/css/descriptor_block.rs b/Libraries/LibWeb/Rust/src/css/descriptor_block.rs
index eeeefb66fb1..c2d37188bd8 100644
--- a/Libraries/LibWeb/Rust/src/css/descriptor_block.rs
+++ b/Libraries/LibWeb/Rust/src/css/descriptor_block.rs
@@ -292,7 +292,7 @@ mod tests {
use super::*;
use crate::css::parser::syntax_parser::parse_shared_stylesheet;
use crate::css::parser::value_parser::ParseContext;
- use crate::css::rule::{rust_rule_list_at, rust_rule_payload};
+ use crate::css::rule::rust_rule_payload;
#[test]
fn descriptor_snapshots_can_be_mutated_on_a_worker() {
@@ -338,8 +338,8 @@ mod tests {
let context = ParseContext::default();
let parse = unsafe { parse_shared_stylesheet(input, &context) };
let rules = crate::css::rule::NativeRuleList::from_parsed(parse);
- let rule = unsafe { &*rust_rule_list_at(&rules, 0) };
- let block = unsafe { &*rust_rule_payload(rule).descriptors };
+ let rule = rules.rule_at(0);
+ let block = unsafe { &*rust_rule_payload(&rule).descriptors };
let snapshot = block.data();
let old_data = Arc::downgrade(&snapshot);
assert_eq!(snapshot.descriptors.len(), 2);
@@ -377,7 +377,7 @@ mod tests {
rust_descriptor_block_replace(&mut retained, &fork);
assert_eq!(rust_descriptor_block_length(block), 2);
assert!(matches!(*fork.state.borrow(), DescriptorBlockState::Immutable(_)));
- drop(rules);
+ drop((rule, rules));
let first = &snapshot.descriptors[0];
assert!(unsafe { rust_descriptor_block_remove(&mut fork, first.id, FfiUtf16View::default()) });
assert!(matches!(*fork.state.borrow(), DescriptorBlockState::Mutable(_)));
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 70f8e981878..b47a7bd3abe 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
@@ -284,7 +284,6 @@ fn keyframe_mutation_preserves_exposed_declarations_and_snapshots() {
use crate::css::declaration_block::{rust_declaration_block_identity as identity, rust_declaration_block_replace};
use crate::css::property_metadata::property_id;
use crate::css::rule::*;
- use std::rc::Rc;
let sheet = parse_shared_on_worker(
"@keyframes 色 { from, 50% { width: 13px !important; height: 17px; } 25% { width: 19px; } to { width: 29px; } }",
@@ -331,7 +330,7 @@ fn keyframe_mutation_preserves_exposed_declarations_and_snapshots() {
assert_eq!(identity(&declarations_at(children, 1)), identity(&exposed_declarations));
rust_rule_list_remove(children, 1);
rust_declaration_block_replace(&mut exposed_declarations, &original);
- rust_rule_list_insert(children, 1, Rc::as_ptr(&exposed));
+ 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).unwrap(),
diff --git a/Libraries/LibWeb/Rust/src/css/rule.rs b/Libraries/LibWeb/Rust/src/css/rule.rs
index 8c162365e72..7b08084555f 100644
--- a/Libraries/LibWeb/Rust/src/css/rule.rs
+++ b/Libraries/LibWeb/Rust/src/css/rule.rs
@@ -252,7 +252,12 @@ impl NativeRule {
None
}
- pub(crate) unsafe fn matching_selectors(&self) -> Rc<RustParsedSelectorList> {
+ /// The rule's child rules, for a grouping rule.
+ pub(crate) fn child_rules(&self) -> Option<&Rc<NativeRuleList>> {
+ self.children.as_ref()
+ }
+
+ 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 {
@@ -262,7 +267,7 @@ impl NativeRule {
}
});
let parents = if parent_kind == StyleNestingParent::Style {
- Some(unsafe { parent.as_ref().unwrap().matching_selectors() })
+ Some(parent.as_ref().unwrap().matching_selectors())
} else {
None
};
@@ -324,7 +329,7 @@ impl NativeRule {
}
}
- pub(crate) unsafe fn scope_start_selectors(&self) -> Option<Rc<RustParsedSelectorList>> {
+ 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 {
@@ -340,7 +345,7 @@ impl NativeRule {
_ => StyleNestingParent::None,
});
let parents = if parent_kind == StyleNestingParent::Style {
- Some(unsafe { parent.as_ref().unwrap().matching_selectors() })
+ Some(parent.as_ref().unwrap().matching_selectors())
} else {
None
};
@@ -848,24 +853,22 @@ pub extern "C" fn rust_rule_selectors(rule: &NativeRule) -> *const c_void {
Arc::as_ptr(&rule.style_rule().selectors()).cast()
}
-/// # Safety
-/// Call only for style or nested-declaration rules on the document thread.
-/// The returned list must be released with `rust_parsed_selector_list_destroy` on that same thread.
+/// Call only for style or nested-declaration rules. The returned list must be released with
+/// `rust_parsed_selector_list_destroy` on the same thread.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_rule_matching_selectors(rule: &NativeRule) -> *mut c_void {
- let selectors = unsafe { rule.matching_selectors() };
+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(),
}))
.cast()
}
-/// # Safety
-/// Call for a scope rule or scoped import on the document thread. A non-null result
-/// must be destroyed with `rust_parsed_selector_list_destroy`; null means the start is omitted.
+/// Call for a scope rule or scoped import. A non-null result must be destroyed with
+/// `rust_parsed_selector_list_destroy`; null means the start is omitted.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_rule_scope_start_selectors(rule: &NativeRule) -> *mut c_void {
- unsafe { rule.scope_start_selectors() }
+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(),
@@ -1046,7 +1049,7 @@ pub unsafe extern "C" fn rust_rule_set_page_selectors(rule: &NativeRule, selecto
#[unsafe(no_mangle)]
pub extern "C" fn rust_rule_children(rule: &NativeRule) -> *const NativeRuleList {
- rule.children.as_ref().map_or(std::ptr::null(), Rc::as_ptr)
+ rule.child_rules().map_or(std::ptr::null(), Rc::as_ptr)
}
#[unsafe(no_mangle)]
diff --git a/Libraries/LibWeb/Rust/src/css/rule/compilation.rs b/Libraries/LibWeb/Rust/src/css/rule/compilation.rs
index f58d66667bd..5896c851dad 100644
--- a/Libraries/LibWeb/Rust/src/css/rule/compilation.rs
+++ b/Libraries/LibWeb/Rust/src/css/rule/compilation.rs
@@ -535,7 +535,7 @@ mod tests {
use crate::css::parser::syntax_parser::parse_shared_stylesheet;
use crate::css::parser::value_parser::ParseContext;
use crate::css::rule::RulePayload;
- use crate::css::style_sheet::{rust_style_sheet_create, rust_style_sheet_set_import};
+ use crate::css::style_sheet::rust_style_sheet_create;
use std::cell::RefCell;
fn sheet(source: &str) -> Rc<NativeStyleSheet> {
@@ -771,7 +771,7 @@ mod tests {
.any_changed
);
});
- unsafe { rust_style_sheet_set_import(&source, source.rules().rule_at(0).identity, Rc::as_ptr(&child)) };
+ source.set_import(source.rules().rule_at(0).identity, Some(child.clone()));
with_media_width(150.0, |environment| {
let mut published = Vec::new();
let result = source.evaluate_media_queries(environment, &mut state, &mut |identity, holds| {
@@ -789,7 +789,7 @@ mod tests {
crate::css::rule::NativeRuleList::new(Vec::new(), None),
media_at(&source, &[0]),
);
- unsafe { rust_style_sheet_set_import(&source, source.rules().rule_at(0).identity, Rc::as_ptr(&child)) };
+ source.set_import(source.rules().rule_at(0).identity, Some(child.clone()));
let mut state = crate::css::style_sheet::NativeMediaEvaluationState::default();
with_media_width(50.0, |environment| {
assert!(
@@ -817,7 +817,7 @@ mod tests {
];
let imports = [source.rules().rule_at(0).identity, source.rules().rule_at(2).identity];
for (identity, child) in imports.iter().zip(&children) {
- unsafe { rust_style_sheet_set_import(&source, *identity, Rc::as_ptr(child)) };
+ source.set_import(*identity, Some(child.clone()));
}
let mut media_state = crate::css::style_sheet::NativeMediaEvaluationState::default();
let media = children.each_ref().map(|child| media_at(child, &[0]));
@@ -863,7 +863,7 @@ mod tests {
let children = std::array::from_fn::<_, 3, _>(|_| sheet(".imported {}"));
let child_rules = children.each_ref().map(|child| child.rules().rule_at(0).identity);
for (identity, child) in imports.iter().zip(&children) {
- unsafe { rust_style_sheet_set_import(&source, *identity, Rc::as_ptr(child)) };
+ source.set_import(*identity, Some(child.clone()));
}
let imported_media = media_at(&source, &[0]);
let outer = media_at(&source, &[3]);
@@ -943,7 +943,7 @@ mod tests {
);
let child = sheet("@layer 子;");
for index in [0, 1] {
- unsafe { rust_style_sheet_set_import(&source, source.rules().rule_at(index).identity, Rc::as_ptr(&child)) };
+ source.set_import(source.rules().rule_at(index).identity, Some(child.clone()));
}
let mut names = Vec::new();
source.visit_layer_names(&mut "根".encode_utf16().collect(), &mut |name| {
@@ -981,24 +981,22 @@ mod tests {
let children = parent.children.as_ref().unwrap();
let child = children.rule_at(0);
let scope = children.rule_at(1);
- unsafe {
- 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 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 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 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()));
}
#[test]
fn ancestor_lifetimes_follow_detachment_and_reparenting() {
- use crate::css::rule::{rust_rule_list_clear, rust_rule_list_insert};
+ 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();
@@ -1028,7 +1026,7 @@ mod tests {
drop(retained);
assert!(ancestors(&leaf).is_empty());
let children = destination.children.as_ref().unwrap();
- unsafe { rust_rule_list_insert(children, 0, Rc::as_ptr(&leaf)) };
+ children.insert(0, leaf.clone());
let reparented = ancestors(&leaf);
assert_eq!(reparented.len(), 1);
assert_eq!(reparented[0].identity, destination.identity);
@@ -1264,9 +1262,7 @@ mod tests {
&media,
))
};
- unsafe {
- rust_style_sheet_set_import(&source, rule.identity(), Rc::as_ptr(&child));
- }
+ source.set_import(rule.identity(), Some(child.clone()));
loaded_child = Some(child);
std::ops::ControlFlow::Break(())
});
@@ -1744,7 +1740,7 @@ mod tests {
} } }",
);
let import = root.rules().materialized_rules()[0].identity;
- unsafe { rust_style_sheet_set_import(&root, import, Rc::as_ptr(&child)) };
+ root.set_import(import, Some(child.clone()));
let rules = collect(&root, 0, NativeCompilationPurpose::Rules);
assert_eq!(rules.len(), 2);
for rule in &rules {
@@ -1802,9 +1798,7 @@ mod tests {
#[test]
fn keyframe_children_share_declarations_and_track_native_membership() {
use crate::css::declaration_block::rust_declaration_block_identity;
- use crate::css::rule::{
- rust_rule_declarations, rust_rule_list_clear, rust_rule_list_insert, rust_rule_list_remove,
- };
+ 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();
@@ -1819,7 +1813,7 @@ mod tests {
rust_rule_list_remove(children, 0);
assert_eq!(first.declaration_owner_identity(), None);
assert_eq!(children.materialized_rules().len(), 1);
- unsafe { rust_rule_list_insert(children, 1, Rc::as_ptr(&first)) };
+ children.insert(1, first.clone());
assert_eq!(first.declaration_owner_identity(), Some(rule.identity));
let reinserted = unsafe { Box::from_raw(rust_rule_declarations(&children.rule_at(1))) };
assert_eq!(
@@ -1833,9 +1827,7 @@ mod tests {
#[test]
fn native_rule_identity_survives_tree_edits() {
- use crate::css::rule::{
- rust_rule_list_clear, rust_rule_list_insert, rust_rule_list_remove, rust_rule_list_replace,
- };
+ use crate::css::rule::{rust_rule_list_clear, rust_rule_list_remove, rust_rule_list_replace};
let source = ".先頭 {} @media all { .兄弟 {} @supports (display: grid) { .対象 { width: 13px } } }";
let first = sheet(source);
let second = sheet(source);
@@ -1860,11 +1852,11 @@ mod tests {
assert_eq!(path(rules, target.identity), [0, 0, 0]);
rust_rule_list_remove(descendants, 0);
assert!(path(rules, target.identity).is_empty());
- unsafe { rust_rule_list_insert(descendants, 0, Rc::as_ptr(&target)) };
+ descendants.insert(0, target.clone());
assert_eq!(path(rules, target.identity), [0, 0, 0]);
rust_rule_list_clear(rules);
assert!(path(rules, target.identity).is_empty());
- unsafe { rust_rule_list_insert(rules, 0, Rc::as_ptr(&media)) };
+ rules.insert(0, media.clone());
assert_eq!(path(rules, target.identity), [0, 0, 0]);
rust_rule_list_replace(rules, other);
assert!(path(rules, target.identity).is_empty());
diff --git a/Libraries/LibWeb/Rust/src/css/rule/mutation.rs b/Libraries/LibWeb/Rust/src/css/rule/mutation.rs
index d081a152f4e..1e9113932a9 100644
--- a/Libraries/LibWeb/Rust/src/css/rule/mutation.rs
+++ b/Libraries/LibWeb/Rust/src/css/rule/mutation.rs
@@ -116,7 +116,6 @@ mod tests {
use crate::css::parser::syntax_parser::parse_shared_stylesheet;
use crate::css::parser::value_parser::ParseContext;
use crate::css::rule::rust_rule_list_remove;
- use crate::css::style_sheet::rust_style_sheet_set_import;
fn sheet(source: &str) -> Rc<NativeStyleSheet> {
let units: Vec<_> = source.encode_utf16().collect();
@@ -151,10 +150,8 @@ mod tests {
let nested = sheet("@keyframes 動き { from { opacity: 0 } to { opacity: 1 } } .先頭 {}");
let import = root.rules().materialized_rules()[0].clone();
let nested_import = imported.rules().materialized_rules()[0].clone();
- unsafe {
- rust_style_sheet_set_import(&root, import.identity, Rc::as_ptr(&imported));
- rust_style_sheet_set_import(&imported, nested_import.identity, Rc::as_ptr(&nested));
- }
+ root.set_import(import.identity, Some(imported.clone()));
+ imported.set_import(nested_import.identity, Some(nested.clone()));
let middle = imported.rules().materialized_rules()[1].identity;
let last = root.rules().materialized_rules()[1].identity;
let published = |identity| identity == middle || identity == last;
@@ -164,7 +161,7 @@ mod tests {
assert!(!declares_layer(&nested_import));
rust_rule_list_remove(root.rules(), 0);
- unsafe { rust_style_sheet_set_import(&root, import.identity, std::ptr::null()) };
+ root.set_import(import.identity, None);
let removed = unsafe { removed_rules(&import, &root, Some(&imported)) };
let kinds: Vec<_> = removed.iter().map(|rule| rule.rule_type).collect();
assert!(
diff --git a/Libraries/LibWeb/Rust/src/css/style/bridge.rs b/Libraries/LibWeb/Rust/src/css/style/bridge.rs
index beb5b35d1cf..8171780a316 100644
--- a/Libraries/LibWeb/Rust/src/css/style/bridge.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/bridge.rs
@@ -2842,28 +2842,21 @@ pub unsafe extern "C" fn style_engine_remove_native_rule(
/// Read a rule's native cascade data without a CSSOM facade.
///
-/// # Safety
-/// `host` must be a live document host, on its document's thread. On success the caller owns
-/// declarations and must release it with rust_declaration_data_release. Layer text is borrowed
-/// until the next rule mutation; callers must copy any text needed across such a mutation. Source
-/// identity never retains a native sheet.
+/// On success the caller owns declarations and must release it with
+/// rust_declaration_data_release. Layer text is borrowed until the next rule mutation; callers must
+/// copy any text needed across such a mutation. Source identity never retains a native sheet.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn style_engine_native_rule_target(
+pub extern "C" fn style_engine_native_rule_target(
host: &DocumentHost,
read: &crate::render_state::BegunRead,
rule: u32,
result: &mut FfiNativeRuleTarget,
) -> bool {
- // SAFETY: Guaranteed by the caller.
- // SAFETY: Guaranteed by the caller.
- with_engine(read, host, |engine| unsafe { native_rule_target(engine, rule, result) })
+ with_engine(read, host, |engine| native_rule_target(engine, rule, result))
}
/// [`style_engine_native_rule_target`] on `engine`.
-///
-/// # Safety
-/// As for [`style_engine_native_rule_target`], for the arguments after `engine`.
-pub unsafe fn native_rule_target(engine: &mut StyleEngine, rule: u32, result: &mut FfiNativeRuleTarget) -> bool {
+pub fn native_rule_target(engine: &mut StyleEngine, rule: u32, result: &mut FfiNativeRuleTarget) -> bool {
let Some(target) = rule
.checked_sub(1)
.and_then(|id| engine.native_rules.targets.get(&RuleID(id)))
diff --git a/Libraries/LibWeb/Rust/src/css/style/native_rules.rs b/Libraries/LibWeb/Rust/src/css/style/native_rules.rs
index 669782e90ca..a82cc3acfb4 100644
--- a/Libraries/LibWeb/Rust/src/css/style/native_rules.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/native_rules.rs
@@ -181,7 +181,7 @@ mod tests {
use crate::css::media_list::MediaList;
use crate::css::parser::syntax_parser::parse_shared_stylesheet;
use crate::css::parser::value_parser::ParseContext;
- use crate::css::rule::{rust_rule_identity, rust_rule_list_at, rust_rule_list_clear, rust_rule_retain};
+ use crate::css::rule::{rust_rule_identity, rust_rule_list_clear};
use crate::css::style::StyleEngine;
use crate::css::style::program::{CascadeOrigin, RuleKind, StyleSheetObjectID};
use crate::css::style_sheet::NativeStyleSheet;
@@ -201,7 +201,7 @@ mod tests {
#[test]
fn native_rule_inputs_do_not_retain_document_local_sheets_or_rules() {
let source = source();
- let rule = unsafe { Rc::from_raw(rust_rule_retain(rust_rule_list_at(source.rules(), 0))) };
+ let rule = source.rules().rule_at(0);
let identity = rust_rule_identity(&rule);
let source_weak = Rc::downgrade(&source);
let source_identity = source.identity();
@@ -253,12 +253,11 @@ mod tests {
#[test]
fn declaration_edits_resolve_native_owners_and_use_engine_revisions() {
- use crate::css::rule::rust_rule_children;
use crate::css::style::rule_writes::publish_native_rule_declarations;
let source = source();
- let rule = unsafe { &*rust_rule_list_at(source.rules(), 0) };
- let children = unsafe { &*rust_rule_children(rule) };
- let child = unsafe { Rc::from_raw(rust_rule_retain(rust_rule_list_at(children, 0))) };
+ let rule = &source.rules().rule_at(0);
+ let children = rule.child_rules().unwrap();
+ let child = children.rule_at(0);
let mut engine = StyleEngine::new();
let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);
let id = engine.add_non_matching_rule(sheet, None, RuleKind::Function);
@@ -301,8 +300,8 @@ mod tests {
fn replacing_a_native_owner_retires_the_old_reverse_lookup() {
let old_source = source();
let new_source = source();
- let old_rule = unsafe { &*rust_rule_list_at(old_source.rules(), 0) };
- let new_rule = unsafe { &*rust_rule_list_at(new_source.rules(), 0) };
+ let old_rule = &old_source.rules().rule_at(0);
+ let new_rule = &new_source.rules().rule_at(0);
let mut engine = StyleEngine::new();
let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);
let id = engine.add_non_matching_rule(sheet, None, RuleKind::Function);
diff --git a/Libraries/LibWeb/Rust/src/css/style/tests.rs b/Libraries/LibWeb/Rust/src/css/style/tests.rs
index 1b764804faf..7c14b04e979 100644
--- a/Libraries/LibWeb/Rust/src/css/style/tests.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/tests.rs
@@ -65,7 +65,7 @@ fn native_selector_publication_and_replacement_outlive_the_source() {
for (text, matches) in [(".別, .色 {}", true), (".別 {}", false), (".色 {}", true)] {
let rules = native_rules(text);
let rule = rules.rule_at(0);
- let bound = unsafe { rule.matching_selectors() };
+ let bound = rule.matching_selectors();
let selectors: Vec<_> = bound.selectors.iter().map(|selector| selector.as_ref()).collect();
if published == 0 {
published = publish_style_rule(
@@ -100,7 +100,7 @@ fn native_selector_publication_and_replacement_outlive_the_source() {
#[test]
fn native_scope_publication_outlives_the_rule_graph() {
use super::bridge::{BoundScopeChain, publish_style_rule, publish_style_rule_selectors};
- use crate::css::rule::{NativeRuleType, rust_rule_children, rust_rule_list_count};
+ use crate::css::rule::{NativeRuleType, rust_rule_list_count};
for (source, matches) in [
("@scope (.根) {}", true),
("@scope (.別) {}", false),
@@ -129,18 +129,18 @@ fn native_scope_publication_outlives_the_rule_graph() {
crate::css::rule::rust_rule_type(&rule),
NativeRuleType::Scope | NativeRuleType::Import
) {
- let start = unsafe { rule.scope_start_selectors() };
+ let start = rule.scope_start_selectors();
let end = rule.scope_end_selectors();
scope.push(start.as_deref(), end.as_deref(), nodes[0].raw());
}
- let children = unsafe { rust_rule_children(&rule).as_ref() };
+ let children = rule.child_rules().map(|children| &**children);
let Some(children) = children.filter(|children| rust_rule_list_count(children) > 0) else {
break;
};
rule = children.rule_at(0);
}
let universal = native_rules("* {}");
- let bound = unsafe { universal.rule_at(0).matching_selectors() };
+ let bound = universal.rule_at(0).matching_selectors();
let selectors: Vec<_> = bound.selectors.iter().map(|selector| selector.as_ref()).collect();
if published == 0 {
published = publish_style_rule(
@@ -175,7 +175,7 @@ fn native_declaration_publication_reuses_values_and_observes_live_mutation() {
let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);
engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);
let first = native_rules("* { color: #14181c; }");
- let bound = unsafe { first.rule_at(0).matching_selectors() };
+ let bound = first.rule_at(0).matching_selectors();
let selectors: Vec<_> = bound.selectors.iter().map(|selector| selector.as_ref()).collect();
let rule = publish_style_rule(
&mut engine,
diff --git a/Libraries/LibWeb/Rust/src/css/style_rule.rs b/Libraries/LibWeb/Rust/src/css/style_rule.rs
index 010ae71633b..f30163d2549 100644
--- a/Libraries/LibWeb/Rust/src/css/style_rule.rs
+++ b/Libraries/LibWeb/Rust/src/css/style_rule.rs
@@ -54,7 +54,7 @@ mod tests {
use super::*;
use crate::css::parser::syntax_parser::parse_shared_stylesheet;
use crate::css::parser::value_parser::ParseContext;
- use crate::css::rule::{NativeRuleList, rust_rule_list_at, rust_rule_list_visit_images};
+ use crate::css::rule::{NativeRuleList, rust_rule_list_visit_images};
use std::ffi::c_void;
use std::rc::Rc;
@@ -73,7 +73,7 @@ mod tests {
use crate::css::style::bridge::publish_rule_declarations;
use crate::css::style::program::{CascadeOrigin, RuleKind, StyleSheetObjectID};
let rules = rules(".文字 { width: 13px; transition: width 1s; background-image: url(image.png); }");
- let rule = unsafe { &*rust_rule_list_at(&rules, 0) };
+ 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()));
@@ -100,7 +100,7 @@ mod tests {
fn cascade_targets_retain_immutable_snapshots_without_promoting_style_owners() {
use crate::css::media_list::MediaList;
use crate::css::property_metadata::property_id;
- use crate::css::rule::{rust_rule_list_clear, rust_rule_retain};
+ 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};
@@ -112,8 +112,8 @@ mod tests {
let source = NativeStyleSheet::new(rules.clone(), media);
let source_lifetime = Rc::downgrade(&source);
let source_identity = source.identity();
- let rule = unsafe { &*rust_rule_list_at(&rules, 0) };
- let retained_rule = unsafe { Rc::from_raw(rust_rule_retain(rule)) };
+ let rule = rules.rule_at(0);
+ let retained_rule = Rc::clone(&rule);
let rule_lifetime = Rc::downgrade(&retained_rule);
drop(retained_rule);
let style = rule.style_rule();
@@ -122,7 +122,7 @@ mod tests {
let id = engine.add_non_matching_rule(sheet, None, RuleKind::Style);
engine.register_native_rule(
id,
- crate::css::rule::rust_rule_identity(rule),
+ crate::css::rule::rust_rule_identity(&rule),
rule.cascade_declarations(),
source.identity(),
&[],
@@ -130,7 +130,7 @@ mod tests {
);
// All fields are integers, nullable pointers, booleans, or enums whose zero variant is valid.
let mut target: FfiNativeRuleTarget = unsafe { std::mem::zeroed() };
- assert!(unsafe { native_rule_target(&mut engine, id.0 + 1, &mut target,) });
+ assert!(native_rule_target(&mut engine, id.0 + 1, &mut target,));
let snapshot = unsafe { Arc::from_raw(target.declarations.cast::<DeclarationBlockData>()) };
assert_eq!(target.source_identity, source_identity);
assert!(style.declarations.is_immutable());
@@ -145,25 +145,26 @@ mod tests {
.and_then(|identity| engine.native_rule_id(identity))
.expect("the rule owns its declarations");
publish_native_rule_declarations(&mut engine, rule.cascade_declarations(), owner);
- assert!(unsafe { native_rule_target(&mut engine, id.0 + 1, &mut target,) });
+ assert!(native_rule_target(&mut engine, id.0 + 1, &mut target,));
let edited_snapshot = unsafe { Arc::from_raw(target.declarations.cast::<DeclarationBlockData>()) };
assert_eq!(target.identity, identity);
assert_ne!(target.declaration_version, version);
assert!(!Arc::ptr_eq(&snapshot, &edited_snapshot));
drop(declarations);
+ drop(rule);
rust_rule_list_clear(&rules);
drop(source);
drop(rules);
assert!(source_lifetime.upgrade().is_none());
assert!(rule_lifetime.upgrade().is_none());
// The program reads its published snapshot, not a live document-local rule record.
- assert!(unsafe { native_rule_target(&mut engine, id.0 + 1, &mut target,) });
+ 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));
assert_eq!(target.identity, identity);
assert_eq!(target.source_identity, source_identity);
engine.remove_style_rule(id);
- assert!(!unsafe { native_rule_target(&mut engine, id.0 + 1, &mut target,) });
+ assert!(!native_rule_target(&mut engine, id.0 + 1, &mut target,));
drop(engine);
assert!(
snapshot
@@ -186,13 +187,13 @@ mod tests {
fn retained_rules_share_mutation_without_changing_parsed_snapshots() {
use crate::css::property_metadata::property_id;
let rules = rules(".文字 { width: 13px; height: 19px; }");
- let rule = unsafe { &*rust_rule_list_at(&rules, 0) };
+ let rule = &rules.rule_at(0);
let style = rule.style_rule();
let snapshot = style.declarations.data();
let fork = StyleRule::new(style.selectors(), style.declarations.data());
assert!(style.declarations.is_immutable());
assert!(fork.declarations.is_immutable());
- let retained_rule = unsafe { Rc::from_raw(crate::css::rule::rust_rule_retain(rule)) };
+ let retained_rule = Rc::clone(rule);
let retained = retained_rule.style_rule();
assert!(std::ptr::eq(style, retained));
let mut declarations = retained.declarations.clone();
diff --git a/Libraries/LibWeb/Rust/src/css/style_sheet.rs b/Libraries/LibWeb/Rust/src/css/style_sheet.rs
index b6bd6d2ddb5..8be8b51de6b 100644
--- a/Libraries/LibWeb/Rust/src/css/style_sheet.rs
+++ b/Libraries/LibWeb/Rust/src/css/style_sheet.rs
@@ -79,6 +79,19 @@ pub struct NativeStyleSheet {
}
impl NativeStyleSheet {
+ /// Attach a loaded sheet to the import rule `rule_identity` names, or remove the edge when
+ /// the rule is detached. The imported sheet must not transitively import this one.
+ pub(crate) fn set_import(&self, rule_identity: u64, imported: Option<Rc<NativeStyleSheet>>) {
+ match imported {
+ None => {
+ self.imports.borrow_mut().remove(&rule_identity);
+ }
+ Some(imported) => {
+ self.imports.borrow_mut().insert(rule_identity, imported);
+ }
+ }
+ }
+
pub(crate) fn identity(&self) -> u64 {
self.identity
}
@@ -479,15 +492,14 @@ pub unsafe extern "C" fn rust_style_sheet_set_import(
rule_identity: u64,
imported: *const NativeStyleSheet,
) {
- if imported.is_null() {
- sheet.imports.borrow_mut().remove(&rule_identity);
- } else {
- unsafe { Rc::increment_strong_count(imported) };
- sheet
- .imports
- .borrow_mut()
- .insert(rule_identity, unsafe { Rc::from_raw(imported) });
- }
+ let imported = (!imported.is_null()).then(|| {
+ // SAFETY: Guaranteed by the caller.
+ unsafe {
+ Rc::increment_strong_count(imported);
+ Rc::from_raw(imported)
+ }
+ });
+ sheet.set_import(rule_identity, imported);
}
#[cfg(test)]
@@ -656,7 +668,7 @@ mod tests {
use crate::css::media_list::rust_media_list_length;
use crate::css::parser::syntax_parser::{ParsedStyleSheet, parse_shared_stylesheet};
use crate::css::parser::value_parser::ParseContext;
- use crate::css::rule::{rust_rule_list_at, rust_rule_list_count, rust_rule_list_remove};
+ use crate::css::rule::{rust_rule_list_count, rust_rule_list_remove};
fn parse(source: &str) -> std::sync::Arc<ParsedStyleSheet> {
let units: Vec<_> = source.encode_utf16().collect();
@@ -918,10 +930,8 @@ mod tests {
let leaf_rule = identity(&leaf, 0);
let middle_rule = identity(&middle, 1);
let root_rule = identity(&root, 1);
- unsafe {
- rust_style_sheet_set_import(&root, root_import, Rc::as_ptr(&middle));
- rust_style_sheet_set_import(&middle, middle_import, Rc::as_ptr(&leaf));
- }
+ root.set_import(root_import, Some(middle.clone()));
+ middle.set_import(middle_import, Some(leaf.clone()));
let owners = crate::css::rule::RULE_OWNER_ALLOCATIONS.get();
let mut prefix = Vec::with_capacity(32);
prefix.extend("根".encode_utf16());
@@ -974,7 +984,7 @@ mod tests {
vec![entry(root_import, "根"), entry(root_rule, "根")]
);
set_media(&middle, "");
- unsafe { rust_style_sheet_set_import(&middle, middle_import, std::ptr::null()) };
+ middle.set_import(middle_import, None);
assert_eq!(
collect(FfiRuleTraversalOrder::Preorder),
vec![
@@ -993,14 +1003,12 @@ mod tests {
let root = sheet(&parse("@import 'middle.css' layer(外); @layer 末;"));
let middle = sheet(&parse("@import 'leaf.css' layer(中); @layer 隣;"));
let leaf = sheet(&parse("@layer 内;"));
- let root_import = unsafe { &*rust_rule_list_at(&root.rules, 0) };
- let middle_import = unsafe { &*rust_rule_list_at(&middle.rules, 0) };
+ let root_import = &root.rules.rule_at(0);
+ let middle_import = &middle.rules.rule_at(0);
let root_id = crate::css::rule::rust_rule_identity(root_import);
let middle_id = crate::css::rule::rust_rule_identity(middle_import);
- unsafe {
- rust_style_sheet_set_import(&middle, middle_id, Rc::as_ptr(&leaf));
- rust_style_sheet_set_import(&root, root_id, Rc::as_ptr(&middle));
- }
+ middle.set_import(middle_id, Some(leaf.clone()));
+ root.set_import(root_id, Some(middle.clone()));
let weak_middle = Rc::downgrade(&middle);
let weak_leaf = Rc::downgrade(&leaf);
drop(middle);
@@ -1009,10 +1017,10 @@ mod tests {
let middle = weak_middle.upgrade().unwrap();
let leaf = weak_leaf.upgrade().unwrap();
let replacement = sheet(&parse("@layer 替;"));
- unsafe { rust_style_sheet_set_import(&root, root_id, Rc::as_ptr(&replacement)) };
+ root.set_import(root_id, Some(replacement.clone()));
drop(replacement);
assert_layers(&root, &["根.外.替", "根.外", "根.末"]);
- unsafe { rust_style_sheet_set_import(&root, root_id, std::ptr::null()) };
+ root.set_import(root_id, None);
assert!(style_sheet_import(&root, root_id).is_null());
assert_layers(&root, &["根.外", "根.末"]);
assert_layers(&middle, &["根.中.内", "根.中", "根.隣"]);
@@ -1033,7 +1041,7 @@ mod tests {
let leaf = Rc::downgrade(&child);
for _ in 0..20_000 {
let parent = sheet(&parsed);
- let rule = unsafe { &*rust_rule_list_at(&parent.rules, 0) };
+ let rule = &parent.rules.rule_at(0);
parent
.imports
.borrow_mut()