Skip to main content

style/invalidation/element/
relative_selector.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! Invalidation of element styles relative selectors.
6
7use crate::FxHashMap;
8use crate::data::ElementData;
9use crate::dom::{TElement, TNode};
10use crate::invalidation::element::element_wrapper::{ElementWrapper, Snapshots};
11use crate::invalidation::element::invalidation_map::{
12    AdditionalRelativeSelectorInvalidationMap, Dependency, DependencyInvalidationKind,
13    InvalidationMap, NormalDependencyInvalidationKind, RelativeDependencyInvalidationKind,
14    ScopeDependencyInvalidationKind, TSStateForInvalidation,
15};
16use crate::invalidation::element::invalidator::{
17    DescendantInvalidationLists, Invalidation, InvalidationProcessor, InvalidationResult,
18    InvalidationVector, SiblingTraversalMap, TreeStyleInvalidator,
19    note_scope_dependency_force_at_subject,
20};
21use crate::invalidation::element::restyle_hints::RestyleHint;
22use crate::invalidation::element::state_and_attributes::{
23    check_dependency, dependency_may_be_relevant, invalidated_descendants, invalidated_self,
24    invalidated_sibling, push_invalidation, should_process_descendants,
25};
26use crate::stylist::{CascadeData, Stylist};
27use dom::ElementState;
28use selectors::OpaqueElement;
29use selectors::kleene_value::KleeneValue;
30use selectors::matching::{
31    ElementSelectorFlags, MatchingContext, MatchingForInvalidation, MatchingMode,
32    NeedsSelectorFlags, QuirksMode, SelectorCaches, SubjectOrPseudoElement, VisitedHandlingMode,
33    early_reject_by_local_name, matches_compound_selector, matches_selector,
34};
35use selectors::parser::SelectorKey;
36use smallvec::{SmallVec, smallvec};
37use std::ops::DerefMut;
38
39/// Kind of DOM mutation this relative selector invalidation is being carried out in.
40#[derive(Clone, Copy)]
41pub enum DomMutationOperation {
42    /// Insertion operation, can cause side effect, but presumed already happened.
43    Insert,
44    /// Append operation, cannot cause side effect.
45    Append,
46    /// Removal operation, can cause side effect, but presumed already happened. Sibling relationships are destroyed.
47    Remove,
48    /// Invalidating for side effect of a DOM operation, for the previous sibling.
49    SideEffectPrevSibling,
50    /// Invalidating for side effect of a DOM operation, for the next sibling.
51    SideEffectNextSibling,
52}
53
54impl DomMutationOperation {
55    fn accept<E: TElement>(&self, d: &Dependency, e: E) -> bool {
56        match self {
57            Self::Insert | Self::Append | Self::Remove => {
58                !e.relative_selector_search_direction().is_empty()
59            },
60            // `:has(+ .a + .b)` with `.anchor + .a + .remove + .b` - `.a` would be present
61            // in the search path.
62            Self::SideEffectPrevSibling => {
63                !e.relative_selector_search_direction().is_empty()
64                    && d.right_combinator_is_next_sibling()
65            },
66            // If an element is being removed and would cause next-sibling match to happen,
67            // e.g. `:has(+ .a)` with `.anchor + .remove + .a`, `.a` isn't yet searched
68            // for relative selector matching.
69            Self::SideEffectNextSibling => d.dependency_is_relative_with_single_next_sibling(),
70        }
71    }
72
73    fn is_side_effect(&self) -> bool {
74        match self {
75            Self::Insert | Self::Append | Self::Remove => false,
76            Self::SideEffectPrevSibling | Self::SideEffectNextSibling => true,
77        }
78    }
79}
80
81/// Context required to try and optimize away relative dependencies.
82struct OptimizationContext<'a, E: TElement> {
83    sibling_traversal_map: &'a SiblingTraversalMap<E>,
84    operation: DomMutationOperation,
85}
86
87impl<'a, E: TElement> OptimizationContext<'a, E> {
88    fn can_be_ignored(
89        &self,
90        quirks_mode: QuirksMode,
91        is_subtree: bool,
92        element: E,
93        host: Option<OpaqueElement>,
94        dependency: &Dependency,
95        leftmost_collapse_offset: usize,
96    ) -> bool {
97        if is_subtree {
98            // Subtree elements don't have unaffected sibling to look at.
99            return false;
100        }
101        debug_assert!(
102            matches!(
103                dependency.invalidation_kind(),
104                DependencyInvalidationKind::Relative(..)
105            ),
106            "Non-relative selector being evaluated for optimization"
107        );
108        // This optimization predecates on the fact that there may be a sibling that can readily
109        // "take over" this element.
110        let sibling = match self.sibling_traversal_map.prev_sibling_for(&element) {
111            None => {
112                if matches!(self.operation, DomMutationOperation::Append) {
113                    return false;
114                }
115                match self.sibling_traversal_map.next_sibling_for(&element) {
116                    Some(s) => s,
117                    None => return false,
118                }
119            },
120            Some(s) => s,
121        };
122        {
123            // Run through the affected compund.
124            let iter = dependency.selector.iter_from(dependency.selector_offset);
125            for c in iter {
126                if c.has_indexed_selector_in_subject() {
127                    // We do not calculate indices during invalidation as they're wasteful - as a side effect,
128                    // such selectors always return true, breaking this optimization. Note that we only check
129                    // this compound only because the check to skip compares against this element's sibling.
130                    // i.e. Given `:has(:nth-child(2) .foo)`, we'd try to find `.foo`'s sibling, which
131                    // shares `:nth-child` up the selector.
132                    return false;
133                }
134            }
135        }
136        let dependency_is_rightmost = dependency.selector_offset == 0;
137        if !dependency_is_rightmost {
138            let combinator = dependency
139                .selector
140                .combinator_at_match_order(dependency.selector_offset - 1);
141            if combinator.is_ancestor() {
142                // We can safely ignore these, since we're about to traverse the
143                // rest of the affected tree anyway to find the rightmost invalidated element.
144                return true;
145            }
146            if combinator.is_sibling() && matches!(self.operation, DomMutationOperation::Append) {
147                // If we're at the top of the DOM tree being mutated, we can ignore it if the
148                // operation is append - we know we'll cover all the later siblings and their descendants.
149                return true;
150            }
151        }
152
153        // We have a situation like `:has(.item .item + .item + .item)`, where the first element in the sibling
154        // chain position (i.e. The element matched by the second `.item` from the left) mutates. By the time we
155        // get here, we've collapsed the 4 dependencies for each of `.item` position into one at the rightmost
156        // position. Before we look for a standin, we need to find which `.item` this element matches - Doing
157        // that would generate more work than it saves.
158        if dependency_is_rightmost
159            && leftmost_collapse_offset != dependency.selector_offset
160            && self
161                .sibling_traversal_map
162                .next_sibling_for(&element)
163                .is_some()
164        {
165            return false;
166        }
167
168        let mut caches = SelectorCaches::default();
169        let mut matching_context = MatchingContext::new(
170            MatchingMode::Normal,
171            None,
172            &mut caches,
173            quirks_mode,
174            NeedsSelectorFlags::No,
175            MatchingForInvalidation::Yes,
176        );
177        matching_context.current_host = host;
178        let sibling_matches = matches_selector(
179            &dependency.selector,
180            dependency.selector_offset,
181            None,
182            sibling,
183            &mut matching_context,
184        );
185        if sibling_matches {
186            // Remember that at this point, we know that the combinator to the right of this
187            // compound is a sibling combinator. Effectively, we've found a standin for the
188            // element we're mutating.
189            // e.g. Given `:has(... .a ~ .b ...)`, we're the mutating element matching `... .a`,
190            // if we find a sibling that matches the `... .a`, it can stand in for us.
191            debug_assert!(
192                dependency.next.is_some(),
193                "No relative selector outer dependency?"
194            );
195            return dependency.next.as_ref().is_some_and(|deps| {
196                // ... However, if the standin sibling can be the anchor, we can't skip it, since
197                // that sibling should be invlidated to become the anchor.
198                let next = &deps.as_ref().slice()[0];
199                !matches_selector(
200                    &next.selector,
201                    next.selector_offset,
202                    None,
203                    sibling,
204                    &mut matching_context,
205                )
206            });
207        }
208        // Ok, there's no standin element - but would this element have matched the upstream
209        // selector anyway? If we don't, either the match exists somewhere far from us
210        // (In which case our mutation doesn't really matter), or it doesn't exist at all,
211        // so we can just skip the invalidation.
212        let (combinator, prev_offset) = {
213            let mut iter = dependency.selector.iter_from(dependency.selector_offset);
214            let mut o = dependency.selector_offset;
215            while iter.next().is_some() {
216                o += 1;
217            }
218            let combinator = iter.next_sequence();
219            o += 1;
220            debug_assert!(
221                combinator.is_some(),
222                "Should at least see a relative combinator"
223            );
224            (combinator.unwrap(), o)
225        };
226        if combinator.is_sibling() && prev_offset >= dependency.selector.len() - 1 {
227            // Hit the relative combinator - we don't have enough information to
228            // see if there's going to be a downstream match.
229            return false;
230        }
231        !matches_selector(
232            &dependency.selector,
233            dependency.selector_offset,
234            None,
235            element,
236            &mut matching_context,
237        )
238    }
239}
240
241/// Overall invalidator for handling relative selector invalidations.
242pub struct RelativeSelectorInvalidator<'a, 'b: 'a, E>
243where
244    E: TElement,
245{
246    /// Element triggering the invalidation.
247    pub element: E,
248    /// Quirks mode of the current invalidation.
249    pub quirks_mode: QuirksMode,
250    /// Snapshot containing changes to invalidate against.
251    /// Can be None if it's a DOM mutation.
252    pub snapshots: Option<&'a Snapshots<'b>>,
253    /// Callback to trigger when the subject element is invalidated.
254    pub invalidated: fn(E, &InvalidationResult),
255    /// The traversal map that should be used to process invalidations.
256    pub sibling_traversal_map: SiblingTraversalMap<E>,
257}
258
259struct RelativeSelectorInvalidation<'a> {
260    host: Option<OpaqueElement>,
261    kind: RelativeDependencyInvalidationKind,
262    dependency: &'a Dependency,
263}
264
265type ElementDependencies<'a> = SmallVec<[(Option<OpaqueElement>, &'a Dependency); 1]>;
266type Dependencies<'a, E> = SmallVec<[(E, ElementDependencies<'a>); 1]>;
267type AlreadyInvalidated<'a, E> = SmallVec<[AlreadyInvalidatedEntry<'a, E>; 2]>;
268
269struct AlreadyInvalidatedEntry<'a, E>
270where
271    E: TElement + 'a,
272{
273    /// Element where the invalidation will begin.
274    element: E,
275    /// The current shadow host.
276    host: Option<OpaqueElement>,
277    /// Dependency chain for this invalidation.
278    dependency: &'a Dependency,
279    /// The offset, of the leftmost dependencies that this
280    /// invalidation collapsed. See the `update()` function
281    /// for more information.
282    leftmost_collapse_offset: usize,
283}
284
285impl<'a, E> AlreadyInvalidatedEntry<'a, E>
286where
287    E: TElement + 'a,
288{
289    fn new(element: E, host: Option<OpaqueElement>, dependency: &'a Dependency) -> Self {
290        Self {
291            element,
292            host,
293            dependency,
294            leftmost_collapse_offset: dependency.selector_offset,
295        }
296    }
297
298    /// Update this invalidation with a new invalidation that may collapse with it.
299    fn update(&mut self, element: E, host: Option<OpaqueElement>, dependency: &'a Dependency) {
300        // This dependency should invalidate the same way - Collapse the invalidation
301        // to a more general case so we don't do duplicate work.
302        // e.g. For `:has(.item .item + .item + .item)`, since the anchor would be located
303        // in the ancestor chain for any invalidation triggered by any `.item` compound,
304        // 4 entries can collapse into one - but keep track of the leftmost offset.
305        if self.dependency.selector_offset > dependency.selector_offset {
306            *self = Self {
307                element,
308                host,
309                dependency,
310                leftmost_collapse_offset: self.leftmost_collapse_offset,
311            };
312        } else if self.leftmost_collapse_offset < dependency.selector_offset {
313            self.leftmost_collapse_offset = dependency.selector_offset;
314        }
315    }
316}
317
318/// Interface for collecting relative selector dependencies.
319pub struct RelativeSelectorDependencyCollector<'a, 's, E>
320where
321    E: TElement,
322{
323    /// Dependencies that need to run through the normal invalidation that may generate
324    /// a relative selector invalidation.
325    dependencies: FxHashMap<E, ElementDependencies<'a>>,
326    /// Dependencies that created an invalidation right away.
327    invalidations: AlreadyInvalidated<'a, E>,
328    /// The top element in the subtree being invalidated.
329    top: E,
330    /// Optional context that will be used to try and skip invalidations
331    /// by running selector matches.
332    optimization_context: Option<OptimizationContext<'a, E>>,
333    quirks_mode: QuirksMode,
334    /// Snapshots map, if not in the context of DOM mutation.
335    snapshots: Option<&'a Snapshots<'s>>,
336}
337
338type Invalidations<'a> = SmallVec<[RelativeSelectorInvalidation<'a>; 1]>;
339type InnerInvalidations<'a, E> = SmallVec<[(E, RelativeSelectorInvalidation<'a>); 1]>;
340
341struct ToInvalidate<'a, E: TElement + 'a> {
342    /// Dependencies to run through normal invalidator.
343    dependencies: Dependencies<'a, E>,
344    /// Dependencies already invalidated.
345    invalidations: Invalidations<'a>,
346}
347
348impl<'a, E: TElement + 'a> Default for ToInvalidate<'a, E> {
349    fn default() -> Self {
350        Self {
351            dependencies: Dependencies::default(),
352            invalidations: Invalidations::default(),
353        }
354    }
355}
356
357fn invalidation_can_collapse(
358    a: &Dependency,
359    b: &Dependency,
360    allow_indexed_selectors: bool,
361) -> bool {
362    // We want to detect identical dependencies that occur at different
363    // compounds but has the identical compound in the same selector,
364    // e.g. :has(.item .item).
365
366    // If they trigger different invalidations, they shouldn't be collapsed.
367    if a.relative_invalidation_kind() != b.relative_invalidation_kind() {
368        return false;
369    }
370
371    // Not in the same selector, trivially skipped.
372    if SelectorKey::new(&a.selector) != SelectorKey::new(&b.selector) {
373        return false;
374    }
375
376    // Check that this is in the same nesting.
377    // TODO(dshin): @scope probably brings more subtleties...
378    let mut a_next = a.next.as_ref();
379    let mut b_next = b.next.as_ref();
380    while let (Some(a_deps), Some(b_deps)) = (a_next, b_next) {
381        // This is a bit subtle - but we don't need to do the checks we do at higher levels.
382        // Cases like `:is(.item .foo) :is(.item .foo)` where `.item` invalidates would
383        // point to different dependencies, pointing to the same outer selector, but
384        // differing in selector offset.
385        let a_nexts = a_deps.as_ref().slice();
386        let b_nexts = b_deps.as_ref().slice();
387        if a_nexts.is_empty() || b_nexts.is_empty() {
388            // Can happen when we get out to empty @scope() rules.
389            // If they're both empty, we can just do nothing for both.
390            return a_nexts.is_empty() == b_nexts.is_empty();
391        }
392        let a_n = &a_nexts[0];
393        let b_n = &b_nexts[0];
394        if SelectorKey::new(&a_n.selector) != SelectorKey::new(&b_n.selector) {
395            return false;
396        }
397        a_next = a_n.next.as_ref();
398        b_next = b_n.next.as_ref();
399    }
400    if a_next.is_some() || b_next.is_some() {
401        return false;
402    }
403
404    // Ok, now, do the compounds actually match?
405    // This can get expensive quickly, but we're assuming that:
406    //
407    //   * In most cases, authors don't generally duplicate compounds in a selector, so
408    //     this fails quickly
409    //   * In cases where compounds are duplicated, reducing the number of invalidations
410    //     has a payoff that offsets the comparison cost
411    //
412    // Note, `.a.b` != `.b.a` - doesn't affect correctness, though.
413    // TODO(dshin): Caching this may be worth it as well?
414    let mut a_iter = a.selector.iter_from(a.selector_offset);
415    let mut b_iter = b.selector.iter_from(b.selector_offset);
416    loop {
417        let a_component = a_iter.next();
418        let b_component = b_iter.next();
419
420        if a_component != b_component {
421            return false;
422        }
423        let Some(component) = a_component else {
424            return true;
425        };
426        if !allow_indexed_selectors && component.has_indexed_selector_in_subject() {
427            // The element's positioning matters, so can't collapse.
428            return false;
429        }
430    }
431}
432
433impl<'a, 's, E> RelativeSelectorDependencyCollector<'a, 's, E>
434where
435    E: TElement,
436{
437    fn new(
438        top: E,
439        quirks_mode: QuirksMode,
440        optimization_context: Option<OptimizationContext<'a, E>>,
441        snapshots: Option<&'a Snapshots<'s>>,
442    ) -> Self {
443        Self {
444            dependencies: FxHashMap::default(),
445            invalidations: AlreadyInvalidated::default(),
446            top,
447            quirks_mode,
448            optimization_context,
449            snapshots,
450        }
451    }
452
453    fn insert_invalidation(
454        &mut self,
455        element: E,
456        dependency: &'a Dependency,
457        host: Option<OpaqueElement>,
458    ) {
459        let in_subtree = element != self.top;
460        if let Some(entry) = self.invalidations.iter_mut().find(|entry| {
461            // If we're in the subtree of DOM manipulation - worrying the about positioning of this element
462            // is irrelevant, because the DOM structure is either completely new or about to go away.
463            let both_in_subtree = in_subtree && entry.element != self.top;
464            // If we're considering the same element for invalidation, their evaluation of the indexed selector
465            // is identical by definition.
466            let same_element = element == entry.element;
467            invalidation_can_collapse(
468                dependency,
469                entry.dependency,
470                both_in_subtree || same_element,
471            )
472        }) {
473            entry.update(element, host, dependency)
474        } else {
475            self.invalidations
476                .push(AlreadyInvalidatedEntry::new(element, host, dependency));
477        }
478    }
479
480    /// Add this dependency, if it is unique (i.e. Different outer dependency or same outer dependency
481    /// but requires a different invalidation traversal).
482    pub fn add_dependency(
483        &mut self,
484        dependency: &'a Dependency,
485        element: E,
486        host: Option<OpaqueElement>,
487    ) {
488        if let Some(snapshots) = self.snapshots
489            && !Self::compound_may_be_different(
490                self.quirks_mode,
491                dependency,
492                element,
493                host,
494                snapshots,
495            )
496        {
497            // Nothing in the compound changed, we can safely ignore.
498            return;
499        }
500        match dependency.invalidation_kind() {
501            DependencyInvalidationKind::FullSelector => unreachable!(),
502            DependencyInvalidationKind::Normal(..) | DependencyInvalidationKind::Scope(..) => {
503                self.dependencies
504                    .entry(element)
505                    .or_default()
506                    .push((host, dependency));
507            },
508            DependencyInvalidationKind::Relative(kind) => {
509                debug_assert!(
510                    dependency.next.is_some(),
511                    "Orphaned inner relative selector?"
512                );
513                if element != self.top
514                    && matches!(
515                        kind,
516                        RelativeDependencyInvalidationKind::Parent
517                            | RelativeDependencyInvalidationKind::PrevSibling
518                            | RelativeDependencyInvalidationKind::EarlierSibling
519                    )
520                {
521                    return;
522                }
523                if early_reject_by_local_name(
524                    &dependency.selector,
525                    dependency.selector_offset,
526                    element,
527                ) {
528                    return;
529                }
530                self.insert_invalidation(element, dependency, host);
531            },
532        };
533    }
534
535    /// Check for a quick exit for the invalidation initiating element. Dependencies
536    /// up the chain are checked by the invalidator.
537    fn compound_may_be_different(
538        quirks_mode: QuirksMode,
539        dependency: &'a Dependency,
540        element: E,
541        host: Option<OpaqueElement>,
542        snapshots: &Snapshots<'s>,
543    ) -> bool {
544        debug_assert!(element.has_snapshot());
545        let mut selector_caches = SelectorCaches::default();
546        let mut matching_context = MatchingContext::<'_, E::Impl>::new_for_visited(
547            MatchingMode::Normal,
548            None,
549            &mut selector_caches,
550            VisitedHandlingMode::AllLinksVisitedAndUnvisited,
551            quirks_mode,
552            NeedsSelectorFlags::No,
553            MatchingForInvalidation::YesForComparison,
554        );
555        matching_context.current_host = host;
556        // Pseudos are disallowed in :has, so this should work.
557        let is_rightmost = if dependency.selector_offset == 0 {
558            SubjectOrPseudoElement::Yes
559        } else {
560            SubjectOrPseudoElement::No
561        };
562        let matches_now = matches_compound_selector(
563            &mut dependency.selector.iter_from(dependency.selector_offset),
564            element,
565            &mut matching_context,
566            is_rightmost,
567        );
568
569        let wrapper = ElementWrapper::new(element, snapshots);
570        let matched_then = matches_compound_selector(
571            &mut dependency.selector.iter_from(dependency.selector_offset),
572            wrapper,
573            &mut matching_context,
574            is_rightmost,
575        );
576        matched_then != matches_now || matches_now == KleeneValue::Unknown
577    }
578
579    /// Get the dependencies in a list format.
580    fn get(self) -> ToInvalidate<'a, E> {
581        let mut result = ToInvalidate::default();
582        for invalidation in self.invalidations {
583            match invalidation.dependency.invalidation_kind() {
584                DependencyInvalidationKind::FullSelector => unreachable!(),
585                DependencyInvalidationKind::Normal(_) | DependencyInvalidationKind::Scope(_) => {
586                    unreachable!("Inner selector in invalidation?")
587                },
588                DependencyInvalidationKind::Relative(kind) => {
589                    if let Some(context) = self.optimization_context.as_ref()
590                        && context.can_be_ignored(
591                            self.quirks_mode,
592                            invalidation.element != self.top,
593                            invalidation.element,
594                            invalidation.host,
595                            invalidation.dependency,
596                            invalidation.leftmost_collapse_offset,
597                        )
598                    {
599                        continue;
600                    }
601                    let dependency = &invalidation.dependency.next.as_ref().unwrap().slice()[0];
602                    result.invalidations.push(RelativeSelectorInvalidation {
603                        kind,
604                        host: invalidation.host,
605                        dependency,
606                    });
607                    // We move the invalidation up to the top of the subtree to avoid unnecessary traveral, but
608                    // this means that we need to take ancestor-earlier sibling invalidations into account, as
609                    // they'd look into earlier siblings of the top of the subtree as well.
610                    if invalidation.element != self.top
611                        && matches!(
612                            kind,
613                            RelativeDependencyInvalidationKind::AncestorEarlierSibling
614                                | RelativeDependencyInvalidationKind::AncestorPrevSibling
615                        )
616                    {
617                        result.invalidations.push(RelativeSelectorInvalidation {
618                            kind: if matches!(
619                                kind,
620                                RelativeDependencyInvalidationKind::AncestorPrevSibling
621                            ) {
622                                RelativeDependencyInvalidationKind::PrevSibling
623                            } else {
624                                RelativeDependencyInvalidationKind::EarlierSibling
625                            },
626                            host: invalidation.host,
627                            dependency,
628                        });
629                    }
630                },
631            };
632        }
633        for (key, element_dependencies) in self.dependencies {
634            result.dependencies.push((key, element_dependencies));
635        }
636        result
637    }
638
639    fn collect_all_dependencies_for_element(
640        &mut self,
641        element: E,
642        scope: Option<OpaqueElement>,
643        quirks_mode: QuirksMode,
644        map: &'a InvalidationMap,
645        additional_relative_selector_invalidation_map: &'a AdditionalRelativeSelectorInvalidationMap,
646        operation: DomMutationOperation,
647    ) {
648        element.id().map(|v| {
649            if let Some(v) = map.id_to_selector.get(v, quirks_mode) {
650                for dependency in v {
651                    if !operation.accept(dependency, element) {
652                        continue;
653                    }
654                    self.add_dependency(dependency, element, scope);
655                }
656            }
657        });
658        element.each_class(|v| {
659            if let Some(v) = map.class_to_selector.get(v, quirks_mode) {
660                for dependency in v {
661                    if !operation.accept(dependency, element) {
662                        continue;
663                    }
664                    self.add_dependency(dependency, element, scope);
665                }
666            }
667        });
668        element.each_custom_state(|v| {
669            if let Some(v) = map.custom_state_affecting_selectors.get(v) {
670                for dependency in v {
671                    if !operation.accept(dependency, element) {
672                        continue;
673                    }
674                    self.add_dependency(dependency, element, scope);
675                }
676            }
677        });
678        element.each_attr_name(|v| {
679            if let Some(v) = map.other_attribute_affecting_selectors.get(v) {
680                for dependency in v {
681                    if !operation.accept(dependency, element) {
682                        continue;
683                    }
684                    self.add_dependency(dependency, element, scope);
685                }
686            }
687        });
688        let state = element.state();
689        map.state_affecting_selectors.lookup_with_additional(
690            element,
691            quirks_mode,
692            None,
693            &[],
694            ElementState::empty(),
695            |dependency| {
696                if !dependency.state.intersects(state) {
697                    return true;
698                }
699                if !operation.accept(&dependency.dep, element) {
700                    return true;
701                }
702                self.add_dependency(&dependency.dep, element, scope);
703                true
704            },
705        );
706
707        additional_relative_selector_invalidation_map
708            .ts_state_to_selector
709            .lookup_with_additional(
710                element,
711                quirks_mode,
712                None,
713                &[],
714                ElementState::empty(),
715                |dependency| {
716                    if !operation.accept(&dependency.dep, element) {
717                        return true;
718                    }
719                    // This section contain potential optimization for not running full invalidation -
720                    // consult documentation in `TSStateForInvalidation`.
721                    if dependency.state.may_be_optimized() {
722                        if operation.is_side_effect() {
723                            // Side effect operations act on element not being mutated, so they can't
724                            // change the match outcome of these optimizable pseudoclasses.
725                            return true;
726                        }
727                        debug_assert!(
728                            self.optimization_context.is_some(),
729                            "Optimization context not available for DOM mutation?"
730                        );
731                        if dependency.state.contains(TSStateForInvalidation::EMPTY)
732                            && element.first_element_child().is_some()
733                        {
734                            return true;
735                        }
736
737                        let sibling_traversal_map = self
738                            .optimization_context
739                            .as_ref()
740                            .unwrap()
741                            .sibling_traversal_map;
742                        if dependency
743                            .state
744                            .contains(TSStateForInvalidation::NTH_EDGE_FIRST)
745                            && sibling_traversal_map.prev_sibling_for(&element).is_some()
746                        {
747                            return true;
748                        }
749
750                        if dependency
751                            .state
752                            .contains(TSStateForInvalidation::NTH_EDGE_LAST)
753                            && sibling_traversal_map.next_sibling_for(&element).is_some()
754                        {
755                            return true;
756                        }
757                    }
758                    self.add_dependency(&dependency.dep, element, scope);
759                    true
760                },
761            );
762
763        if let Some(v) = additional_relative_selector_invalidation_map
764            .type_to_selector
765            .get(element.local_name())
766        {
767            for dependency in v {
768                if !operation.accept(dependency, element) {
769                    continue;
770                }
771                self.add_dependency(dependency, element, scope);
772            }
773        }
774
775        for dependency in &additional_relative_selector_invalidation_map.any_to_selector {
776            if !operation.accept(dependency, element) {
777                continue;
778            }
779            self.add_dependency(dependency, element, scope);
780        }
781    }
782
783    fn is_empty(&self) -> bool {
784        self.invalidations.is_empty() && self.dependencies.is_empty()
785    }
786}
787
788impl<'a, 'b, E> RelativeSelectorInvalidator<'a, 'b, E>
789where
790    E: TElement + 'a,
791{
792    /// Gather relative selector dependencies for the given element, and invalidate as necessary.
793    #[inline(never)]
794    pub fn invalidate_relative_selectors_for_this<F>(
795        self,
796        stylist: &'a Stylist,
797        mut gather_dependencies: F,
798    ) where
799        F: FnMut(
800            &E,
801            Option<OpaqueElement>,
802            &'a CascadeData,
803            QuirksMode,
804            &mut RelativeSelectorDependencyCollector<'a, 'b, E>,
805        ),
806    {
807        let mut collector = RelativeSelectorDependencyCollector::new(
808            self.element,
809            self.quirks_mode,
810            None,
811            self.snapshots,
812        );
813        stylist.for_each_cascade_data_with_scope(self.element, |data, scope| {
814            let map = data.relative_invalidation_map_attributes();
815            if !map.used {
816                return;
817            }
818            gather_dependencies(
819                &self.element,
820                scope.map(|e| e.opaque()),
821                data,
822                self.quirks_mode,
823                &mut collector,
824            );
825        });
826        if collector.is_empty() {
827            return;
828        }
829        self.invalidate_from_dependencies(collector.get());
830    }
831
832    /// Gather relative selector dependencies for the given element (And its subtree) that mutated, and invalidate as necessary.
833    #[inline(never)]
834    pub fn invalidate_relative_selectors_for_dom_mutation(
835        self,
836        subtree: bool,
837        stylist: &'a Stylist,
838        inherited_search_path: ElementSelectorFlags,
839        operation: DomMutationOperation,
840    ) {
841        let mut collector = RelativeSelectorDependencyCollector::new(
842            self.element,
843            self.quirks_mode,
844            if operation.is_side_effect() {
845                None
846            } else {
847                Some(OptimizationContext {
848                    sibling_traversal_map: &self.sibling_traversal_map,
849                    operation,
850                })
851            },
852            None,
853        );
854        let mut traverse_subtree = false;
855        self.element.apply_selector_flags(inherited_search_path);
856        stylist.for_each_cascade_data_with_scope(self.element, |data, scope| {
857            let map_attributes = data.relative_invalidation_map_attributes();
858            if !map_attributes.used {
859                return;
860            }
861            let map = data.relative_selector_invalidation_map();
862            traverse_subtree |= map_attributes.needs_ancestors_traversal;
863            collector.collect_all_dependencies_for_element(
864                self.element,
865                scope.map(|e| e.opaque()),
866                self.quirks_mode,
867                map,
868                map_attributes,
869                operation,
870            );
871        });
872
873        if subtree && traverse_subtree {
874            for node in self.element.as_node().dom_descendants() {
875                let descendant = match node.as_element() {
876                    Some(e) => e,
877                    None => continue,
878                };
879                descendant.apply_selector_flags(inherited_search_path);
880                stylist.for_each_cascade_data_with_scope(descendant, |data, scope| {
881                    let map_attributes = data.relative_invalidation_map_attributes();
882                    if !map_attributes.used {
883                        return;
884                    }
885                    let map = data.relative_selector_invalidation_map();
886                    collector.collect_all_dependencies_for_element(
887                        descendant,
888                        scope.map(|e| e.opaque()),
889                        self.quirks_mode,
890                        map,
891                        map_attributes,
892                        operation,
893                    );
894                });
895            }
896        }
897        if collector.is_empty() {
898            return;
899        }
900        self.invalidate_from_dependencies(collector.get());
901    }
902
903    /// Carry out complete invalidation triggered by a relative selector invalidation.
904    fn invalidate_from_dependencies(&self, to_invalidate: ToInvalidate<'a, E>) {
905        for (element, dependencies) in to_invalidate.dependencies {
906            let mut selector_caches = SelectorCaches::default();
907            let mut processor = RelativeSelectorInnerInvalidationProcessor::new(
908                self.quirks_mode,
909                self.snapshots,
910                &dependencies,
911                &mut selector_caches,
912                &self.sibling_traversal_map,
913            );
914            TreeStyleInvalidator::new(element, None, &mut processor).invalidate();
915            for (element, invalidation) in processor.take_invalidations() {
916                self.invalidate_upwards(element, &invalidation);
917            }
918        }
919        for invalidation in to_invalidate.invalidations {
920            self.invalidate_upwards(self.element, &invalidation);
921        }
922    }
923
924    fn invalidate_upwards(&self, element: E, invalidation: &RelativeSelectorInvalidation<'a>) {
925        // This contains the main reason for why relative selector invalidation is handled
926        // separately - It travels ancestor and/or earlier sibling direction.
927        match invalidation.kind {
928            RelativeDependencyInvalidationKind::Parent => {
929                element.parent_element().map(|e| {
930                    if !Self::in_search_direction(
931                        &e,
932                        ElementSelectorFlags::RELATIVE_SELECTOR_SEARCH_DIRECTION_ANCESTOR,
933                    ) {
934                        return;
935                    }
936                    self.handle_anchor(e, invalidation.dependency, invalidation.host);
937                });
938            },
939            RelativeDependencyInvalidationKind::Ancestors => {
940                let mut parent = element.parent_element();
941                while let Some(par) = parent {
942                    if !Self::in_search_direction(
943                        &par,
944                        ElementSelectorFlags::RELATIVE_SELECTOR_SEARCH_DIRECTION_ANCESTOR,
945                    ) {
946                        return;
947                    }
948                    self.handle_anchor(par, invalidation.dependency, invalidation.host);
949                    parent = par.parent_element();
950                }
951            },
952            RelativeDependencyInvalidationKind::PrevSibling => {
953                self.sibling_traversal_map
954                    .prev_sibling_for(&element)
955                    .map(|e| {
956                        if !Self::in_search_direction(
957                            &e,
958                            ElementSelectorFlags::RELATIVE_SELECTOR_SEARCH_DIRECTION_SIBLING,
959                        ) {
960                            return;
961                        }
962                        self.handle_anchor(e, invalidation.dependency, invalidation.host);
963                    });
964            },
965            RelativeDependencyInvalidationKind::AncestorPrevSibling => {
966                let mut parent = element.parent_element();
967                while let Some(par) = parent {
968                    if !Self::in_search_direction(
969                        &par,
970                        ElementSelectorFlags::RELATIVE_SELECTOR_SEARCH_DIRECTION_ANCESTOR,
971                    ) {
972                        return;
973                    }
974                    par.prev_sibling_element().map(|e| {
975                        if !Self::in_search_direction(
976                            &e,
977                            ElementSelectorFlags::RELATIVE_SELECTOR_SEARCH_DIRECTION_SIBLING,
978                        ) {
979                            return;
980                        }
981                        self.handle_anchor(e, invalidation.dependency, invalidation.host);
982                    });
983                    parent = par.parent_element();
984                }
985            },
986            RelativeDependencyInvalidationKind::EarlierSibling => {
987                let mut sibling = self.sibling_traversal_map.prev_sibling_for(&element);
988                while let Some(sib) = sibling {
989                    if !Self::in_search_direction(
990                        &sib,
991                        ElementSelectorFlags::RELATIVE_SELECTOR_SEARCH_DIRECTION_SIBLING,
992                    ) {
993                        return;
994                    }
995                    self.handle_anchor(sib, invalidation.dependency, invalidation.host);
996                    sibling = sib.prev_sibling_element();
997                }
998            },
999            RelativeDependencyInvalidationKind::AncestorEarlierSibling => {
1000                let mut parent = element.parent_element();
1001                while let Some(par) = parent {
1002                    if !Self::in_search_direction(
1003                        &par,
1004                        ElementSelectorFlags::RELATIVE_SELECTOR_SEARCH_DIRECTION_ANCESTOR,
1005                    ) {
1006                        return;
1007                    }
1008                    let mut sibling = par.prev_sibling_element();
1009                    while let Some(sib) = sibling {
1010                        if !Self::in_search_direction(
1011                            &sib,
1012                            ElementSelectorFlags::RELATIVE_SELECTOR_SEARCH_DIRECTION_SIBLING,
1013                        ) {
1014                            return;
1015                        }
1016                        self.handle_anchor(sib, invalidation.dependency, invalidation.host);
1017                        sibling = sib.prev_sibling_element();
1018                    }
1019                    parent = par.parent_element();
1020                }
1021            },
1022        }
1023    }
1024
1025    /// Is this element in the direction of the given relative selector search path?
1026    fn in_search_direction(element: &E, desired: ElementSelectorFlags) -> bool {
1027        element
1028            .relative_selector_search_direction()
1029            .intersects(desired)
1030    }
1031
1032    /// Handle a potential relative selector anchor.
1033    fn handle_anchor(
1034        &self,
1035        element: E,
1036        outer_dependency: &Dependency,
1037        host: Option<OpaqueElement>,
1038    ) {
1039        let is_rightmost = Self::is_subject(outer_dependency);
1040        if (is_rightmost
1041            && !element.has_selector_flags(ElementSelectorFlags::ANCHORS_RELATIVE_SELECTOR))
1042            || (!is_rightmost
1043                && !element.has_selector_flags(
1044                    ElementSelectorFlags::ANCHORS_RELATIVE_SELECTOR_NON_SUBJECT,
1045                ))
1046        {
1047            // If it was never a relative selector anchor, don't bother.
1048            return;
1049        }
1050        let mut selector_caches = SelectorCaches::default();
1051        let matching_context = MatchingContext::<'_, E::Impl>::new_for_visited(
1052            MatchingMode::Normal,
1053            None,
1054            &mut selector_caches,
1055            VisitedHandlingMode::AllLinksVisitedAndUnvisited,
1056            self.quirks_mode,
1057            NeedsSelectorFlags::No,
1058            MatchingForInvalidation::Yes,
1059        );
1060        let mut data = match element.mutate_data() {
1061            Some(data) => data,
1062            None => return,
1063        };
1064        let mut processor = RelativeSelectorOuterInvalidationProcessor {
1065            element,
1066            host,
1067            data: data.deref_mut(),
1068            dependency: outer_dependency,
1069            matching_context,
1070            traversal_map: &self.sibling_traversal_map,
1071        };
1072        let result = TreeStyleInvalidator::new(element, None, &mut processor).invalidate();
1073        (self.invalidated)(element, &result);
1074    }
1075
1076    /// Does this relative selector dependency have its relative selector in the subject position?
1077    fn is_subject(outer_dependency: &Dependency) -> bool {
1078        debug_assert!(
1079            matches!(
1080                outer_dependency.invalidation_kind(),
1081                DependencyInvalidationKind::Normal(_) | DependencyInvalidationKind::Scope(_)
1082            ),
1083            "Outer selector of relative selector is relative?"
1084        );
1085
1086        if let Some(x) = outer_dependency.next.as_ref() {
1087            // We only care to ensure that we're the subject in the outermost selector of the current
1088            // selector - Crossing over a scope invalidation would mean moving into a selector inside
1089            // the current scope block
1090            if matches!(
1091                outer_dependency.invalidation_kind(),
1092                DependencyInvalidationKind::Normal(..)
1093            ) && !Self::is_subject(&x.as_ref().slice()[0])
1094            {
1095                // Not subject in outer selector.
1096                return false;
1097            }
1098        }
1099        outer_dependency
1100            .selector
1101            .is_rightmost(outer_dependency.selector_offset)
1102    }
1103}
1104
1105/// Blindly invalidate everything outside of a relative selector.
1106/// Consider `:is(.a :has(.b) .c ~ .d) ~ .e .f`, where .b gets deleted.
1107/// Since the tree mutated, we cannot rely on snapshots.
1108pub struct RelativeSelectorOuterInvalidationProcessor<'a, 'b, E: TElement> {
1109    /// Element being invalidated.
1110    pub element: E,
1111    /// The current shadow host, if any.
1112    pub host: Option<OpaqueElement>,
1113    /// Data for the element being invalidated.
1114    pub data: &'a mut ElementData,
1115    /// Dependency to be processed.
1116    pub dependency: &'b Dependency,
1117    /// Matching context to use for invalidation.
1118    pub matching_context: MatchingContext<'a, E::Impl>,
1119    /// Traversal map for this invalidation.
1120    pub traversal_map: &'a SiblingTraversalMap<E>,
1121}
1122
1123impl<'a, 'b: 'a, E: 'a> InvalidationProcessor<'b, 'a, E>
1124    for RelativeSelectorOuterInvalidationProcessor<'a, 'b, E>
1125where
1126    E: TElement,
1127{
1128    fn invalidates_on_pseudo_element(&self) -> bool {
1129        true
1130    }
1131
1132    fn check_outer_dependency(
1133        &mut self,
1134        _dependency: &Dependency,
1135        _element: E,
1136        _: Option<OpaqueElement>,
1137    ) -> bool {
1138        // At this point, we know a relative selector invalidated, and are ignoring them.
1139        true
1140    }
1141
1142    fn matching_context(&mut self) -> &mut MatchingContext<'a, E::Impl> {
1143        &mut self.matching_context
1144    }
1145
1146    fn sibling_traversal_map(&self) -> &SiblingTraversalMap<E> {
1147        self.traversal_map
1148    }
1149
1150    fn collect_invalidations(
1151        &mut self,
1152        element: E,
1153        _self_invalidations: &mut InvalidationVector<'b>,
1154        descendant_invalidations: &mut DescendantInvalidationLists<'b>,
1155        sibling_invalidations: &mut InvalidationVector<'b>,
1156    ) -> bool {
1157        debug_assert_eq!(element, self.element);
1158        debug_assert!(
1159            self.matching_context.matching_for_invalidation(),
1160            "Not matching for invalidation?"
1161        );
1162
1163        // Ok, this element can potentially an anchor to the given dependency.
1164        // Before we do the potentially-costly ancestor/earlier sibling traversal,
1165        // See if it can actuall be an anchor by trying to match the "rest" of the selector
1166        // outside and to the left of `:has` in question.
1167        // e.g. Element under consideration can only be the anchor to `:has` in
1168        // `.foo .bar ~ .baz:has()`, iff it matches `.foo .bar ~ .baz`.
1169        let invalidated_self = {
1170            let mut invalidated = false;
1171            let mut dependencies_to_invalidate: SmallVec<[&Dependency; 1]> =
1172                smallvec![self.dependency];
1173            while let Some(d) = dependencies_to_invalidate.pop() {
1174                debug_assert!(
1175                    matches!(
1176                        d.invalidation_kind(),
1177                        DependencyInvalidationKind::Normal(_)
1178                            | DependencyInvalidationKind::Scope(_)
1179                    ),
1180                    "Unexpected dependency kind"
1181                );
1182                if !dependency_may_be_relevant(d, &element, false) {
1183                    continue;
1184                }
1185                if !matches_selector(
1186                    &d.selector,
1187                    d.selector_offset,
1188                    None,
1189                    element,
1190                    self.matching_context(),
1191                ) {
1192                    continue;
1193                }
1194
1195                let invalidation_kind = d.invalidation_kind();
1196
1197                if let DependencyInvalidationKind::Scope(scope_kind) = invalidation_kind
1198                    && d.selector.is_rightmost(d.selector_offset)
1199                {
1200                    if scope_kind == ScopeDependencyInvalidationKind::ScopeEnd {
1201                        let invalidations = note_scope_dependency_force_at_subject(
1202                            d,
1203                            self.matching_context.current_host,
1204                            self.matching_context.scope_element,
1205                            false,
1206                        );
1207                        descendant_invalidations
1208                            .dom_descendants
1209                            .extend(invalidations);
1210
1211                        invalidated |= true;
1212                    } else if let Some(ref next) = d.next {
1213                        dependencies_to_invalidate.extend(next.as_ref().slice());
1214                    }
1215                    continue;
1216                }
1217
1218                if matches!(
1219                    invalidation_kind,
1220                    DependencyInvalidationKind::Normal(NormalDependencyInvalidationKind::Element)
1221                ) {
1222                    if let Some(ref deps) = d.next {
1223                        // Normal dependencies should only have one next
1224                        dependencies_to_invalidate.push(&deps.as_ref().slice()[0]);
1225                        continue;
1226                    }
1227                    invalidated |= true;
1228                    continue;
1229                }
1230                debug_assert_ne!(d.selector_offset, 0);
1231                debug_assert_ne!(d.selector_offset, d.selector.len());
1232                let invalidation = Invalidation::new(d, self.host, None);
1233                invalidated |= push_invalidation(
1234                    invalidation,
1235                    d.invalidation_kind(),
1236                    descendant_invalidations,
1237                    sibling_invalidations,
1238                );
1239            }
1240            invalidated
1241        };
1242
1243        if invalidated_self {
1244            self.data.hint.insert(RestyleHint::RESTYLE_SELF);
1245        }
1246        invalidated_self
1247    }
1248
1249    fn should_process_descendants(&mut self, element: E) -> bool {
1250        if element == self.element {
1251            return should_process_descendants(self.data);
1252        }
1253
1254        match element.borrow_data() {
1255            Some(d) => should_process_descendants(&d),
1256            None => false,
1257        }
1258    }
1259
1260    fn recursion_limit_exceeded(&mut self, _element: E) {
1261        unreachable!("Unexpected recursion limit");
1262    }
1263
1264    fn invalidated_descendants(&mut self, element: E, child: E) {
1265        invalidated_descendants(element, child)
1266    }
1267
1268    fn invalidated_self(&mut self, element: E) {
1269        debug_assert_ne!(element, self.element);
1270        invalidated_self(element);
1271    }
1272
1273    fn invalidated_sibling(&mut self, element: E, of: E) {
1274        debug_assert_ne!(element, self.element);
1275        invalidated_sibling(element, of);
1276    }
1277}
1278
1279/// Invalidation for the selector(s) inside a relative selector.
1280pub struct RelativeSelectorInnerInvalidationProcessor<'a, 'b, 's, E>
1281where
1282    E: TElement,
1283{
1284    /// Matching context to be used.
1285    matching_context: MatchingContext<'b, E::Impl>,
1286    /// Table of snapshots.
1287    snapshots: Option<&'b Snapshots<'s>>,
1288    /// Incoming dependencies to be processed.
1289    dependencies: &'b ElementDependencies<'a>,
1290    /// Generated invalidations.
1291    invalidations: InnerInvalidations<'a, E>,
1292    /// Traversal map for this invalidation.
1293    traversal_map: &'b SiblingTraversalMap<E>,
1294}
1295
1296impl<'a, 'b, 's, E> RelativeSelectorInnerInvalidationProcessor<'a, 'b, 's, E>
1297where
1298    E: TElement,
1299{
1300    fn new(
1301        quirks_mode: QuirksMode,
1302        snapshots: Option<&'b Snapshots<'s>>,
1303        dependencies: &'b ElementDependencies<'a>,
1304        selector_caches: &'b mut SelectorCaches,
1305        traversal_map: &'b SiblingTraversalMap<E>,
1306    ) -> Self {
1307        let matching_context = MatchingContext::new_for_visited(
1308            MatchingMode::Normal,
1309            None,
1310            selector_caches,
1311            VisitedHandlingMode::AllLinksVisitedAndUnvisited,
1312            quirks_mode,
1313            NeedsSelectorFlags::No,
1314            MatchingForInvalidation::Yes,
1315        );
1316        Self {
1317            matching_context,
1318            snapshots,
1319            dependencies,
1320            invalidations: InnerInvalidations::default(),
1321            traversal_map,
1322        }
1323    }
1324
1325    fn note_dependency(
1326        &mut self,
1327        element: E,
1328        host: Option<OpaqueElement>,
1329        dependency: &'a Dependency,
1330        descendant_invalidations: &mut DescendantInvalidationLists<'a>,
1331        sibling_invalidations: &mut InvalidationVector<'a>,
1332    ) {
1333        match dependency.invalidation_kind() {
1334            DependencyInvalidationKind::FullSelector => unreachable!(),
1335            DependencyInvalidationKind::Normal(_) | DependencyInvalidationKind::Scope(_) => (),
1336            DependencyInvalidationKind::Relative(kind) => {
1337                self.found_relative_selector_invalidation(element, kind, dependency);
1338                return;
1339            },
1340        }
1341        if matches!(
1342            dependency.normal_invalidation_kind(),
1343            NormalDependencyInvalidationKind::Element
1344        ) {
1345            // Ok, keep heading outwards.
1346            debug_assert!(
1347                dependency.next.is_some(),
1348                "Orphaned inner selector dependency?"
1349            );
1350            if let Some(next) = dependency.next.as_ref() {
1351                self.note_dependency(
1352                    element,
1353                    host,
1354                    &next.as_ref().slice()[0],
1355                    descendant_invalidations,
1356                    sibling_invalidations,
1357                );
1358            }
1359            return;
1360        }
1361        let invalidation = Invalidation::new(dependency, None, None);
1362        match dependency.normal_invalidation_kind() {
1363            NormalDependencyInvalidationKind::Descendants => {
1364                // Descendant invalidations are simplified due to pseudo-elements not being available within the relative selector.
1365                descendant_invalidations.dom_descendants.push(invalidation)
1366            },
1367            NormalDependencyInvalidationKind::Siblings => sibling_invalidations.push(invalidation),
1368            // Note(dshin, bug 1940212): Nesting can enabling stuffing pseudo-elements into :has, like `::marker { :has(&) }`.
1369            // Ideally, we can just not insert the dependency into the invalidation map, but the necessary selector information
1370            // for this (i.e. `HAS_PSEUDO`) is filtered out in `replace_parent_selector` through
1371            // `SelectorFlags::forbidden_for_nesting`, so just ignoring such dependencies here is the best we can do.
1372            _ => (),
1373        }
1374    }
1375
1376    /// Take the generated invalidations.
1377    fn take_invalidations(self) -> InnerInvalidations<'a, E> {
1378        self.invalidations
1379    }
1380}
1381
1382impl<'a, 'b, E> InvalidationProcessor<'a, 'b, E>
1383    for RelativeSelectorInnerInvalidationProcessor<'a, 'b, '_, E>
1384where
1385    E: TElement,
1386{
1387    fn check_outer_dependency(
1388        &mut self,
1389        dependency: &Dependency,
1390        element: E,
1391        _: Option<OpaqueElement>,
1392    ) -> bool {
1393        if let Some(snapshots) = self.snapshots {
1394            let wrapper = ElementWrapper::new(element, snapshots);
1395            return check_dependency(
1396                dependency,
1397                element,
1398                wrapper,
1399                &mut self.matching_context,
1400                None,
1401            );
1402        }
1403        // Just invalidate if we don't have a snapshot.
1404        true
1405    }
1406
1407    fn matching_context(&mut self) -> &mut MatchingContext<'b, E::Impl> {
1408        &mut self.matching_context
1409    }
1410
1411    fn collect_invalidations(
1412        &mut self,
1413        element: E,
1414        _self_invalidations: &mut InvalidationVector<'a>,
1415        descendant_invalidations: &mut DescendantInvalidationLists<'a>,
1416        sibling_invalidations: &mut InvalidationVector<'a>,
1417    ) -> bool {
1418        for (scope, dependency) in self.dependencies {
1419            self.note_dependency(
1420                element,
1421                *scope,
1422                dependency,
1423                descendant_invalidations,
1424                sibling_invalidations,
1425            )
1426        }
1427        false
1428    }
1429
1430    fn should_process_descendants(&mut self, _element: E) -> bool {
1431        true
1432    }
1433
1434    fn recursion_limit_exceeded(&mut self, _element: E) {
1435        unreachable!("Unexpected recursion limit");
1436    }
1437
1438    // Don't do anything for normal invalidations.
1439    fn invalidated_self(&mut self, _element: E) {}
1440    fn invalidated_sibling(&mut self, _sibling: E, _of: E) {}
1441    fn invalidated_descendants(&mut self, _element: E, _child: E) {}
1442
1443    fn found_relative_selector_invalidation(
1444        &mut self,
1445        element: E,
1446        kind: RelativeDependencyInvalidationKind,
1447        dep: &'a Dependency,
1448    ) {
1449        debug_assert!(dep.next.is_some(), "Orphaned inners selector?");
1450        if element.relative_selector_search_direction().is_empty() {
1451            return;
1452        }
1453        self.invalidations.push((
1454            element,
1455            RelativeSelectorInvalidation {
1456                host: self.matching_context.current_host,
1457                kind,
1458                dependency: &dep.next.as_ref().unwrap().as_ref().slice()[0],
1459            },
1460        ));
1461    }
1462
1463    fn sibling_traversal_map(&self) -> &SiblingTraversalMap<E> {
1464        self.traversal_map
1465    }
1466}