Skip to main content

lewp_selectors/
matching.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
5use crate::attr::{AttrSelectorOperation, NamespaceConstraint, ParsedAttrSelectorOperation};
6use crate::bloom::{BloomFilter, BLOOM_HASH_MASK};
7use crate::nth_index_cache::NthIndexCacheInner;
8use crate::parser::{AncestorHashes, Combinator, Component, LocalName};
9use crate::parser::{NonTSPseudoClass, Selector, SelectorImpl, SelectorIter, SelectorList};
10use crate::tree::Element;
11use smallvec::SmallVec;
12use std::borrow::Borrow;
13use std::iter;
14
15pub use crate::context::*;
16
17// The bloom filter for descendant CSS selectors will have a <1% false
18// positive rate until it has this many selectors in it, then it will
19// rapidly increase.
20pub static RECOMMENDED_SELECTOR_BLOOM_FILTER_SIZE: usize = 4096;
21
22bitflags! {
23    /// Set of flags that are set on either the element or its parent (depending
24    /// on the flag) if the element could potentially match a selector.
25    pub struct ElementSelectorFlags: usize {
26        /// When a child is added or removed from the parent, all the children
27        /// must be restyled, because they may match :nth-last-child,
28        /// :last-of-type, :nth-last-of-type, or :only-of-type.
29        const HAS_SLOW_SELECTOR = 1 << 0;
30
31        /// When a child is added or removed from the parent, any later
32        /// children must be restyled, because they may match :nth-child,
33        /// :first-of-type, or :nth-of-type.
34        const HAS_SLOW_SELECTOR_LATER_SIBLINGS = 1 << 1;
35
36        /// When a child is added or removed from the parent, the first and
37        /// last children must be restyled, because they may match :first-child,
38        /// :last-child, or :only-child.
39        const HAS_EDGE_CHILD_SELECTOR = 1 << 2;
40
41        /// The element has an empty selector, so when a child is appended we
42        /// might need to restyle the parent completely.
43        const HAS_EMPTY_SELECTOR = 1 << 3;
44    }
45}
46
47impl ElementSelectorFlags {
48    /// Returns the subset of flags that apply to the element.
49    pub fn for_self(self) -> ElementSelectorFlags {
50        self & (ElementSelectorFlags::HAS_EMPTY_SELECTOR)
51    }
52
53    /// Returns the subset of flags that apply to the parent.
54    pub fn for_parent(self) -> ElementSelectorFlags {
55        self & (ElementSelectorFlags::HAS_SLOW_SELECTOR |
56            ElementSelectorFlags::HAS_SLOW_SELECTOR_LATER_SIBLINGS |
57            ElementSelectorFlags::HAS_EDGE_CHILD_SELECTOR)
58    }
59}
60
61/// Holds per-compound-selector data.
62struct LocalMatchingContext<'a, 'b: 'a, Impl: SelectorImpl> {
63    shared: &'a mut MatchingContext<'b, Impl>,
64    matches_hover_and_active_quirk: MatchesHoverAndActiveQuirk,
65}
66
67#[inline(always)]
68pub fn matches_selector_list<E>(
69    selector_list: &SelectorList<E::Impl>,
70    element: &E,
71    context: &mut MatchingContext<E::Impl>,
72) -> bool
73where
74    E: Element,
75{
76    // This is pretty much any(..) but manually inlined because the compiler
77    // refuses to do so from querySelector / querySelectorAll.
78    for selector in &selector_list.0 {
79        let matches = matches_selector(selector, 0, None, element, context, &mut |_, _| {});
80
81        if matches {
82            return true;
83        }
84    }
85
86    false
87}
88
89#[inline(always)]
90fn may_match(hashes: &AncestorHashes, bf: &BloomFilter) -> bool {
91    // Check the first three hashes. Note that we can check for zero before
92    // masking off the high bits, since if any of the first three hashes is
93    // zero the fourth will be as well. We also take care to avoid the
94    // special-case complexity of the fourth hash until we actually reach it,
95    // because we usually don't.
96    //
97    // To be clear: this is all extremely hot.
98    for i in 0..3 {
99        let packed = hashes.packed_hashes[i];
100        if packed == 0 {
101            // No more hashes left - unable to fast-reject.
102            return true;
103        }
104
105        if !bf.might_contain_hash(packed & BLOOM_HASH_MASK) {
106            // Hooray! We fast-rejected on this hash.
107            return false;
108        }
109    }
110
111    // Now do the slighty-more-complex work of synthesizing the fourth hash,
112    // and check it against the filter if it exists.
113    let fourth = hashes.fourth_hash();
114    fourth == 0 || bf.might_contain_hash(fourth)
115}
116
117/// A result of selector matching, includes 3 failure types,
118///
119///   NotMatchedAndRestartFromClosestLaterSibling
120///   NotMatchedAndRestartFromClosestDescendant
121///   NotMatchedGlobally
122///
123/// When NotMatchedGlobally appears, stop selector matching completely since
124/// the succeeding selectors never matches.
125/// It is raised when
126///   Child combinator cannot find the candidate element.
127///   Descendant combinator cannot find the candidate element.
128///
129/// When NotMatchedAndRestartFromClosestDescendant appears, the selector
130/// matching does backtracking and restarts from the closest Descendant
131/// combinator.
132/// It is raised when
133///   NextSibling combinator cannot find the candidate element.
134///   LaterSibling combinator cannot find the candidate element.
135///   Child combinator doesn't match on the found element.
136///
137/// When NotMatchedAndRestartFromClosestLaterSibling appears, the selector
138/// matching does backtracking and restarts from the closest LaterSibling
139/// combinator.
140/// It is raised when
141///   NextSibling combinator doesn't match on the found element.
142///
143/// For example, when the selector "d1 d2 a" is provided and we cannot *find*
144/// an appropriate ancestor element for "d1", this selector matching raises
145/// NotMatchedGlobally since even if "d2" is moved to more upper element, the
146/// candidates for "d1" becomes less than before and d1 .
147///
148/// The next example is siblings. When the selector "b1 + b2 ~ d1 a" is
149/// provided and we cannot *find* an appropriate brother element for b1,
150/// the selector matching raises NotMatchedAndRestartFromClosestDescendant.
151/// The selectors ("b1 + b2 ~") doesn't match and matching restart from "d1".
152///
153/// The additional example is child and sibling. When the selector
154/// "b1 + c1 > b2 ~ d1 a" is provided and the selector "b1" doesn't match on
155/// the element, this "b1" raises NotMatchedAndRestartFromClosestLaterSibling.
156/// However since the selector "c1" raises
157/// NotMatchedAndRestartFromClosestDescendant. So the selector
158/// "b1 + c1 > b2 ~ " doesn't match and restart matching from "d1".
159#[derive(Clone, Copy, Eq, PartialEq)]
160enum SelectorMatchingResult {
161    Matched,
162    NotMatchedAndRestartFromClosestLaterSibling,
163    NotMatchedAndRestartFromClosestDescendant,
164    NotMatchedGlobally,
165}
166
167/// Whether the :hover and :active quirk applies.
168///
169/// https://quirks.spec.whatwg.org/#the-active-and-hover-quirk
170#[derive(Clone, Copy, Debug, PartialEq)]
171enum MatchesHoverAndActiveQuirk {
172    Yes,
173    No,
174}
175
176/// Matches a selector, fast-rejecting against a bloom filter.
177///
178/// We accept an offset to allow consumers to represent and match against
179/// partial selectors (indexed from the right). We use this API design, rather
180/// than having the callers pass a SelectorIter, because creating a SelectorIter
181/// requires dereferencing the selector to get the length, which adds an
182/// unncessary cache miss for cases when we can fast-reject with AncestorHashes
183/// (which the caller can store inline with the selector pointer).
184#[inline(always)]
185pub fn matches_selector<E, F>(
186    selector: &Selector<E::Impl>,
187    offset: usize,
188    hashes: Option<&AncestorHashes>,
189    element: &E,
190    context: &mut MatchingContext<E::Impl>,
191    flags_setter: &mut F,
192) -> bool
193where
194    E: Element,
195    F: FnMut(&E, ElementSelectorFlags),
196{
197    // Use the bloom filter to fast-reject.
198    if let Some(hashes) = hashes {
199        if let Some(filter) = context.bloom_filter {
200            if !may_match(hashes, filter) {
201                return false;
202            }
203        }
204    }
205
206    matches_complex_selector(selector.iter_from(offset), element, context, flags_setter)
207}
208
209/// Whether a compound selector matched, and whether it was the rightmost
210/// selector inside the complex selector.
211pub enum CompoundSelectorMatchingResult {
212    /// The selector was fully matched.
213    FullyMatched,
214    /// The compound selector matched, and the next combinator offset is
215    /// `next_combinator_offset`.
216    Matched { next_combinator_offset: usize },
217    /// The selector didn't match.
218    NotMatched,
219}
220
221/// Matches a compound selector belonging to `selector`, starting at offset
222/// `from_offset`, matching left to right.
223///
224/// Requires that `from_offset` points to a `Combinator`.
225///
226/// NOTE(emilio): This doesn't allow to match in the leftmost sequence of the
227/// complex selector, but it happens to be the case we don't need it.
228pub fn matches_compound_selector_from<E>(
229    selector: &Selector<E::Impl>,
230    mut from_offset: usize,
231    context: &mut MatchingContext<E::Impl>,
232    element: &E,
233) -> CompoundSelectorMatchingResult
234where
235    E: Element,
236{
237    if cfg!(debug_assertions) && from_offset != 0 {
238        selector.combinator_at_parse_order(from_offset - 1); // This asserts.
239    }
240
241    let mut local_context = LocalMatchingContext {
242        shared: context,
243        matches_hover_and_active_quirk: MatchesHoverAndActiveQuirk::No,
244    };
245
246    // Find the end of the selector or the next combinator, then match
247    // backwards, so that we match in the same order as
248    // matches_complex_selector, which is usually faster.
249    let start_offset = from_offset;
250    for component in selector.iter_raw_parse_order_from(from_offset) {
251        if matches!(*component, Component::Combinator(..)) {
252            debug_assert_ne!(from_offset, 0, "Selector started with a combinator?");
253            break;
254        }
255
256        from_offset += 1;
257    }
258
259    debug_assert!(from_offset >= 1);
260    debug_assert!(from_offset <= selector.len());
261
262    let iter = selector.iter_from(selector.len() - from_offset);
263    debug_assert!(
264        iter.clone().next().is_some() ||
265            (from_offset != selector.len() &&
266                matches!(
267                    selector.combinator_at_parse_order(from_offset),
268                    Combinator::SlotAssignment | Combinator::PseudoElement
269                )),
270        "Got the math wrong: {:?} | {:?} | {} {}",
271        selector,
272        selector.iter_raw_match_order().as_slice(),
273        from_offset,
274        start_offset
275    );
276
277    for component in iter {
278        if !matches_simple_selector(component, element, &mut local_context, &mut |_, _| {}) {
279            return CompoundSelectorMatchingResult::NotMatched;
280        }
281    }
282
283    if from_offset != selector.len() {
284        return CompoundSelectorMatchingResult::Matched {
285            next_combinator_offset: from_offset,
286        };
287    }
288
289    CompoundSelectorMatchingResult::FullyMatched
290}
291
292/// Matches a complex selector.
293#[inline(always)]
294pub fn matches_complex_selector<E, F>(
295    mut iter: SelectorIter<E::Impl>,
296    element: &E,
297    context: &mut MatchingContext<E::Impl>,
298    flags_setter: &mut F,
299) -> bool
300where
301    E: Element,
302    F: FnMut(&E, ElementSelectorFlags),
303{
304    // If this is the special pseudo-element mode, consume the ::pseudo-element
305    // before proceeding, since the caller has already handled that part.
306    if context.matching_mode() == MatchingMode::ForStatelessPseudoElement && !context.is_nested() {
307        // Consume the pseudo.
308        match *iter.next().unwrap() {
309            Component::PseudoElement(ref pseudo) => {
310                if let Some(ref f) = context.pseudo_element_matching_fn {
311                    if !f(pseudo) {
312                        return false;
313                    }
314                }
315            },
316            _ => {
317                debug_assert!(
318                    false,
319                    "Used MatchingMode::ForStatelessPseudoElement \
320                     in a non-pseudo selector"
321                );
322            },
323        }
324
325        if !iter.matches_for_stateless_pseudo_element() {
326            return false;
327        }
328
329        // Advance to the non-pseudo-element part of the selector.
330        let next_sequence = iter.next_sequence().unwrap();
331        debug_assert_eq!(next_sequence, Combinator::PseudoElement);
332    }
333
334    let result =
335        matches_complex_selector_internal(iter, element, context, flags_setter, Rightmost::Yes);
336
337    matches!(result, SelectorMatchingResult::Matched)
338}
339
340#[inline]
341fn matches_hover_and_active_quirk<Impl: SelectorImpl>(
342    selector_iter: &SelectorIter<Impl>,
343    context: &MatchingContext<Impl>,
344    rightmost: Rightmost,
345) -> MatchesHoverAndActiveQuirk {
346    if context.quirks_mode() != QuirksMode::Quirks {
347        return MatchesHoverAndActiveQuirk::No;
348    }
349
350    if context.is_nested() {
351        return MatchesHoverAndActiveQuirk::No;
352    }
353
354    // This compound selector had a pseudo-element to the right that we
355    // intentionally skipped.
356    if rightmost == Rightmost::Yes &&
357        context.matching_mode() == MatchingMode::ForStatelessPseudoElement
358    {
359        return MatchesHoverAndActiveQuirk::No;
360    }
361
362    let all_match = selector_iter.clone().all(|simple| match *simple {
363        Component::LocalName(_) |
364        Component::AttributeInNoNamespaceExists { .. } |
365        Component::AttributeInNoNamespace { .. } |
366        Component::AttributeOther(_) |
367        Component::ID(_) |
368        Component::Class(_) |
369        Component::PseudoElement(_) |
370        Component::Negation(_) |
371        Component::FirstChild |
372        Component::LastChild |
373        Component::OnlyChild |
374        Component::Empty |
375        Component::NthChild(_, _) |
376        Component::NthLastChild(_, _) |
377        Component::NthOfType(_, _) |
378        Component::NthLastOfType(_, _) |
379        Component::FirstOfType |
380        Component::LastOfType |
381        Component::OnlyOfType => false,
382        Component::NonTSPseudoClass(ref pseudo_class) => pseudo_class.is_active_or_hover(),
383        _ => true,
384    });
385
386    if all_match {
387        MatchesHoverAndActiveQuirk::Yes
388    } else {
389        MatchesHoverAndActiveQuirk::No
390    }
391}
392
393#[derive(Clone, Copy, PartialEq)]
394enum Rightmost {
395    Yes,
396    No,
397}
398
399#[inline(always)]
400fn next_element_for_combinator<E>(
401    element: &E,
402    combinator: Combinator,
403    selector: &SelectorIter<E::Impl>,
404    context: &MatchingContext<E::Impl>,
405) -> Option<E>
406where
407    E: Element,
408{
409    match combinator {
410        Combinator::NextSibling | Combinator::LaterSibling => element.prev_sibling_element(),
411        Combinator::Child | Combinator::Descendant => {
412            match element.parent_element() {
413                Some(e) => return Some(e),
414                None => {},
415            }
416
417            if !element.parent_node_is_shadow_root() {
418                return None;
419            }
420
421            // https://drafts.csswg.org/css-scoping/#host-element-in-tree:
422            //
423            //   For the purpose of Selectors, a shadow host also appears in
424            //   its shadow tree, with the contents of the shadow tree treated
425            //   as its children. (In other words, the shadow host is treated as
426            //   replacing the shadow root node.)
427            //
428            // and also:
429            //
430            //   When considered within its own shadow trees, the shadow host is
431            //   featureless. Only the :host, :host(), and :host-context()
432            //   pseudo-classes are allowed to match it.
433            //
434            // Since we know that the parent is a shadow root, we necessarily
435            // are in a shadow tree of the host, and the next selector will only
436            // match if the selector is a featureless :host selector.
437            if !selector.clone().is_featureless_host_selector() {
438                return None;
439            }
440
441            element.containing_shadow_host()
442        },
443        Combinator::Part => element.containing_shadow_host(),
444        Combinator::SlotAssignment => {
445            debug_assert!(element
446                .assigned_slot()
447                .map_or(true, |s| s.is_html_slot_element()));
448            let scope = context.current_host?;
449            let mut current_slot = element.assigned_slot()?;
450            while current_slot.containing_shadow_host().unwrap().opaque() != scope {
451                current_slot = current_slot.assigned_slot()?;
452            }
453            Some(current_slot)
454        },
455        Combinator::PseudoElement => element.pseudo_element_originating_element(),
456    }
457}
458
459fn matches_complex_selector_internal<E, F>(
460    mut selector_iter: SelectorIter<E::Impl>,
461    element: &E,
462    context: &mut MatchingContext<E::Impl>,
463    flags_setter: &mut F,
464    rightmost: Rightmost,
465) -> SelectorMatchingResult
466where
467    E: Element,
468    F: FnMut(&E, ElementSelectorFlags),
469{
470    debug!(
471        "Matching complex selector {:?} for {:?}",
472        selector_iter, element
473    );
474
475    let matches_compound_selector = matches_compound_selector(
476        &mut selector_iter,
477        element,
478        context,
479        flags_setter,
480        rightmost,
481    );
482
483    let combinator = selector_iter.next_sequence();
484    if combinator.map_or(false, |c| c.is_sibling()) {
485        flags_setter(
486            element,
487            ElementSelectorFlags::HAS_SLOW_SELECTOR_LATER_SIBLINGS,
488        );
489    }
490
491    if !matches_compound_selector {
492        return SelectorMatchingResult::NotMatchedAndRestartFromClosestLaterSibling;
493    }
494
495    let combinator = match combinator {
496        None => return SelectorMatchingResult::Matched,
497        Some(c) => c,
498    };
499
500    let candidate_not_found = match combinator {
501        Combinator::NextSibling | Combinator::LaterSibling => {
502            SelectorMatchingResult::NotMatchedAndRestartFromClosestDescendant
503        },
504        Combinator::Child |
505        Combinator::Descendant |
506        Combinator::SlotAssignment |
507        Combinator::Part |
508        Combinator::PseudoElement => SelectorMatchingResult::NotMatchedGlobally,
509    };
510
511    let mut next_element =
512        next_element_for_combinator(element, combinator, &selector_iter, &context);
513
514    // Stop matching :visited as soon as we find a link, or a combinator for
515    // something that isn't an ancestor.
516    let mut visited_handling = if element.is_link() || combinator.is_sibling() {
517        VisitedHandlingMode::AllLinksUnvisited
518    } else {
519        context.visited_handling()
520    };
521
522    loop {
523        let element = match next_element {
524            None => return candidate_not_found,
525            Some(next_element) => next_element,
526        };
527
528        let result = context.with_visited_handling_mode(visited_handling, |context| {
529            matches_complex_selector_internal(
530                selector_iter.clone(),
531                &element,
532                context,
533                flags_setter,
534                Rightmost::No,
535            )
536        });
537
538        match (result, combinator) {
539            // Return the status immediately.
540            (SelectorMatchingResult::Matched, _) |
541            (SelectorMatchingResult::NotMatchedGlobally, _) |
542            (_, Combinator::NextSibling) => {
543                return result;
544            },
545
546            // Upgrade the failure status to
547            // NotMatchedAndRestartFromClosestDescendant.
548            (_, Combinator::PseudoElement) | (_, Combinator::Child) => {
549                return SelectorMatchingResult::NotMatchedAndRestartFromClosestDescendant;
550            },
551
552            // If the failure status is
553            // NotMatchedAndRestartFromClosestDescendant and combinator is
554            // Combinator::LaterSibling, give up this Combinator::LaterSibling
555            // matching and restart from the closest descendant combinator.
556            (
557                SelectorMatchingResult::NotMatchedAndRestartFromClosestDescendant,
558                Combinator::LaterSibling,
559            ) => {
560                return result;
561            },
562
563            // The Combinator::Descendant combinator and the status is
564            // NotMatchedAndRestartFromClosestLaterSibling or
565            // NotMatchedAndRestartFromClosestDescendant, or the
566            // Combinator::LaterSibling combinator and the status is
567            // NotMatchedAndRestartFromClosestDescendant, we can continue to
568            // matching on the next candidate element.
569            _ => {},
570        }
571
572        if element.is_link() {
573            visited_handling = VisitedHandlingMode::AllLinksUnvisited;
574        }
575
576        next_element = next_element_for_combinator(&element, combinator, &selector_iter, &context);
577    }
578}
579
580#[inline]
581fn matches_local_name<E>(element: &E, local_name: &LocalName<E::Impl>) -> bool
582where
583    E: Element,
584{
585    let name = select_name(
586        element.is_html_element_in_html_document(),
587        &local_name.name,
588        &local_name.lower_name,
589    )
590    .borrow();
591    element.has_local_name(name)
592}
593
594/// Determines whether the given element matches the given compound selector.
595#[inline]
596fn matches_compound_selector<E, F>(
597    selector_iter: &mut SelectorIter<E::Impl>,
598    element: &E,
599    context: &mut MatchingContext<E::Impl>,
600    flags_setter: &mut F,
601    rightmost: Rightmost,
602) -> bool
603where
604    E: Element,
605    F: FnMut(&E, ElementSelectorFlags),
606{
607    let matches_hover_and_active_quirk =
608        matches_hover_and_active_quirk(&selector_iter, context, rightmost);
609
610    // Handle some common cases first.
611    // We may want to get rid of this at some point if we can make the
612    // generic case fast enough.
613    let mut selector = selector_iter.next();
614    if let Some(&Component::LocalName(ref local_name)) = selector {
615        if !matches_local_name(element, local_name) {
616            return false;
617        }
618        selector = selector_iter.next();
619    }
620    let class_and_id_case_sensitivity = context.classes_and_ids_case_sensitivity();
621    if let Some(&Component::ID(ref id)) = selector {
622        if !element.has_id(id, class_and_id_case_sensitivity) {
623            return false;
624        }
625        selector = selector_iter.next();
626    }
627    while let Some(&Component::Class(ref class)) = selector {
628        if !element.has_class(class, class_and_id_case_sensitivity) {
629            return false;
630        }
631        selector = selector_iter.next();
632    }
633    let selector = match selector {
634        Some(s) => s,
635        None => return true,
636    };
637
638    let mut local_context = LocalMatchingContext {
639        shared: context,
640        matches_hover_and_active_quirk,
641    };
642    iter::once(selector)
643        .chain(selector_iter)
644        .all(|simple| matches_simple_selector(simple, element, &mut local_context, flags_setter))
645}
646
647/// Determines whether the given element matches the given single selector.
648fn matches_simple_selector<E, F>(
649    selector: &Component<E::Impl>,
650    element: &E,
651    context: &mut LocalMatchingContext<E::Impl>,
652    flags_setter: &mut F,
653) -> bool
654where
655    E: Element,
656    F: FnMut(&E, ElementSelectorFlags),
657{
658    debug_assert!(context.shared.is_nested() || !context.shared.in_negation());
659
660    match *selector {
661        Component::Combinator(_) => unreachable!(),
662        Component::Part(ref parts) => {
663            let mut hosts = SmallVec::<[E; 4]>::new();
664
665            let mut host = match element.containing_shadow_host() {
666                Some(h) => h,
667                None => return false,
668            };
669
670            let current_host = context.shared.current_host;
671            if current_host != Some(host.opaque()) {
672                loop {
673                    let outer_host = host.containing_shadow_host();
674                    if outer_host.as_ref().map(|h| h.opaque()) == current_host {
675                        break;
676                    }
677                    let outer_host = match outer_host {
678                        Some(h) => h,
679                        None => return false,
680                    };
681                    // TODO(emilio): if worth it, we could early return if
682                    // host doesn't have the exportparts attribute.
683                    hosts.push(host);
684                    host = outer_host;
685                }
686            }
687
688            // Translate the part into the right scope.
689            parts.iter().all(|part| {
690                let mut part = part.clone();
691                for host in hosts.iter().rev() {
692                    part = match host.imported_part(&part) {
693                        Some(p) => p,
694                        None => return false,
695                    };
696                }
697                element.is_part(&part)
698            })
699        },
700        Component::Slotted(ref selector) => {
701            // <slots> are never flattened tree slottables.
702            !element.is_html_slot_element() &&
703                context.shared.nest(|context| {
704                    matches_complex_selector(selector.iter(), element, context, flags_setter)
705                })
706        },
707        Component::PseudoElement(ref pseudo) => {
708            element.match_pseudo_element(pseudo, context.shared)
709        },
710        Component::LocalName(ref local_name) => matches_local_name(element, local_name),
711        Component::ExplicitUniversalType | Component::ExplicitAnyNamespace => true,
712        Component::Namespace(_, ref url) | Component::DefaultNamespace(ref url) => {
713            element.has_namespace(&url.borrow())
714        },
715        Component::ExplicitNoNamespace => {
716            let ns = crate::parser::namespace_empty_string::<E::Impl>();
717            element.has_namespace(&ns.borrow())
718        },
719        Component::ID(ref id) => {
720            element.has_id(id, context.shared.classes_and_ids_case_sensitivity())
721        },
722        Component::Class(ref class) => {
723            element.has_class(class, context.shared.classes_and_ids_case_sensitivity())
724        },
725        Component::AttributeInNoNamespaceExists {
726            ref local_name,
727            ref local_name_lower,
728        } => {
729            let is_html = element.is_html_element_in_html_document();
730            element.attr_matches(
731                &NamespaceConstraint::Specific(&crate::parser::namespace_empty_string::<E::Impl>()),
732                select_name(is_html, local_name, local_name_lower),
733                &AttrSelectorOperation::Exists,
734            )
735        },
736        Component::AttributeInNoNamespace {
737            ref local_name,
738            ref value,
739            operator,
740            case_sensitivity,
741            never_matches,
742        } => {
743            if never_matches {
744                return false;
745            }
746            let is_html = element.is_html_element_in_html_document();
747            element.attr_matches(
748                &NamespaceConstraint::Specific(&crate::parser::namespace_empty_string::<E::Impl>()),
749                local_name,
750                &AttrSelectorOperation::WithValue {
751                    operator,
752                    case_sensitivity: case_sensitivity.to_unconditional(is_html),
753                    expected_value: value,
754                },
755            )
756        },
757        Component::AttributeOther(ref attr_sel) => {
758            if attr_sel.never_matches {
759                return false;
760            }
761            let is_html = element.is_html_element_in_html_document();
762            let empty_string;
763            let namespace = match attr_sel.namespace() {
764                Some(ns) => ns,
765                None => {
766                    empty_string = crate::parser::namespace_empty_string::<E::Impl>();
767                    NamespaceConstraint::Specific(&empty_string)
768                },
769            };
770            element.attr_matches(
771                &namespace,
772                select_name(is_html, &attr_sel.local_name, &attr_sel.local_name_lower),
773                &match attr_sel.operation {
774                    ParsedAttrSelectorOperation::Exists => AttrSelectorOperation::Exists,
775                    ParsedAttrSelectorOperation::WithValue {
776                        operator,
777                        case_sensitivity,
778                        ref expected_value,
779                    } => AttrSelectorOperation::WithValue {
780                        operator,
781                        case_sensitivity: case_sensitivity.to_unconditional(is_html),
782                        expected_value,
783                    },
784                },
785            )
786        },
787        Component::NonTSPseudoClass(ref pc) => {
788            if context.matches_hover_and_active_quirk == MatchesHoverAndActiveQuirk::Yes &&
789                !context.shared.is_nested() &&
790                pc.is_active_or_hover() &&
791                !element.is_link()
792            {
793                return false;
794            }
795
796            element.match_non_ts_pseudo_class(pc, &mut context.shared, flags_setter)
797        },
798        Component::FirstChild => matches_first_child(element, flags_setter),
799        Component::LastChild => matches_last_child(element, flags_setter),
800        Component::OnlyChild => {
801            matches_first_child(element, flags_setter) && matches_last_child(element, flags_setter)
802        },
803        Component::Root => element.is_root(),
804        Component::Empty => {
805            flags_setter(element, ElementSelectorFlags::HAS_EMPTY_SELECTOR);
806            element.is_empty()
807        },
808        Component::Host(ref selector) => {
809            context
810                .shared
811                .shadow_host()
812                .map_or(false, |host| host == element.opaque()) &&
813                selector.as_ref().map_or(true, |selector| {
814                    context.shared.nest(|context| {
815                        matches_complex_selector(selector.iter(), element, context, flags_setter)
816                    })
817                })
818        },
819        Component::Scope => match context.shared.scope_element {
820            Some(ref scope_element) => element.opaque() == *scope_element,
821            None => element.is_root(),
822        },
823        Component::NthChild(a, b) => {
824            matches_generic_nth_child(element, context, a, b, false, false, flags_setter)
825        },
826        Component::NthLastChild(a, b) => {
827            matches_generic_nth_child(element, context, a, b, false, true, flags_setter)
828        },
829        Component::NthOfType(a, b) => {
830            matches_generic_nth_child(element, context, a, b, true, false, flags_setter)
831        },
832        Component::NthLastOfType(a, b) => {
833            matches_generic_nth_child(element, context, a, b, true, true, flags_setter)
834        },
835        Component::FirstOfType => {
836            matches_generic_nth_child(element, context, 0, 1, true, false, flags_setter)
837        },
838        Component::LastOfType => {
839            matches_generic_nth_child(element, context, 0, 1, true, true, flags_setter)
840        },
841        Component::OnlyOfType => {
842            matches_generic_nth_child(element, context, 0, 1, true, false, flags_setter) &&
843                matches_generic_nth_child(element, context, 0, 1, true, true, flags_setter)
844        },
845        Component::Is(ref list) | Component::Where(ref list) => context.shared.nest(|context| {
846            for selector in &**list {
847                if matches_complex_selector(selector.iter(), element, context, flags_setter) {
848                    return true;
849                }
850            }
851            false
852        }),
853        Component::Negation(ref list) => context.shared.nest_for_negation(|context| {
854            for selector in &**list {
855                if matches_complex_selector(selector.iter(), element, context, flags_setter) {
856                    return false;
857                }
858            }
859            true
860        }),
861    }
862}
863
864#[inline(always)]
865fn select_name<'a, T>(is_html: bool, local_name: &'a T, local_name_lower: &'a T) -> &'a T {
866    if is_html {
867        local_name_lower
868    } else {
869        local_name
870    }
871}
872
873#[inline]
874fn matches_generic_nth_child<E, F>(
875    element: &E,
876    context: &mut LocalMatchingContext<E::Impl>,
877    a: i32,
878    b: i32,
879    is_of_type: bool,
880    is_from_end: bool,
881    flags_setter: &mut F,
882) -> bool
883where
884    E: Element,
885    F: FnMut(&E, ElementSelectorFlags),
886{
887    if element.ignores_nth_child_selectors() {
888        return false;
889    }
890
891    flags_setter(
892        element,
893        if is_from_end {
894            ElementSelectorFlags::HAS_SLOW_SELECTOR
895        } else {
896            ElementSelectorFlags::HAS_SLOW_SELECTOR_LATER_SIBLINGS
897        },
898    );
899
900    // Grab a reference to the appropriate cache.
901    let mut cache = context
902        .shared
903        .nth_index_cache
904        .as_mut()
905        .map(|c| c.get(is_of_type, is_from_end));
906
907    // Lookup or compute the index.
908    let index = if let Some(i) = cache.as_mut().and_then(|c| c.lookup(element.opaque())) {
909        i
910    } else {
911        let i = nth_child_index(element, is_of_type, is_from_end, cache.as_deref_mut());
912        if let Some(c) = cache.as_mut() {
913            c.insert(element.opaque(), i)
914        }
915        i
916    };
917    debug_assert_eq!(
918        index,
919        nth_child_index(element, is_of_type, is_from_end, None),
920        "invalid cache"
921    );
922
923    // Is there a non-negative integer n such that An+B=index?
924    match index.checked_sub(b) {
925        None => false,
926        Some(an) => match an.checked_div(a) {
927            Some(n) => n >= 0 && a * n == an,
928            None /* a == 0 */ => an == 0,
929        },
930    }
931}
932
933#[inline]
934fn nth_child_index<E>(
935    element: &E,
936    is_of_type: bool,
937    is_from_end: bool,
938    mut cache: Option<&mut NthIndexCacheInner>,
939) -> i32
940where
941    E: Element,
942{
943    // The traversal mostly processes siblings left to right. So when we walk
944    // siblings to the right when computing NthLast/NthLastOfType we're unlikely
945    // to get cache hits along the way. As such, we take the hit of walking the
946    // siblings to the left checking the cache in the is_from_end case (this
947    // matches what Gecko does). The indices-from-the-left is handled during the
948    // regular look further below.
949    if let Some(ref mut c) = cache {
950        if is_from_end && !c.is_empty() {
951            let mut index: i32 = 1;
952            let mut curr = element.clone();
953            while let Some(e) = curr.prev_sibling_element() {
954                curr = e;
955                if !is_of_type || element.is_same_type(&curr) {
956                    if let Some(i) = c.lookup(curr.opaque()) {
957                        return i - index;
958                    }
959                    index += 1;
960                }
961            }
962        }
963    }
964
965    let mut index: i32 = 1;
966    let mut curr = element.clone();
967    let next = |e: E| {
968        if is_from_end {
969            e.next_sibling_element()
970        } else {
971            e.prev_sibling_element()
972        }
973    };
974    while let Some(e) = next(curr) {
975        curr = e;
976        if !is_of_type || element.is_same_type(&curr) {
977            // If we're computing indices from the left, check each element in the
978            // cache. We handle the indices-from-the-right case at the top of this
979            // function.
980            if !is_from_end {
981                if let Some(i) = cache.as_mut().and_then(|c| c.lookup(curr.opaque())) {
982                    return i + index;
983                }
984            }
985            index += 1;
986        }
987    }
988
989    index
990}
991
992#[inline]
993fn matches_first_child<E, F>(element: &E, flags_setter: &mut F) -> bool
994where
995    E: Element,
996    F: FnMut(&E, ElementSelectorFlags),
997{
998    flags_setter(element, ElementSelectorFlags::HAS_EDGE_CHILD_SELECTOR);
999    element.prev_sibling_element().is_none()
1000}
1001
1002#[inline]
1003fn matches_last_child<E, F>(element: &E, flags_setter: &mut F) -> bool
1004where
1005    E: Element,
1006    F: FnMut(&E, ElementSelectorFlags),
1007{
1008    flags_setter(element, ElementSelectorFlags::HAS_EDGE_CHILD_SELECTOR);
1009    element.next_sibling_element().is_none()
1010}