Truly independent web browser
LibWeb: Hold the parsed rules of a style sheet in one table
Andreas Kling881bac90aeda
diff --git a/Libraries/LibWeb/Rust/src/css/parser/memory_tests.rs b/Libraries/LibWeb/Rust/src/css/parser/memory_tests.rsindex 5f57344e5f4..f8226fafb9b 100644--- a/Libraries/LibWeb/Rust/src/css/parser/memory_tests.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/memory_tests.rs@@ -179,8 +179,9 @@ fn parsed_sheet_bytes_per_unit() {Unit {name: "sheet, fixed",bytes: sheets,- // NB: The arena holds the sheet's `@namespace` declarations and the rank of its compounds.- ceiling: 928.0,+ // NB: The arena holds the sheet's `@namespace` declarations and the rank of its compounds. The sheet holds+ // its rules in four tables: all rules, the top-level ones, and the children and native children.+ ceiling: 976.0,typical: "about 600-1000 B",},Unit {diff --git a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rsindex be9775fff59..9dd5479b71e 100644--- a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs@@ -1523,7 +1523,8 @@ struct ParsedDeclarationList {}enum ParsedRuleChild {- Rule(Arc<ParsedRule>),+ /// A rule, by its index among the rules of the sheet.+ Rule(u32),/// Boxed, as most children are rules, which would otherwise each pay for a declaration list.Declarations(Box<ParsedDeclarationList>),}@@ -1646,20 +1647,20 @@ struct ParsedRule {has_source_position: bool,start_line: u32,start_column: u32,- /// None for a rule without child rules or declarations, as most style rules are.- children: Option<Box<ParsedRuleChildren>>,+ /// Where the children of the rule start among the children of the sheet, and how many there are. A rule without+ /// child rules or declarations, as most style rules are, has none there.+ first_child: u32,+ child_count: u32,+ /// Where the positions among its children of the rules the CSSOM sees start among the native children of the+ /// sheet, and how many there are.+ first_native_child: u32,+ native_child_count: u32,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]>,-}+const _: () = assert!(size_of::<ParsedRule>() == 56);/// 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@@ -1705,12 +1706,16 @@ enum ParsedRulePayload {}impl ParsedRule {- fn children(&self) -> &[ParsedRuleChild] {- self.children.as_ref().map_or(&[], |children| &children.children)+ /// Where the children of the rule are among the children of the sheet.+ fn child_range(&self) -> std::ops::Range<usize> {+ let first = self.first_child as usize;+ first..first + self.child_count as usize}- fn native_children(&self) -> &[u32] {- self.children.as_ref().map_or(&[], |children| &children.native_children)+ /// Where the positions of the rule's native children are among the native children of the sheet.+ fn native_child_range(&self) -> std::ops::Range<usize> {+ let first = self.first_native_child as usize;+ first..first + self.native_child_count as usize}fn source_position(&self) -> Option<(usize, usize)> {@@ -1888,7 +1893,14 @@ struct SyntaxParseBuilder<'a> {declarations: Vec<ParsedDeclaration>,// Declaration ranges are builder state; published lists retain their normalized blocks.declaration_ranges: Vec<std::ops::Range<usize>>,- rules: Vec<Arc<ParsedRule>>,+ /// Every rule that the parser ended, each after the rules in it.+ rules: Vec<ParsedRule>,+ /// The indices among `rules` of the rules of the sheet, in the order of the source.+ roots: Vec<u32>,+ /// The children of the rules that the parser ended: those of each rule are together.+ children: Vec<ParsedRuleChild>,+ /// For each rule that the parser ended, the positions among its children of the rules the CSSOM sees.+ native_children: Vec<u32>,items: Vec<ParsedRuleChild>,identity_count: u64,font_feature_values: Vec<u32>,@@ -2012,7 +2024,14 @@ pub struct ParsedStyleSheet {// Raw declarations remain only for root callbacks and diagnostics.declarations: Box<[ParsedDeclaration]>,root_declarations: Box<[u32]>,- rules: Box<[Arc<ParsedRule>]>,+ /// Every rule of the sheet, each after the rules in it.+ rules: Box<[ParsedRule]>,+ /// The indices among `rules` of the top-level rules, in the order of the source.+ roots: Box<[u32]>,+ /// The children of all rules: those of each rule are together.+ children: Box<[ParsedRuleChild]>,+ /// For each rule, the positions among its children of the rules the CSSOM sees.+ native_children: Box<[u32]>,items: Box<[ParsedRuleChild]>,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@@ -2034,13 +2053,40 @@ enum NestedDeclarationsKind {}impl ParsedStyleSheet {- /// About how many bytes the parse holds beside its text: its values, and a rule for each identity.+ /// About how many bytes the parse holds beside its text: its values, its rules and their children, and a list of+ /// declarations for each other identity.pub(super) fn bytes_kept_past_release(&self) -> usize {+ let declaration_lists = usize::try_from(self.identity_count)+ .expect("a parse fits in memory")+ .saturating_sub(self.rules.len());size_of::<Self>()+ size_of_val(&*self.values)+ size_of_val(&*self.declarations)+ + size_of_val(&*self.rules)+ + size_of_val(&*self.roots)+ + size_of_val(&*self.children)+ + size_of_val(&*self.native_children)+ size_of_val(&*self.items)- + usize::try_from(self.identity_count).expect("a parse fits in memory") * size_of::<ParsedRule>()+ + declaration_lists * size_of::<ParsedDeclarationList>()+ }++ /// The rule at `index` among the rules of the sheet.+ fn rule(&self, index: u32) -> &ParsedRule {+ &self.rules[index as usize]+ }++ /// The top-level rule at `position`, in the order of the source.+ fn root(&self, position: usize) -> &ParsedRule {+ self.rule(self.roots[position])+ }++ fn children_of(&self, rule: &ParsedRule) -> &[ParsedRuleChild] {+ &self.children[rule.child_range()]+ }++ /// The positions among the children of `rule` of the rules the CSSOM sees.+ fn native_children_of(&self, rule: &ParsedRule) -> &[u32] {+ &self.native_children[rule.native_child_range()]}pub(crate) fn identity_count(&self) -> u64 {@@ -2086,16 +2132,17 @@ impl ParsedStyleSheet {fn native_rule(self: &Arc<Self>,- rule: &Arc<ParsedRule>,+ index: u32,declarations_kind: NestedDeclarationsKind,list: &NativeRuleList,) -> Option<Rc<NativeRule>> {+ let rule = self.rule(index);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)));+ .filter(|_| kind != NativeRuleType::Style || !self.children_of(rule).is_empty())+ .map(|kind| list.parsed_children(ParsedRuleList::children(self.clone(), index, kind)));let position = rule.source_position().filter(|_| kind == NativeRuleType::Style);let payload = match kind {NativeRuleType::Style => RulePayload::Style(StyleRule::new(@@ -2165,7 +2212,7 @@ pub extern "C" fn rust_css_syntax_native_rules(parse: ArcRef<'_, ParsedStyleShee#[unsafe(no_mangle)]pub extern "C" fn rust_css_syntax_root_count(parse: &ParsedStyleSheet) -> usize {- parse.rules.len() + parse.items.len()+ parse.roots.len() + parse.items.len()}// These callbacks borrow the immutable parser result, without creating compatibility views.@@ -2541,6 +2588,15 @@ fn invalid_location_inner_name(rule: &Rule, rule_kind: ParsedRuleKind, outer_nam}impl<'a> SyntaxParseBuilder<'a> {+ /// The rule at `index` among the rules that the parser ended.+ fn rule(&self, index: u32) -> &ParsedRule {+ &self.rules[index as usize]+ }++ fn children_of(&self, rule: &ParsedRule) -> &[ParsedRuleChild] {+ &self.children[rule.child_range()]+ }+fn collect_declaration_errors(&self) -> Box<[usize]> {fn visit_item(sheet: &SyntaxParseBuilder<'_>, item: &ParsedRuleChild, errors: &mut Vec<usize>) {match item {@@ -2554,11 +2610,12 @@ impl<'a> SyntaxParseBuilder<'a> {}}}- ParsedRuleChild::Rule(rule) => {+ &ParsedRuleChild::Rule(rule) => {+ let rule = sheet.rule(rule);if rule.is_qualified && rule.selector_list().is_none() {return;}- for child in rule.children() {+ for child in sheet.children_of(rule) {visit_item(sheet, child, errors);}}@@ -2576,16 +2633,16 @@ impl<'a> SyntaxParseBuilder<'a> {| ParsedRuleKind::Page => {}_ => return,}- for child in rule.children() {+ for child in sheet.children_of(rule) {match child {ParsedRuleChild::Declarations(_) => visit_item(sheet, child, errors),- ParsedRuleChild::Rule(rule) => visit_rule(sheet, rule, errors),+ &ParsedRuleChild::Rule(rule) => visit_rule(sheet, sheet.rule(rule), errors),}}}let mut errors = Vec::new();- for rule in &self.rules {- visit_rule(self, rule, &mut errors);+ for &root in &self.roots {+ visit_rule(self, self.rule(root), &mut errors);}for item in &self.items {visit_item(self, item, &mut errors);@@ -2646,6 +2703,9 @@ impl<'a> SyntaxParseBuilder<'a> {declarations: declarations.into_boxed_slice(),root_declarations: narrow(root_declarations),rules: self.rules.into_boxed_slice(),+ roots: self.roots.into_boxed_slice(),+ children: self.children.into_boxed_slice(),+ native_children: self.native_children.into_boxed_slice(),items: self.items.into_boxed_slice(),native_roots: Box::default(),media_holding_roots: Box::default(),@@ -2654,21 +2714,30 @@ impl<'a> SyntaxParseBuilder<'a> {};parsed.native_roots = if parsed.items.is_empty() {parsed- .rules+ .roots.iter().enumerate()- .filter_map(|(index, rule)| rule.native_type().map(|_| shared_rules::narrow_index(index)))+ .filter_map(|(position, &index)| {+ parsed+ .rule(index)+ .native_type()+ .map(|_| shared_rules::narrow_index(position))+ }).collect()} else {- shared_rules::native_child_indices(&parsed.items, None)+ shared_rules::native_child_indices(&parsed.rules, &parsed.items, None).collect()};parsed.media_holding_roots = (0..parsed.native_roots.len()).filter(|&position| {let index = parsed.native_roots[position] as usize;if parsed.items.is_empty() {- parsed.rules[index].holds_media_rules()+ parsed.root(index).holds_media_rules(&parsed)} else {- matches!(&parsed.items[index], ParsedRuleChild::Rule(rule) if rule.holds_media_rules())+ let rule = match parsed.items[index] {+ ParsedRuleChild::Rule(rule) => parsed.rule(rule),+ ParsedRuleChild::Declarations(_) => return false,+ };+ rule.holds_media_rules(&parsed)}}).map(shared_rules::narrow_index)@@ -2694,6 +2763,9 @@ impl<'a> SyntaxParseBuilder<'a> {declarations: Vec::new(),declaration_ranges: Vec::new(),rules: Vec::new(),+ roots: Vec::new(),+ children: Vec::new(),+ native_children: Vec::new(),items: Vec::new(),identity_count: 0,font_feature_values: Vec::new(),@@ -3259,18 +3331,23 @@ impl<'a> SyntaxParseBuilder<'a> {/// Ends the rule that is open, and makes it a child of the rule it is in, or a rule of the sheet.fn end_rule(&mut self) {let open = self.open_rules.pop().expect("a rule is open");- let children: Box<[ParsedRuleChild]> = self.open_children.drain(open.first_child..).collect();+ // NB: The children of the rule move to the end of the children of the sheet, where they stay together.+ let first_child = self.children.len();+ self.children.extend(self.open_children.drain(open.first_child..));self.nesting.set(Some(open.outer_nesting));self.parent.set(Some(open.outer_parent));- let parsed = self.finish_rule(&open, children);+ let parsed = self.finish_rule(&open, first_child..self.children.len());+ let index = shared_rules::narrow_index(self.rules.len());+ self.rules.push(parsed);if self.open_rules.is_empty() && !self.roots_are_items {- self.append_root(&open.rule, parsed);+ self.append_root(&open.rule, index);} else {- self.open_children.push(ParsedRuleChild::Rule(parsed));+ self.open_children.push(ParsedRuleChild::Rule(index));}}- fn finish_rule(&mut self, open: &OpenRule, children: Box<[ParsedRuleChild]>) -> Arc<ParsedRule> {+ /// Makes the rule `open` is, whose children are at `children` among the children of the sheet.+ fn finish_rule(&mut self, open: &OpenRule, children: std::ops::Range<usize>) -> ParsedRule {let rule = &open.rule;let original_rule_kind = open.original_rule_kind;let (is_qualified, name, has_block, source_position) = match rule {@@ -3280,7 +3357,7 @@ impl<'a> SyntaxParseBuilder<'a> {let (declarations_start, declaration_count) = (open.declarations_start, open.declaration_count);let selector_list = open.selector_list.clone();let outer_parent = open.outer_parent;- let descriptor_block = Self::rule_descriptors(&children, original_rule_kind);+ let descriptor_block = Self::rule_descriptors(&self.children[children.clone()], original_rule_kind);let parse_context = self.parse_context;let declared_namespaces = self.declared_namespaces@@ -3364,16 +3441,17 @@ impl<'a> SyntaxParseBuilder<'a> {families: names.iter().map(|name| CssString::from_utf16(name)).collect(),..Default::default()};- for child in &children {+ for child in &self.children[children.clone()] {// FIXME: Handle the font-display descriptor here, see// https://drafts.csswg.org/css-fonts-4/#font-display-font-feature-values- let ParsedRuleChild::Rule(child) = child else {+ let &ParsedRuleChild::Rule(child) = child else {continue;};+ let child = self.rule(child);let ParsedRulePayload::FontFeatureValuesRule(kind) = child.payload else {continue;};- for item in child.children() {+ for item in self.children_of(child) {let ParsedRuleChild::Declarations(item) = item else {continue;};@@ -3500,7 +3578,7 @@ impl<'a> SyntaxParseBuilder<'a> {!qualified_rule.prelude_is_selector,);if !qualified_rule.prelude_is_selector {- for item in &children {+ for item in &self.children[children.clone()] {if let ParsedRuleChild::Declarations(item) = item {let range = &self.declaration_ranges[item.local_identity as usize];self.append_declaration_block(&mut block, range.start, range.len(), true);@@ -3522,12 +3600,12 @@ impl<'a> SyntaxParseBuilder<'a> {Some(block)}} else if matches!(rule_kind, ParsedRuleKind::Margin | ParsedRuleKind::PositionTry) {- Some(declaration_block_from_blocks(children.iter().filter_map(- |item| match item {+ Some(declaration_block_from_blocks(+ self.children[children.clone()].iter().filter_map(|item| match item {ParsedRuleChild::Declarations(item) => item.declaration_block.as_ref(),ParsedRuleChild::Rule(_) => None,- },- )))+ }),+ ))} else {None};@@ -3553,11 +3631,15 @@ impl<'a> SyntaxParseBuilder<'a> {} else {None};- let native_children = if keyframe.is_some() {- Box::default()- } else {- shared_rules::native_child_indices(&children, Some(rule_kind))- };+ let first_native_child = self.native_children.len();+ if keyframe.is_none() {+ self.native_children.extend(shared_rules::native_child_indices(+ &self.rules,+ &self.children[children.clone()],+ Some(rule_kind),+ ));+ }+ let native_child_count = self.native_children.len() - first_native_child;// NB: A rule's prelude, or its kind, gives it one payload at most.let payload = if let Some(keyframe) = keyframe {ParsedRulePayload::Keyframe(keyframe)@@ -3621,7 +3703,7 @@ impl<'a> SyntaxParseBuilder<'a> {ParsedRulePayload::None};let narrow = |value: usize| u32::try_from(value).expect("style sheet text exceeds u32");- Arc::new(ParsedRule {+ ParsedRule {local_identity: u32::try_from(self.next_identity()).expect("style sheet has too many rules"),is_qualified,rule_kind,@@ -3629,19 +3711,19 @@ impl<'a> SyntaxParseBuilder<'a> {has_source_position: source_position.is_some(),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,- })- }),+ first_child: shared_rules::narrow_index(children.start),+ child_count: shared_rules::narrow_index(children.len()),+ first_native_child: shared_rules::narrow_index(first_native_child),+ native_child_count: shared_rules::narrow_index(native_child_count),payload,- })+ }}- fn append_root(&mut self, rule: &Rule, mut parsed: Arc<ParsedRule>) {+ /// Makes the rule at `index` among the rules a rule of the sheet.+ fn append_root(&mut self, rule: &Rule, index: u32) {// NB: Invalid rules do not close either ordering window, and statement @layer rules do not// close the import or namespace window.+ let parsed = &self.rules[index as usize];let rule_kind = parsed.rule_kind;match rule_kind {ParsedRuleKind::Invalid | ParsedRuleKind::Unknown | ParsedRuleKind::IgnoredVendor => {}@@ -3658,11 +3740,11 @@ impl<'a> SyntaxParseBuilder<'a> {FfiSyntaxDiagnosticCode::MisplacedImport,prelude.as_ref(),);- Arc::get_mut(&mut parsed).unwrap().rule_kind = ParsedRuleKind::Invalid;+ self.rules[index as usize].rule_kind = ParsedRuleKind::Invalid;}ParsedRuleKind::Namespace if self.namespace_rules_valid => {self.import_rules_valid = false;- let namespace = parsed.namespace_rule().unwrap();+ let namespace = self.rules[index as usize].namespace_rule().unwrap();self.selectors.borrow_mut().declare_namespace(namespace.prefix.units(), namespace.uri.units());@@ -3687,14 +3769,14 @@ impl<'a> SyntaxParseBuilder<'a> {FfiSyntaxDiagnosticCode::MisplacedNamespace,prelude.as_ref(),);- Arc::get_mut(&mut parsed).unwrap().rule_kind = ParsedRuleKind::Invalid;+ self.rules[index as usize].rule_kind = ParsedRuleKind::Invalid;}_ => {self.import_rules_valid = false;self.namespace_rules_valid = false;}}- self.rules.push(parsed);+ self.roots.push(index);}}@@ -4192,7 +4274,8 @@ mod tests {fn consumers_can_retain_the_same_parsed_value_independently() {let parse = parse_test_stylesheet(b"a { width: 13.25px }");let pointer = crate::css::style_value_arc::StyleValueArc::as_ptr(- &parse.rules[0]+ &parse+ .root(0).declaration_block().unwrap().properties()@@ -4248,7 +4331,11 @@ mod tests {b"undeclared|element {} @font-face serif {} @import url('data:text/css,'); \@namespace known 'urn:known'; known|element {}",);- let root_kinds = parse.rules.iter().map(|rule| rule.rule_kind).collect::<Vec<_>>();+ let root_kinds = parse+ .roots+ .iter()+ .map(|&index| parse.rule(index).rule_kind)+ .collect::<Vec<_>>();assert_eq!(root_kinds,vec![@@ -4273,8 +4360,8 @@ mod tests {);let parse = parse_test_stylesheet(b"element {} @import url('data:text/css,'); @namespace late 'urn:late';");- assert_eq!(parse.rules[1].rule_kind, ParsedRuleKind::Invalid);- assert_eq!(parse.rules[2].rule_kind, ParsedRuleKind::Invalid);+ assert_eq!(parse.root(1).rule_kind, ParsedRuleKind::Invalid);+ assert_eq!(parse.root(2).rule_kind, ParsedRuleKind::Invalid);assert!(parse.diagnostics@@ -4296,7 +4383,11 @@ mod tests {let parse = parse_test_stylesheet(b"@styleset {} @import url('data:text/css,'); @namespace known 'urn:known'; known|element {}",);- let root_kinds = parse.rules.iter().map(|rule| rule.rule_kind).collect::<Vec<_>>();+ let root_kinds = parse+ .roots+ .iter()+ .map(|&index| parse.rule(index).rule_kind)+ .collect::<Vec<_>>();assert_eq!(root_kinds,vec![@@ -4308,15 +4399,15 @@ 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.children_of(parse.root(0))[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 {+ assert_eq!(parse.rule(media_child).rule_kind, ParsedRuleKind::Invalid);+ let ParsedRuleChild::Rule(font_feature_values_child) = parse.children_of(parse.root(1))[0] else {panic!("expected rule")};assert_eq!(- font_feature_values_child.rule_kind,+ parse.rule(font_feature_values_child).rule_kind,ParsedRuleKind::FontFeatureValuesRule);}@@ -4325,11 +4416,11 @@ mod tests {fn validates_nested_rule_contexts_without_flattening_them() {let parse = parse_test_stylesheet(b"a { @layer direct; } @scope { @layer scoped; }");let layer_rules = parse- .rules+ .roots.iter()- .flat_map(|rule| rule.children().iter())- .filter_map(|child| match child {- ParsedRuleChild::Rule(rule) => Some(rule),+ .flat_map(|&index| parse.children_of(parse.rule(index)))+ .filter_map(|child| match *child {+ ParsedRuleChild::Rule(rule) => Some(parse.rule(rule)),_ => None,}).filter(|rule| matches!(rule.rule_kind, ParsedRuleKind::Invalid | ParsedRuleKind::Layer))@@ -4364,7 +4455,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().unwrap().descriptors;+ let descriptors = &sheet.root(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.rsindex 5b3416ca1f6..3386d9de8ee 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@@ -33,7 +33,7 @@ fn declarations(source: &str) -> crate::css::declaration_block::DeclarationBlock}fn first_rule_block(sheet: &ParsedStyleSheet) -> &crate::css::declaration_block::SharedDeclarationBlock {- sheet.rules[0].declaration_block().unwrap()+ sheet.root(0).declaration_block().unwrap()}fn first_value(block: &crate::css::declaration_block::DeclarationBlock) -> Vec<u16> {@@ -71,8 +71,8 @@ fn parse_shared_on_worker(source: &'static str) -> Arc<ParsedStyleSheet> {#[test]fn style_rule_mutation_forks_current_selectors_and_declarations() {let sheet = parse_shared_on_worker(".親 { width: 13px; --色: 緑; }");- assert_eq!(sheet.rules.len(), 1);- let parsed = &sheet.rules[0];+ assert_eq!(sheet.roots.len(), 1);+ let parsed = sheet.root(0);let rule = StyleRule::new(parsed.selector_list().cloned().unwrap(),parsed.declaration_block().cloned().unwrap(),@@ -122,8 +122,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().cloned().unwrap());- let other = FfiCounterStyle::new(sheet.rules[1].counter_style().cloned().unwrap());+ let rule = FfiCounterStyle::new(sheet.root(0).counter_style().cloned().unwrap());+ let other = FfiCounterStyle::new(sheet.root(1).counter_style().cloned().unwrap());drop(sheet);assert_eq!(rule.name().units(), utf16("初"));unsafe {@@ -175,7 +175,7 @@ fn font_feature_mutation_preserves_live_owners_and_shared_maps() {let sheet = parse_shared_on_worker("@font-feature-values 色 { @styleset { first: 1 2; 色: 3; first: 4; invalid: -1; } @styleset { second: 5; 色: 6 7; } @character-variant { cv: 8 9; bad: 1 2 3; } @annotation { a: 10; } @ornaments { o: 11; } @stylistic { s: 12; } @swash { w: 13; } @historical-forms { h: 14; } }",);- assert_eq!(sheet.rules.len(), 1);+ assert_eq!(sheet.roots.len(), 1);let rules = NativeRuleList::from_parsed(sheet);let rule = rules.rule_at(0);let RulePayload::FontFeatureValues(values) = &rule.payload else {@@ -260,10 +260,10 @@ 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.children_of(sheet.root(0))[0] else {unreachable!()};- let data = first.keyframe().unwrap();+ let data = sheet.rule(first).keyframe().unwrap();assert_eq!(&*data.keys, [0.0, 50.0]);assert_eq!(data.declarations.properties().len(), 1);assert_eq!(@@ -353,9 +353,10 @@ fn worker_block_merging_and_shorthand_expansion_only_use_thread_safe_callbacks()&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.children_of(sheet.root(0))[0] else {panic!()};+ let margin = sheet.rule(margin);assert_eq!(margin.rule_kind, ParsedRuleKind::Margin);let margin = margin.declaration_block().cloned().unwrap();drop(sheet);@@ -363,7 +364,7 @@ fn worker_block_merging_and_shorthand_expansion_only_use_thread_safe_callbacks()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().cloned().unwrap();+ let expanded = sheet.root(0).declaration_block().cloned().unwrap();drop(sheet);assert_eq!(expanded.properties().len(), 5);assert_eq!(expanded.properties().get(0).unwrap().property_id, property_id::MARGIN);@@ -473,10 +474,15 @@ fn worker_selector_normalization_survives_publication() {let selector = unsafe { Box::from_raw(rust_parsed_selector_list_selector(parsed, 0)) };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() {- if let ParsedRuleChild::Rule(child) = child {- visit(child, selectors, scopes);+ fn visit(+ sheet: &ParsedStyleSheet,+ rule: &super::ParsedRule,+ selectors: &mut Vec<Vec<u16>>,+ scopes: &mut Vec<Vec<u16>>,+ ) {+ for child in sheet.children_of(rule) {+ if let &ParsedRuleChild::Rule(child) = child {+ visit(sheet, sheet.rule(child), selectors, scopes);}}if let Some(parsed) = rule.selector_list() {@@ -493,8 +499,8 @@ fn worker_selector_normalization_survives_publication() {);let mut selectors = Vec::new();let mut scopes = Vec::new();- for rule in &sheet.rules {- visit(rule, &mut selectors, &mut scopes);+ for &root in &sheet.roots {+ visit(&sheet, sheet.rule(root), &mut selectors, &mut scopes);}drop(sheet);assert_eq!(@@ -519,11 +525,11 @@ fn import_preludes_outlive_the_worker_and_shared_sheet() {let sheet = parse_shared_on_worker("@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().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();+ assert_eq!(sheet.roots.len(), 4);+ let named = sheet.root(0).import_rule().cloned().unwrap();+ let anonymous = sheet.root(1).import_rule().cloned().unwrap();+ let unlayered = sheet.root(2).import_rule().cloned().unwrap();+ let supports = sheet.root(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());@@ -549,9 +555,9 @@ fn page_text(selectors: &PageSelectorList) -> Vec<u16> {#[test]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().cloned().unwrap();- let empty = sheet.rules[1].page_selector_list().cloned().unwrap();+ assert_eq!(sheet.roots.len(), 2);+ let selectors = sheet.root(0).page_selector_list().cloned().unwrap();+ let empty = sheet.root(1).page_selector_list().cloned().unwrap();drop(sheet);assert_eq!(selectors.selectors.len(), 2);assert_eq!(page_text(&selectors), utf16("雪:left:first, :blank"));@@ -576,9 +582,9 @@ fn function_signatures_own_parameters_after_the_sheet_is_dropped() {let sheet = parse_shared_on_worker("@function --幅(--長さ <length>: 8px, --名: '雪', --未) returns <length> { result: var(--長さ); } @function --空() {}",);- assert_eq!(sheet.rules.len(), 2);- let signature = sheet.rules[0].function_signature().cloned().unwrap();- let empty = sheet.rules[1].function_signature().cloned().unwrap();+ assert_eq!(sheet.roots.len(), 2);+ let signature = sheet.root(0).function_signature().cloned().unwrap();+ let empty = sheet.root(1).function_signature().cloned().unwrap();drop(sheet);assert_eq!(signature.name.units(), utf16("--幅"));assert_eq!(signature.parameters.len(), 3);@@ -602,9 +608,9 @@ fn property_rules_own_syntax_and_initial_values_after_the_sheet_is_dropped() {let sheet = parse_shared_on_worker("@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().cloned().unwrap();- let universal = sheet.rules[1].property_rule().cloned().unwrap();+ assert_eq!(sheet.roots.len(), 2);+ let typed = sheet.root(0).property_rule().cloned().unwrap();+ let universal = sheet.root(1).property_rule().cloned().unwrap();drop(sheet);assert_eq!(typed.name.units(), utf16("--色"));assert_eq!(typed.syntax_source.units(), utf16("<length>"));@@ -623,10 +629,10 @@ fn property_rules_own_syntax_and_initial_values_after_the_sheet_is_dropped() {#[test]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().cloned().unwrap();- let prefixed = sheet.rules[1].namespace_rule().cloned().unwrap();+ assert_eq!(sheet.roots.len(), 3);+ assert!(sheet.root(2).selector_list().is_some());+ let default = sheet.root(0).namespace_rule().cloned().unwrap();+ let prefixed = sheet.root(1).namespace_rule().cloned().unwrap();drop(sheet);assert!(default.prefix.units().is_empty());assert!(default.uri.units().is_empty());@@ -759,9 +765,9 @@ fn retained_values_do_not_keep_the_sheet_in_the_cache() {#[test]fn published_sheet_owns_non_ascii_declarations() {let sheet = parse_shared_on_worker(".é😀 { width: 13px; --é😀: value }");- assert_eq!(sheet.rules.len(), 1);+ assert_eq!(sheet.roots.len(), 1);assert!(sheet.declarations.is_empty());- assert!(sheet.rules[0].selector_list().is_some());+ assert!(sheet.root(0).selector_list().is_some());assert_eq!(first_rule_block(&sheet).custom_properties()@@ -794,24 +800,27 @@ fn independent_workers_read_the_same_immutable_graph() {&expected_value));assert_eq!(serialize_style_value_to_utf16(&expected_value), utf16("13px"));- assert_eq!(sheet.rules.len(), 4);+ assert_eq!(sheet.roots.len(), 4);assert_eq!(- rust_parsed_selector_list_length(sheet.rules[0].selector_list().unwrap()),+ rust_parsed_selector_list_length(sheet.root(0).selector_list().unwrap()),1);assert_eq!(- css_query_evaluate_supports(sheet.rules[1].supports_condition().map(|value| &**value)),+ css_query_evaluate_supports(sheet.root(1).supports_condition().map(|value| &**value)),1);- let ParsedRuleChild::Rule(nested) = &sheet.rules[1].children()[0] else {+ let ParsedRuleChild::Rule(nested) = sheet.children_of(sheet.root(1))[0] else {panic!()};- assert_eq!(rust_parsed_selector_list_length(nested.selector_list().unwrap()), 1);assert_eq!(- *sheet.rules[2].property_rule().unwrap().syntax,+ rust_parsed_selector_list_length(sheet.rule(nested).selector_list().unwrap()),+ 1+ );+ assert_eq!(+ *sheet.root(2).property_rule().unwrap().syntax,SyntaxNode::Type(SyntaxType::Length));- assert_eq!(sheet.rules[3].page_selector_list().unwrap().selectors.len(), 1);+ assert_eq!(sheet.root(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);@@ -828,11 +837,11 @@ fn scope_presence_and_native_selector_names_survive_worker_exit() {let sheet = parse_shared_on_worker("@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());- let scopes: Vec<_> = sheet.rules[1..]+ assert_eq!(sheet.roots.len(), 5);+ assert!(sheet.root(0).scope_selectors().is_none());+ let scopes: Vec<_> = sheet.roots[1..].iter()- .map(|rule| rule.scope_selectors().cloned().unwrap())+ .map(|&index| sheet.rule(index).scope_selectors().cloned().unwrap()).collect();drop(sheet);for (index, scope) in scopes.iter().enumerate() {@@ -862,32 +871,35 @@ fn shared_rule_tree_preserves_nested_declaration_lists() {let sheet = parse_shared_on_worker("@media all { .a { width: 1px; @supports (display: grid) { width: 2px; .b { width: 3px; } height: 4px; } color: red; } } .c { width: 5px; }",);- assert_eq!(sheet.rules.len(), 2);- let media = sheet.rules[0].clone();- let last = sheet.rules[1].clone();- drop(sheet);+ assert_eq!(sheet.roots.len(), 2);+ let media = sheet.root(0);+ let last = sheet.root(1);assert_eq!(media.rule_kind, ParsedRuleKind::Media);- assert_eq!(media.children().len(), 1);- let ParsedRuleChild::Rule(style) = &media.children()[0] else {+ assert_eq!(sheet.children_of(media).len(), 1);+ let ParsedRuleChild::Rule(style) = sheet.children_of(media)[0] else {panic!()};+ let style = sheet.rule(style);assert!(style.selector_list().is_some());- assert_eq!(style.children().len(), 2);- let ParsedRuleChild::Rule(supports) = &style.children()[0] else {+ let style_children = sheet.children_of(style);+ assert_eq!(style_children.len(), 2);+ let ParsedRuleChild::Rule(supports) = style_children[0] else {panic!()};+ let supports = sheet.rule(supports);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]] {+ let supports_children = sheet.children_of(supports);+ 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!(sheet.rule(nested).selector_list().is_some());assert!(last.selector_list().is_some());}@@ -896,8 +908,8 @@ fn container_conditions_own_names_and_queries_after_the_sheet_is_dropped() {use crate::css::parser::query_parser::css_query_serialize_condition;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().cloned().unwrap();+ assert_eq!(sheet.roots.len(), 1);+ let conditions = sheet.root(0).container_conditions().cloned().unwrap();drop(sheet);let entries = &conditions.conditions;assert_eq!(entries.len(), 3);@@ -921,10 +933,10 @@ fn container_conditions_own_names_and_queries_after_the_sheet_is_dropped() {#[test]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().cloned().unwrap();- let block = sheet.rules[1].layer_names().cloned().unwrap();- let anonymous = sheet.rules[2].layer_names().cloned().unwrap();+ assert_eq!(sheet.roots.len(), 3);+ let statement = sheet.root(0).layer_names().cloned().unwrap();+ let block = sheet.root(1).layer_names().cloned().unwrap();+ let anonymous = sheet.root(2).layer_names().cloned().unwrap();drop(sheet);assert_eq!(statement.names.len(), 2);assert_eq!(statement.names[0].units(), utf16("色.子"));@@ -962,7 +974,7 @@ 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().cloned().unwrap();+ let descriptors = sheet.root(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 {@@ -1050,10 +1062,10 @@ 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().cloned().unwrap();+ let original = first.root(0).declaration_block().cloned().unwrap();assert!(SharedDeclarationBlock::ptr_eq(&original,- second.rules[0].declaration_block().unwrap()+ second.root(0).declaration_block().unwrap()));let mut changed = DeclarationBlock::new(original.clone());let independent = DeclarationBlock::new(original.clone());@@ -1068,7 +1080,7 @@ fn declaration_mutation_does_not_change_cached_or_nested_shared_blocks() {let third = parse(&source, &context);assert!(SharedDeclarationBlock::ptr_eq(&original,- third.rules[0].declaration_block().unwrap()+ third.root(0).declaration_block().unwrap()));drop((first, second, third, original));assert_eq!(@@ -1081,8 +1093,8 @@ fn declaration_mutation_does_not_change_cached_or_nested_shared_blocks() {);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.children_of(nested.root(0)).len(), 2);+ let ParsedRuleChild::Declarations(list) = &nested.children_of(nested.root(0))[1] else {panic!()};let original = list.declaration_block.clone().unwrap();@@ -1107,9 +1119,9 @@ fn media_mutation_preserves_live_owners_and_shared_snapshots() {text}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().cloned().unwrap());- let media = MediaList::new(sheet.rules[1].media_list().cloned().unwrap());+ assert_eq!(sheet.roots.len(), 2);+ let imported = MediaList::new(sheet.root(0).media_list().cloned().unwrap());+ let media = MediaList::new(sheet.root(1).media_list().cloned().unwrap());drop(sheet);assert_eq!(text(&imported), utf16("screen, écran"));assert_eq!(text(&media), utf16("all, print"));@@ -1210,10 +1222,10 @@ fn descriptor_mutation_forks_worker_parsed_data() {let sheet = parse_shared_on_worker("@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().cloned().unwrap());- let shared = FfiDescriptorBlock::new(sheet.rules[0].descriptor_block().cloned().unwrap());- let font = sheet.rules[1].descriptor_block().cloned().unwrap();+ assert_eq!(sheet.roots.len(), 2);+ let mut page = FfiDescriptorBlock::new(sheet.root(0).descriptor_block().cloned().unwrap());+ let shared = FfiDescriptorBlock::new(sheet.root(0).descriptor_block().cloned().unwrap());+ let font = sheet.root(1).descriptor_block().cloned().unwrap();drop(sheet);let data = page.data();assert_eq!(data.descriptors.len(), 2);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.rsindex aa268de27a5..f8f1dad1927 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@@ -31,8 +31,13 @@ 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!(+/// The positions among `children` of the rules the CSSOM sees, where the rules of `children` are indices among `rules`.+pub(super) fn native_child_indices<'a>(+ rules: &'a [ParsedRule],+ children: &'a [ParsedRuleChild],+ parent: Option<ParsedRuleKind>,+) -> impl Iterator<Item = u32> + 'a {+ let has_native_children = matches!(parent,None | Some(ParsedRuleKind::Qualified@@ -45,32 +50,29 @@ pub(super) fn native_child_indices(children: &[ParsedRuleChild], parent: Option<| ParsedRuleKind::Page| ParsedRuleKind::Keyframes)- ) {- return Box::default();- }- children- .iter()- .enumerate()- .filter_map(|(index, child)| {- let kind = match child {- ParsedRuleChild::Rule(rule) => rule.native_type()?,- ParsedRuleChild::Declarations(_) => NativeRuleType::NestedDeclarations,- };- if (parent == Some(ParsedRuleKind::Page) && kind != NativeRuleType::Margin)- || (parent == Some(ParsedRuleKind::Keyframes) && kind != NativeRuleType::Keyframe)- {- return None;- }- Some(narrow_index(index))- })- .collect()+ );+ let children = if has_native_children { children } else { &[] };+ children.iter().enumerate().filter_map(move |(index, child)| {+ let kind = match child {+ &ParsedRuleChild::Rule(rule) => rules[rule as usize].native_type()?,+ ParsedRuleChild::Declarations(_) => NativeRuleType::NestedDeclarations,+ };+ if (parent == Some(ParsedRuleKind::Page) && kind != NativeRuleType::Margin)+ || (parent == Some(ParsedRuleKind::Keyframes) && kind != NativeRuleType::Keyframe)+ {+ return None;+ }+ Some(narrow_index(index))+ })}// An immutable list projection retains the original graph, not copies of its rules.#[derive(Clone)]pub(crate) struct ParsedRuleList {sheet: Arc<ParsedStyleSheet>,- parent: Option<(Arc<ParsedRule>, NestedDeclarationsKind)>,+ /// The index among the rules of the sheet of the rule whose children the list is, or none for the top-level+ /// rules of the sheet.+ parent: Option<(u32, NestedDeclarationsKind)>,}impl ParsedRuleList {@@ -84,7 +86,7 @@ impl ParsedRuleList {pub(super) fn children(sheet: Arc<ParsedStyleSheet>,- parent: Arc<ParsedRule>,+ parent: u32,declarations_kind: NestedDeclarationsKind,) -> Self {Self {@@ -119,24 +121,25 @@ impl ParsedRuleList {}pub(crate) fn len(&self) -> usize {- self.parent- .as_ref()- .map_or(self.sheet.native_roots.len(), |(parent, _)| {- parent.native_children().len()- })+ self.parent.map_or(self.sheet.native_roots.len(), |(parent, _)| {+ self.sheet.native_children_of(self.sheet.rule(parent)).len()+ })}pub(crate) fn rule_at(&self, index: usize) -> SharedRule<'_> {- match &self.parent {+ let sheet = &*self.sheet;+ match self.parent {Some((parent, kind)) => {- SharedRule::from_child(&parent.children()[parent.native_children()[index] as usize], *kind).unwrap()+ let parent = sheet.rule(parent);+ let position = sheet.native_children_of(parent)[index] as usize;+ SharedRule::from_child(sheet, &sheet.children_of(parent)[position], kind).unwrap()}None => {- 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()+ let index = sheet.native_roots[index] as usize;+ if sheet.items.is_empty() {+ SharedRule::from_rule(sheet, sheet.roots[index], sheet.declarations_kind).unwrap()} else {- SharedRule::from_child(&self.sheet.items[index], self.sheet.declarations_kind).unwrap()+ SharedRule::from_child(sheet, &sheet.items[index], sheet.declarations_kind).unwrap()}}}@@ -149,7 +152,10 @@ impl ParsedRuleList {) -> std::rc::Rc<crate::css::rule::NativeRule> {let rule = self.rule_at(index);match rule.data {- SharedRuleData::Rule(parsed) => self.sheet.native_rule(parsed, rule.declarations_kind, list).unwrap(),+ SharedRuleData::Rule(_, rule_index) => self+ .sheet+ .native_rule(rule_index, rule.declarations_kind, list)+ .unwrap(),SharedRuleData::Declarations(declarations) => {self.sheet.native_declarations(declarations, rule.declarations_kind, list)@@ -160,7 +166,8 @@ impl ParsedRuleList {#[derive(Clone, Copy)]enum SharedRuleData<'a> {- Rule(&'a Arc<ParsedRule>),+ /// A rule of the sheet, by its index among the rules of the sheet.+ Rule(&'a ParsedStyleSheet, u32),Declarations(&'a ParsedDeclarationList),}@@ -222,27 +229,31 @@ impl ParsedRule {impl ParsedRule {/// Whether the rule is, or holds, a rule a media evaluation reads: a `@media` rule, or an `@import`, whose sheet/// may hold one.- pub(super) fn holds_media_rules(&self) -> bool {+ pub(super) fn holds_media_rules(&self, sheet: &ParsedStyleSheet) -> bool {matches!(self.rule_kind, ParsedRuleKind::Media | ParsedRuleKind::Import)- || self- .children()+ || sheet+ .children_of(self).iter()- .any(|child| matches!(child, ParsedRuleChild::Rule(rule) if rule.holds_media_rules()))+ .any(|child| matches!(*child, ParsedRuleChild::Rule(rule) if sheet.rule(rule).holds_media_rules(sheet)))}}impl<'a> SharedRule<'a> {- fn from_rule(rule: &'a Arc<ParsedRule>, declarations_kind: NestedDeclarationsKind) -> Option<Self> {+ fn from_rule(sheet: &'a ParsedStyleSheet, index: u32, declarations_kind: NestedDeclarationsKind) -> Option<Self> {Some(Self {- data: SharedRuleData::Rule(rule),+ data: SharedRuleData::Rule(sheet, index),declarations_kind,- rule_type: rule.native_type()?,+ rule_type: sheet.rule(index).native_type()?,})}- fn from_child(child: &'a ParsedRuleChild, declarations_kind: NestedDeclarationsKind) -> Option<Self> {+ fn from_child(+ sheet: &'a ParsedStyleSheet,+ child: &'a ParsedRuleChild,+ declarations_kind: NestedDeclarationsKind,+ ) -> Option<Self> {match child {- ParsedRuleChild::Rule(rule) => Self::from_rule(rule, declarations_kind),+ &ParsedRuleChild::Rule(index) => Self::from_rule(sheet, index, declarations_kind),ParsedRuleChild::Declarations(declarations) => Some(Self {data: SharedRuleData::Declarations(declarations),declarations_kind,@@ -254,98 +265,84 @@ impl<'a> SharedRule<'a> {}}+ /// The parsed rule this is, unless it is a list of declarations.+ fn parsed(self) -> Option<&'a ParsedRule> {+ match self.data {+ SharedRuleData::Rule(sheet, index) => Some(sheet.rule(index)),+ SharedRuleData::Declarations(_) => None,+ }+ }+pub(crate) fn rule_type(self) -> NativeRuleType {self.rule_type}pub(crate) fn local_identity(self) -> u64 {match self.data {- SharedRuleData::Rule(rule) => u64::from(rule.local_identity),+ SharedRuleData::Rule(sheet, index) => u64::from(sheet.rule(index).local_identity),SharedRuleData::Declarations(declarations) => declarations.local_identity,}}pub(crate) fn namespace(self) -> Option<&'a Arc<NamespaceRuleData>> {- let SharedRuleData::Rule(rule) = self.data else {- return None;- };+ let rule = self.parsed()?;rule.namespace_rule()}pub(crate) fn property(self) -> Option<&'a PropertyRuleData> {- let SharedRuleData::Rule(rule) = self.data else {- return None;- };+ let rule = self.parsed()?;rule.property_rule().map(|value| &**value)}pub(crate) fn import(self) -> Option<&'a Arc<ImportRuleData>> {- let SharedRuleData::Rule(rule) = self.data else {- return None;- };+ let rule = self.parsed()?;rule.import_rule()}pub(crate) fn media_data(self) -> Arc<MediaListData> {- let SharedRuleData::Rule(rule) = self.data else {- unreachable!()- };+ let Some(rule) = self.parsed() else { unreachable!() };rule.media_list().unwrap().clone()}pub(crate) fn function_signature(self) -> Option<Arc<FunctionSignature>> {- let SharedRuleData::Rule(rule) = self.data else {- return None;- };+ let rule = self.parsed()?;rule.function_signature().cloned()}pub(crate) fn font_feature_values(self) -> Option<Arc<FontFeatureValuesData>> {- let SharedRuleData::Rule(rule) = self.data else {- return None;- };+ let rule = self.parsed()?;rule.font_feature_values().cloned()}pub(crate) fn descriptors(self) -> Option<Arc<DescriptorBlockData>> {match self.data {- SharedRuleData::Rule(rule) => rule.descriptor_block().cloned(),+ SharedRuleData::Rule(sheet, index) => sheet.rule(index).descriptor_block().cloned(),SharedRuleData::Declarations(declarations) => declarations.descriptor_block.clone(),}}pub(crate) fn keyframe(self) -> Option<&'a KeyframeData> {- let SharedRuleData::Rule(rule) = self.data else {- return None;- };+ let rule = self.parsed()?;rule.keyframe().map(|value| &**value)}pub(crate) fn selectors(self) -> Option<Arc<RustParsedSelectorList>> {- let SharedRuleData::Rule(rule) = self.data else {- return None;- };+ let rule = self.parsed()?;rule.selector_list().cloned()}pub(crate) fn scope(self) -> Option<Arc<ScopeSelectors>> {- let SharedRuleData::Rule(rule) = self.data else {- return None;- };+ let rule = self.parsed()?;rule.scope_selectors().cloned()}pub(crate) fn container(self) -> Option<&'a Arc<ContainerConditionsData>> {- let SharedRuleData::Rule(rule) = self.data else {- return None;- };+ let rule = self.parsed()?;rule.container_conditions()}pub(crate) fn layer_name(self) -> Option<&'a [u16]> {- let SharedRuleData::Rule(rule) = self.data else {- return None;- };+ let rule = self.parsed()?;match self.rule_type {NativeRuleType::LayerBlock => Some(rule.layer_names().unwrap().names[0].units()),NativeRuleType::Import => Some(rule.import_rule().unwrap().layer.as_ref()?.units()),@@ -354,9 +351,7 @@ impl<'a> SharedRule<'a> {}pub(crate) fn definition_name(self) -> Option<CssString> {- let SharedRuleData::Rule(rule) = self.data else {- return None;- };+ let rule = self.parsed()?;match self.rule_type {NativeRuleType::Property => Some(rule.property_rule().unwrap().name.clone()),NativeRuleType::Keyframes => rule.keyframes_name().cloned(),@@ -367,23 +362,17 @@ impl<'a> SharedRule<'a> {}pub(crate) fn layer_names(self) -> Option<&'a LayerNames> {- let SharedRuleData::Rule(rule) = self.data else {- return None;- };+ let rule = self.parsed()?;rule.layer_names().map(|value| &**value)}pub(crate) fn media(self) -> Option<&'a MediaListData> {- let SharedRuleData::Rule(rule) = self.data else {- return None;- };+ let rule = self.parsed()?;rule.media_list().map(|value| &**value)}pub(crate) fn supports(self) -> Option<&'a Arc<FfiQueryHandle>> {- let SharedRuleData::Rule(rule) = self.data else {- return None;- };+ let rule = self.parsed()?;if self.rule_type == NativeRuleType::Import {rule.import_rule().unwrap().supports.as_ref()} else {@@ -393,7 +382,9 @@ impl<'a> SharedRule<'a> {pub(crate) fn cascade_declarations(self) -> Option<SharedDeclarationBlock> {match self.data {- SharedRuleData::Rule(rule) if self.rule_type == NativeRuleType::Style => rule.declaration_block().cloned(),+ SharedRuleData::Rule(sheet, index) if self.rule_type == NativeRuleType::Style => {+ sheet.rule(index).declaration_block().cloned()+ }SharedRuleData::Declarations(declarations) if self.rule_type == NativeRuleType::NestedDeclarations => {declarations.declaration_block.clone()}@@ -403,22 +394,24 @@ impl<'a> SharedRule<'a> {pub(crate) fn position_try_declarations(self) -> Option<SharedDeclarationBlock> {match self.data {- SharedRuleData::Rule(rule) if self.rule_type == NativeRuleType::PositionTry => {- rule.declaration_block().cloned()+ SharedRuleData::Rule(sheet, index) if self.rule_type == NativeRuleType::PositionTry => {+ sheet.rule(index).declaration_block().cloned()}_ => None,}}pub(crate) fn visit_children(self, visit: &mut impl FnMut(Self) -> ControlFlow<()>) -> ControlFlow<()> {- let SharedRuleData::Rule(rule) = self.data else {+ let SharedRuleData::Rule(sheet, index) = self.data else {return ControlFlow::Continue(());};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 as usize], declarations_kind).unwrap();+ let rule = sheet.rule(index);+ let children = sheet.children_of(rule);+ for &position in sheet.native_children_of(rule) {+ let child = Self::from_child(sheet, &children[position as usize], declarations_kind).unwrap();visit(child)?;}ControlFlow::Continue(())