1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use selectors::attr::{ParsedAttrSelectorOperation, AttrSelectorOperation, NamespaceConstraint};
use selectors::bloom::{BLOOM_HASH_MASK, BloomFilter};
use selectors::nth_index_cache::NthIndexCacheInner;
use selectors::parser::{AncestorHashes, Combinator, Component, LocalName};
use selectors::parser::{Selector, SelectorImpl, SelectorIter, SelectorList};
use std::borrow::Borrow;
use selectors::tree::Element;

pub use selectors::context::*;

// The bloom filter for descendant CSS selectors will have a <1% false
// positive rate until it has this many selectors in it, then it will
// rapidly increase.
pub static RECOMMENDED_SELECTOR_BLOOM_FILTER_SIZE: usize = 4096;

bitflags! {
    /// Set of flags that are set on either the element or its parent (depending
    /// on the flag) if the element could potentially match a selector.
    pub struct ElementSelectorFlags: usize {
        /// When a child is added or removed from the parent, all the children
        /// must be restyled, because they may match :nth-last-child,
        /// :last-of-type, :nth-last-of-type, or :only-of-type.
        const HAS_SLOW_SELECTOR = 1 << 0;

        /// When a child is added or removed from the parent, any later
        /// children must be restyled, because they may match :nth-child,
        /// :first-of-type, or :nth-of-type.
        const HAS_SLOW_SELECTOR_LATER_SIBLINGS = 1 << 1;

        /// When a child is added or removed from the parent, the first and
        /// last children must be restyled, because they may match :first-child,
        /// :last-child, or :only-child.
        const HAS_EDGE_CHILD_SELECTOR = 1 << 2;

        /// The element has an empty selector, so when a child is appended we
        /// might need to restyle the parent completely.
        const HAS_EMPTY_SELECTOR = 1 << 3;
    }
}

impl ElementSelectorFlags {
    /// Returns the subset of flags that apply to the element.
    pub fn for_self(self) -> ElementSelectorFlags {
        self & (ElementSelectorFlags::HAS_EMPTY_SELECTOR)
    }

    /// Returns the subset of flags that apply to the parent.
    pub fn for_parent(self) -> ElementSelectorFlags {
        self & (ElementSelectorFlags::HAS_SLOW_SELECTOR | ElementSelectorFlags::HAS_SLOW_SELECTOR_LATER_SIBLINGS | ElementSelectorFlags::HAS_EDGE_CHILD_SELECTOR)
    }
}

/// Holds per-selector data alongside a pointer to MatchingContext.
pub struct LocalMatchingContext<'a, 'b: 'a, Impl: SelectorImpl> {
    /// Shared `MatchingContext`.
    pub shared: &'a mut MatchingContext<'b>,
    /// A reference to the base selector we're matching against.
    pub selector: &'a Selector<Impl>,
    /// The offset of the current compound selector being matched, kept up to
    /// date by the callees when the iterator is advanced. This, in conjunction
    /// with the selector reference above, allows callees to synthesize an
    /// iterator for the current compound selector on-demand. This is necessary
    /// because the primary iterator may already have been advanced partway
    /// through the current compound selector, and the callee may need the whole
    /// thing.
    offset: usize,
    /// The level of nesting for the selector being matched.
    pub nesting_level: usize,
    /// Holds a bool flag to see whether :active and :hover quirk should try to
    /// match or not. This flag can only be true in the case PseudoElements are
    /// encountered when matching mode is ForStatelessPseudoElement.
    pub hover_active_quirk_disabled: bool,
}

impl<'a, 'b, Impl> LocalMatchingContext<'a, 'b, Impl>
    where Impl: SelectorImpl
{
    /// Constructs a new `LocalMatchingContext`.
    pub fn new(shared: &'a mut MatchingContext<'b>,
               selector: &'a Selector<Impl>) -> Self {
        Self {
            shared: shared,
            selector: selector,
            offset: 0,
            nesting_level: 0,
            // We flip this off once third sequence is reached.
            hover_active_quirk_disabled: selector.has_pseudo_element(),
        }
    }

    /// Updates offset of Selector to show new compound selector.
    /// To be able to correctly re-synthesize main SelectorIter.
    fn note_position(&mut self, selector_iter: &SelectorIter<Impl>) {
        if let QuirksMode::Quirks = self.shared.quirks_mode() {
            if self.selector.has_pseudo_element() && self.offset != 0 {
                // This is the _second_ call to note_position,
                // which means we've moved past the compound
                // selector adjacent to the pseudo-element.
                self.hover_active_quirk_disabled = false;
            }

            self.offset = self.selector.len() - selector_iter.selector_length();
        }
    }

    /// Returns true if current compound selector matches :active and :hover quirk.
    /// https://quirks.spec.whatwg.org/#the-active-and-hover-quirk
    pub fn active_hover_quirk_matches(&self) -> bool {
        if self.shared.quirks_mode() != QuirksMode::Quirks {
            return false;
        }

        // Don't allow it in recursive selectors such as :not and :-moz-any.
        if self.nesting_level != 0 {
            return false;
        }

        if self.hover_active_quirk_disabled {
            return false;
        }

        let mut iter = if self.offset == 0 {
            self.selector.iter()
        } else {
            self.selector.iter_from(self.offset)
        };

        return iter.all(|simple| {
            match *simple {
                Component::LocalName(_) |
                Component::AttributeInNoNamespaceExists { .. } |
                Component::AttributeInNoNamespace { .. } |
                Component::AttributeOther(_) |
                Component::ID(_) |
                Component::Class(_) |
                Component::PseudoElement(_) |
                Component::Negation(_) |
                Component::FirstChild |
                Component::LastChild |
                Component::OnlyChild |
                Component::Empty |
                Component::NthChild(_, _) |
                Component::NthLastChild(_, _) |
                Component::NthOfType(_, _) |
                Component::NthLastOfType(_, _) |
                Component::FirstOfType |
                Component::LastOfType |
                Component::OnlyOfType => false,
                Component::NonTSPseudoClass(ref pseudo_class) => {
                    Impl::is_active_or_hover(pseudo_class)
                },
                _ => true,
            }
        });
    }
}

pub fn matches_selector_list<E>(selector_list: &SelectorList<E::Impl>,
                                element: &E,
                                context: &mut MatchingContext)
                                -> bool
    where E: Element
{
    selector_list.0.iter().any(|selector| {
        matches_selector(selector,
                         0,
                         None,
                         element,
                         context,
                         &mut |_, _| {})
    })
}

#[inline(always)]
fn may_match<E>(hashes: &AncestorHashes,
                bf: &BloomFilter)
                -> bool
    where E: Element,
{
    // Check the first three hashes. Note that we can check for zero before
    // masking off the high bits, since if any of the first three hashes is
    // zero the fourth will be as well. We also take care to avoid the
    // special-case complexity of the fourth hash until we actually reach it,
    // because we usually don't.
    //
    // To be clear: this is all extremely hot.
    for i in 0..3 {
        let packed = hashes.packed_hashes[i];
        if packed == 0 {
            // No more hashes left - unable to fast-reject.
            return true;
        }

        if !bf.might_contain_hash(packed & BLOOM_HASH_MASK) {
            // Hooray! We fast-rejected on this hash.
            return false;
        }
    }

    // Now do the slighty-more-complex work of synthesizing the fourth hash,
    // and check it against the filter if it exists.
    let fourth = hashes.fourth_hash();
    fourth == 0 || bf.might_contain_hash(fourth)
}

/// Tracks whether we are currently looking for relevant links for a given
/// complex selector. A "relevant link" is the element being matched if it is a
/// link or the nearest ancestor link.
///
/// `matches_complex_selector` creates a new instance of this for each complex
/// selector we try to match for an element. This is done because `is_visited`
/// and `is_unvisited` are based on relevant link state of only the current
/// complex selector being matched (not the global relevant link status for all
/// selectors in `MatchingContext`).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RelevantLinkStatus {
    /// Looking for a possible relevant link.  This is the initial mode when
    /// matching a selector.
    Looking,
    /// Not looking for a relevant link.  We transition to this mode if we
    /// encounter a sibiling combinator (since only ancestor combinators are
    /// allowed for this purpose).
    NotLooking,
    /// Found a relevant link for the element being matched.
    Found,
}

impl Default for RelevantLinkStatus {
    fn default() -> Self {
        RelevantLinkStatus::NotLooking
    }
}

impl RelevantLinkStatus {
    /// If we found the relevant link for this element, record that in the
    /// overall matching context for the element as a whole and stop looking for
    /// addtional links.
    fn examine_potential_link<E>(&self, element: &E, context: &mut MatchingContext)
                                 -> RelevantLinkStatus
        where E: Element,
    {
        // If a relevant link was previously found, we no longer want to look
        // for links.  Only the nearest ancestor link is considered relevant.
        if *self != RelevantLinkStatus::Looking {
            return RelevantLinkStatus::NotLooking
        }

        if !element.is_link() {
            return *self
        }

        // We found a relevant link. Record this in the `MatchingContext`,
        // where we track whether one was found for _any_ selector (meaning
        // this field might already be true from a previous selector).
        context.relevant_link_found = true;
        // Also return `Found` to update the relevant link status for _this_
        // specific selector's matching process.
        RelevantLinkStatus::Found
    }

    /// Returns whether an element is considered visited for the purposes of
    /// matching.  This is true only if the element is a link, an relevant link
    /// exists for the element, and the visited handling mode is set to accept
    /// relevant links as visited.
    pub fn is_visited<E>(&self, element: &E, context: &MatchingContext) -> bool
        where E: Element,
    {
        if !element.is_link() {
            return false
        }

        if context.visited_handling == VisitedHandlingMode::AllLinksVisitedAndUnvisited {
            return true;
        }

        // Non-relevant links are always unvisited.
        if *self != RelevantLinkStatus::Found {
            return false
        }

        context.visited_handling == VisitedHandlingMode::RelevantLinkVisited
    }

    /// Returns whether an element is considered unvisited for the purposes of
    /// matching.  Assuming the element is a link, this is always true for
    /// non-relevant links, since only relevant links can potentially be treated
    /// as visited.  If this is a relevant link, then is it unvisited if the
    /// visited handling mode is set to treat all links as unvisted (including
    /// relevant links).
    pub fn is_unvisited<E>(&self, element: &E, context: &MatchingContext) -> bool
        where E: Element,
    {
        if !element.is_link() {
            return false
        }

        if context.visited_handling == VisitedHandlingMode::AllLinksVisitedAndUnvisited {
            return true;
        }

        // Non-relevant links are always unvisited.
        if *self != RelevantLinkStatus::Found {
            return true
        }

        context.visited_handling == VisitedHandlingMode::AllLinksUnvisited
    }
}

/// A result of selector matching, includes 3 failure types,
///
///   NotMatchedAndRestartFromClosestLaterSibling
///   NotMatchedAndRestartFromClosestDescendant
///   NotMatchedGlobally
///
/// When NotMatchedGlobally appears, stop selector matching completely since
/// the succeeding selectors never matches.
/// It is raised when
///   Child combinator cannot find the candidate element.
///   Descendant combinator cannot find the candidate element.
///
/// When NotMatchedAndRestartFromClosestDescendant appears, the selector
/// matching does backtracking and restarts from the closest Descendant
/// combinator.
/// It is raised when
///   NextSibling combinator cannot find the candidate element.
///   LaterSibling combinator cannot find the candidate element.
///   Child combinator doesn't match on the found element.
///
/// When NotMatchedAndRestartFromClosestLaterSibling appears, the selector
/// matching does backtracking and restarts from the closest LaterSibling
/// combinator.
/// It is raised when
///   NextSibling combinator doesn't match on the found element.
///
/// For example, when the selector "d1 d2 a" is provided and we cannot *find*
/// an appropriate ancestor element for "d1", this selector matching raises
/// NotMatchedGlobally since even if "d2" is moved to more upper element, the
/// candidates for "d1" becomes less than before and d1 .
///
/// The next example is siblings. When the selector "b1 + b2 ~ d1 a" is
/// provided and we cannot *find* an appropriate brother element for b1,
/// the selector matching raises NotMatchedAndRestartFromClosestDescendant.
/// The selectors ("b1 + b2 ~") doesn't match and matching restart from "d1".
///
/// The additional example is child and sibling. When the selector
/// "b1 + c1 > b2 ~ d1 a" is provided and the selector "b1" doesn't match on
/// the element, this "b1" raises NotMatchedAndRestartFromClosestLaterSibling.
/// However since the selector "c1" raises
/// NotMatchedAndRestartFromClosestDescendant. So the selector
/// "b1 + c1 > b2 ~ " doesn't match and restart matching from "d1".
#[derive(Clone, Copy, Eq, PartialEq)]
enum SelectorMatchingResult {
    Matched,
    NotMatchedAndRestartFromClosestLaterSibling,
    NotMatchedAndRestartFromClosestDescendant,
    NotMatchedGlobally,
}

/// Matches a selector, fast-rejecting against a bloom filter.
///
/// We accept an offset to allow consumers to represent and match against
/// partial selectors (indexed from the right). We use this API design, rather
/// than having the callers pass a SelectorIter, because creating a SelectorIter
/// requires dereferencing the selector to get the length, which adds an
/// unncessary cache miss for cases when we can fast-reject with AncestorHashes
/// (which the caller can store inline with the selector pointer).
#[inline(always)]
pub fn matches_selector<E, F>(selector: &Selector<E::Impl>,
                              offset: usize,
                              hashes: Option<&AncestorHashes>,
                              element: &E,
                              context: &mut MatchingContext,
                              flags_setter: &mut F)
                              -> bool
    where E: Element,
          F: FnMut(&E, ElementSelectorFlags),
{
    // Use the bloom filter to fast-reject.
    if let Some(hashes) = hashes {
        if let Some(filter) = context.bloom_filter {
            if !may_match::<E>(hashes, filter) {
                return false;
            }
        }
    }

    let mut local_context = LocalMatchingContext::new(context, selector);
    let iter = if offset == 0 {
        selector.iter()
    } else {
        selector.iter_from(offset)
    };
    matches_complex_selector(iter, element, &mut local_context, flags_setter)
}

/// Whether a compound selector matched, and whether it was the rightmost
/// selector inside the complex selector.
pub enum CompoundSelectorMatchingResult {
    /// The compound selector matched, and the next combinator offset is
    /// `next_combinator_offset`.
    ///
    /// If the next combinator offset is zero, it means that it's the rightmost
    /// selector.
    Matched { next_combinator_offset: usize, },
    /// The selector didn't match.
    NotMatched,
}

/// Matches a compound selector belonging to `selector`, starting at offset
/// `from_offset`, matching left to right.
///
/// Requires that `from_offset` points to a `Combinator`.
///
/// NOTE(emilio): This doesn't allow to match in the leftmost sequence of the
/// complex selector, but it happens to be the case we don't need it.
pub fn matches_compound_selector<E>(
    selector: &Selector<E::Impl>,
    mut from_offset: usize,
    context: &mut MatchingContext,
    element: &E,
) -> CompoundSelectorMatchingResult
where
    E: Element
{
    if cfg!(debug_assertions) {
        selector.combinator_at(from_offset); // This asserts.
    }

    let mut local_context = LocalMatchingContext::new(context, selector);
    for component in selector.iter_raw_parse_order_from(from_offset - 1) {
        if matches!(*component, Component::Combinator(..)) {
            return CompoundSelectorMatchingResult::Matched {
                next_combinator_offset: from_offset - 1,
            }
        }

        if !matches_simple_selector(
            component,
            element,
            &mut local_context,
            &RelevantLinkStatus::NotLooking,
            &mut |_, _| {}) {
            return CompoundSelectorMatchingResult::NotMatched;
        }

        from_offset -= 1;
    }

    return CompoundSelectorMatchingResult::Matched {
        next_combinator_offset: 0,
    }
}

/// Matches a complex selector.
pub fn matches_complex_selector<E, F>(mut iter: SelectorIter<E::Impl>,
                                      element: &E,
                                      context: &mut LocalMatchingContext<E::Impl>,
                                      flags_setter: &mut F)
                                      -> bool
    where E: Element,
          F: FnMut(&E, ElementSelectorFlags),
{
    if cfg!(debug_assertions) {
        if context.nesting_level == 0 &&
            context.shared.matching_mode == MatchingMode::ForStatelessPseudoElement {
            assert!(iter.clone().any(|c| {
                matches!(*c, Component::PseudoElement(..))
            }));
        }
    }

    // If this is the special pseudo-element mode, consume the ::pseudo-element
    // before proceeding, since the caller has already handled that part.
    if context.nesting_level == 0 &&
        context.shared.matching_mode == MatchingMode::ForStatelessPseudoElement {
        // Consume the pseudo.
        let pseudo = iter.next().unwrap();
        debug_assert!(matches!(*pseudo, Component::PseudoElement(..)),
                      "Used MatchingMode::ForStatelessPseudoElement in a non-pseudo selector");

        // The only other parser-allowed Component in this sequence is a state
        // class. We just don't match in that case.
        if let Some(s) = iter.next() {
            debug_assert!(matches!(*s, Component::NonTSPseudoClass(..)),
                          "Someone messed up pseudo-element parsing");
            return false;
        }

        // Advance to the non-pseudo-element part of the selector, and inform
        // the context.
        if iter.next_sequence().is_none() {
            return true;
        }
        context.note_position(&iter);
    }

    match matches_complex_selector_internal(iter,
                                            element,
                                            context,
                                            &mut RelevantLinkStatus::Looking,
                                            flags_setter) {
        SelectorMatchingResult::Matched => true,
        _ => false
    }
}

fn matches_complex_selector_internal<E, F>(mut selector_iter: SelectorIter<E::Impl>,
                                           element: &E,
                                           context: &mut LocalMatchingContext<E::Impl>,
                                           relevant_link: &mut RelevantLinkStatus,
                                           flags_setter: &mut F)
                                           -> SelectorMatchingResult
     where E: Element,
           F: FnMut(&E, ElementSelectorFlags),
{
    *relevant_link = relevant_link.examine_potential_link(element, &mut context.shared);

    debug!("Matching complex selector {:?} for {:?}, relevant link {:?}",
           selector_iter, element, relevant_link);

    let matches_all_simple_selectors = selector_iter.all(|simple| {
        matches_simple_selector(simple, element, context, &relevant_link, flags_setter)
    });

    let combinator = selector_iter.next_sequence();
    let siblings = combinator.map_or(false, |c| c.is_sibling());
    if siblings {
        flags_setter(element, ElementSelectorFlags::HAS_SLOW_SELECTOR_LATER_SIBLINGS);
    }

    if !matches_all_simple_selectors {
        return SelectorMatchingResult::NotMatchedAndRestartFromClosestLaterSibling;
    }

    match combinator {
        None => SelectorMatchingResult::Matched,
        Some(c) => {
            let (mut next_element, candidate_not_found) = match c {
                Combinator::NextSibling | Combinator::LaterSibling => {
                    // Only ancestor combinators are allowed while looking for
                    // relevant links, so switch to not looking.
                    *relevant_link = RelevantLinkStatus::NotLooking;
                    (element.prev_sibling_element(),
                     SelectorMatchingResult::NotMatchedAndRestartFromClosestDescendant)
                }
                Combinator::Child | Combinator::Descendant => {
                    if element.blocks_ancestor_combinators() {
                        (None, SelectorMatchingResult::NotMatchedGlobally)
                    } else {
                        (element.parent_element(),
                         SelectorMatchingResult::NotMatchedGlobally)
                    }
                }
                Combinator::PseudoElement => {
                    (element.pseudo_element_originating_element(),
                     SelectorMatchingResult::NotMatchedGlobally)
                }
            };

            loop {
                let element = match next_element {
                    None => return candidate_not_found,
                    Some(next_element) => next_element,
                };
                // Note in which compound selector are we currently.
                context.note_position(&selector_iter);
                let result = matches_complex_selector_internal(selector_iter.clone(),
                                                               &element,
                                                               context,
                                                               relevant_link,
                                                               flags_setter);
                match (result, c) {
                    // Return the status immediately.
                    (SelectorMatchingResult::Matched, _) => return result,
                    (SelectorMatchingResult::NotMatchedGlobally, _) => return result,

                    // Upgrade the failure status to
                    // NotMatchedAndRestartFromClosestDescendant.
                    (_, Combinator::PseudoElement) |
                    (_, Combinator::Child) => return SelectorMatchingResult::NotMatchedAndRestartFromClosestDescendant,

                    // Return the status directly.
                    (_, Combinator::NextSibling) => return result,

                    // If the failure status is NotMatchedAndRestartFromClosestDescendant
                    // and combinator is Combinator::LaterSibling, give up this Combinator::LaterSibling matching
                    // and restart from the closest descendant combinator.
                    (SelectorMatchingResult::NotMatchedAndRestartFromClosestDescendant, Combinator::LaterSibling)
                        => return result,

                    // The Combinator::Descendant combinator and the status is
                    // NotMatchedAndRestartFromClosestLaterSibling or
                    // NotMatchedAndRestartFromClosestDescendant,
                    // or the Combinator::LaterSibling combinator and the status is
                    // NotMatchedAndRestartFromClosestDescendant
                    // can continue to matching on the next candidate element.
                    _ => {},
                }
                next_element = if siblings {
                    element.prev_sibling_element()
                } else {
                    element.parent_element()
                };
            }
        }
    }
}

/// Determines whether the given element matches the given single selector.
#[inline]
fn matches_simple_selector<E, F>(
        selector: &Component<E::Impl>,
        element: &E,
        context: &mut LocalMatchingContext<E::Impl>,
        relevant_link: &RelevantLinkStatus,
        flags_setter: &mut F)
        -> bool
    where E: Element,
          F: FnMut(&E, ElementSelectorFlags),
{
    match *selector {
        Component::Combinator(_) => unreachable!(),
        Component::PseudoElement(ref pseudo) => {
            element.match_pseudo_element(pseudo, context.shared)
        }
        Component::LocalName(LocalName { ref name, ref lower_name }) => {
            let is_html = element.is_html_element_in_html_document();
            element.get_local_name() == select_name(is_html, name, lower_name).borrow()
        }
        Component::ExplicitUniversalType |
        Component::ExplicitAnyNamespace => {
            true
        }
        Component::Namespace(_, ref url) |
        Component::DefaultNamespace(ref url) => {
            element.get_namespace() == url.borrow()
        }
        Component::ExplicitNoNamespace => {
            let ns = ::selectors::parser::namespace_empty_string::<E::Impl>();
            element.get_namespace() == ns.borrow()
        }
        Component::ID(ref id) => {
            element.has_id(id, context.shared.classes_and_ids_case_sensitivity())
        }
        Component::Class(ref class) => {
            element.has_class(class, context.shared.classes_and_ids_case_sensitivity())
        }
        Component::AttributeInNoNamespaceExists { ref local_name, ref local_name_lower } => {
            let is_html = element.is_html_element_in_html_document();
            element.attr_matches(
                &NamespaceConstraint::Specific(&::selectors::parser::namespace_empty_string::<E::Impl>()),
                select_name(is_html, local_name, local_name_lower),
                &AttrSelectorOperation::Exists
            )
        }
        Component::AttributeInNoNamespace {
            ref local_name,
            ref local_name_lower,
            ref value,
            operator,
            case_sensitivity,
            never_matches,
        } => {
            if never_matches {
                return false
            }
            let is_html = element.is_html_element_in_html_document();
            element.attr_matches(
                &NamespaceConstraint::Specific(&::selectors::parser::namespace_empty_string::<E::Impl>()),
                select_name(is_html, local_name, local_name_lower),
                &AttrSelectorOperation::WithValue {
                    operator: operator,
                    case_sensitivity: case_sensitivity.to_unconditional(is_html),
                    expected_value: value,
                }
            )
        }
        Component::AttributeOther(ref attr_sel) => {
            if attr_sel.never_matches {
                return false
            }
            let is_html = element.is_html_element_in_html_document();
            element.attr_matches(
                &attr_sel.namespace(),
                select_name(is_html, &attr_sel.local_name, &attr_sel.local_name_lower),
                &match attr_sel.operation {
                    ParsedAttrSelectorOperation::Exists => AttrSelectorOperation::Exists,
                    ParsedAttrSelectorOperation::WithValue {
                        operator,
                        case_sensitivity,
                        ref expected_value,
                    } => {
                        AttrSelectorOperation::WithValue {
                            operator: operator,
                            case_sensitivity: case_sensitivity.to_unconditional(is_html),
                            expected_value: expected_value,
                        }
                    }
                }
            )
        }
        Component::NonTSPseudoClass(ref pc) => {
            element.match_non_ts_pseudo_class(pc, context, relevant_link, flags_setter)
        }
        Component::FirstChild => {
            matches_first_child(element, flags_setter)
        }
        Component::LastChild => {
            matches_last_child(element, flags_setter)
        }
        Component::OnlyChild => {
            matches_first_child(element, flags_setter) &&
            matches_last_child(element, flags_setter)
        }
        Component::Root => {
            element.is_root()
        }
        Component::Empty => {
            flags_setter(element, ElementSelectorFlags::HAS_EMPTY_SELECTOR);
            element.is_empty()
        }
        Component::NthChild(a, b) => {
            matches_generic_nth_child(element, context, a, b, false, false, flags_setter)
        }
        Component::NthLastChild(a, b) => {
            matches_generic_nth_child(element, context, a, b, false, true, flags_setter)
        }
        Component::NthOfType(a, b) => {
            matches_generic_nth_child(element, context, a, b, true, false, flags_setter)
        }
        Component::NthLastOfType(a, b) => {
            matches_generic_nth_child(element, context, a, b, true, true, flags_setter)
        }
        Component::FirstOfType => {
            matches_generic_nth_child(element, context, 0, 1, true, false, flags_setter)
        }
        Component::LastOfType => {
            matches_generic_nth_child(element, context, 0, 1, true, true, flags_setter)
        }
        Component::OnlyOfType => {
            matches_generic_nth_child(element, context, 0, 1, true, false, flags_setter) &&
            matches_generic_nth_child(element, context, 0, 1, true, true, flags_setter)
        }
        Component::Negation(ref negated) => {
            context.nesting_level += 1;
            let result = !negated.iter().all(|ss| {
                matches_simple_selector(ss, element, context,
                                        relevant_link, flags_setter)
            });
            context.nesting_level -= 1;
            result
        }
    }
}

fn select_name<'a, T>(is_html: bool, local_name: &'a T, local_name_lower: &'a T) -> &'a T {
    if is_html {
        local_name_lower
    } else {
        local_name
    }
}

#[inline]
fn matches_generic_nth_child<E, F>(element: &E,
                                   context: &mut LocalMatchingContext<E::Impl>,
                                   a: i32,
                                   b: i32,
                                   is_of_type: bool,
                                   is_from_end: bool,
                                   flags_setter: &mut F)
                                   -> bool
    where E: Element,
          F: FnMut(&E, ElementSelectorFlags),
{
    if element.ignores_nth_child_selectors() {
        return false;
    }

    flags_setter(element, if is_from_end {
        ElementSelectorFlags::HAS_SLOW_SELECTOR
    } else {
        ElementSelectorFlags::HAS_SLOW_SELECTOR_LATER_SIBLINGS
    });

    // Grab a reference to the appropriate cache.
    let mut cache = context.shared.nth_index_cache.as_mut().map(|c| {
        c.get(is_of_type, is_from_end)
    });

    // Lookup or compute the index.
    let index = if let Some(i) = cache.as_mut().and_then(|c| c.lookup(element.opaque())) {
        i
    } else {
        let i = nth_child_index(element, is_of_type, is_from_end, cache.as_mut().map(|s| &mut **s));
        cache.as_mut().map(|c| c.insert(element.opaque(), i));
        i
    };
    debug_assert_eq!(index, nth_child_index(element, is_of_type, is_from_end, None), "invalid cache");

    // Is there a non-negative integer n such that An+B=index?
    match index.checked_sub(b) {
        None => false,
        Some(an) => match an.checked_div(a) {
            Some(n) => n >= 0 && a * n == an,
            None /* a == 0 */ => an == 0,
        },
    }
}

#[inline]
fn same_type<E: Element>(a: &E, b: &E) -> bool {
    a.get_local_name() == b.get_local_name() &&
    a.get_namespace() == b.get_namespace()
}

#[inline]
fn nth_child_index<E>(
    element: &E,
    is_of_type: bool,
    is_from_end: bool,
    mut cache: Option<&mut NthIndexCacheInner>,
) -> i32
where
    E: Element,
{
    // The traversal mostly processes siblings left to right. So when we walk
    // siblings to the right when computing NthLast/NthLastOfType we're unlikely
    // to get cache hits along the way. As such, we take the hit of walking the
    // siblings to the left checking the cache in the is_from_end case (this
    // matches what Gecko does). The indices-from-the-left is handled during the
    // regular look further below.
    if let Some(ref mut c) = cache {
        if is_from_end && !c.is_empty() {
            let mut index: i32 = 1;
            let mut curr = element.clone();
            while let Some(e) = curr.prev_sibling_element() {
                curr = e;
                if !is_of_type || same_type(element, &curr) {
                    if let Some(i) = c.lookup(curr.opaque()) {
                        return i - index;
                    }
                    index += 1;
                }
            }
        }
    }

    let mut index: i32 = 1;
    let mut curr = element.clone();
    let next = |e: E| if is_from_end { e.next_sibling_element() } else { e.prev_sibling_element() };
    while let Some(e) = next(curr) {
        curr = e;
        if !is_of_type || same_type(element, &curr) {
            // If we're computing indices from the left, check each element in the
            // cache. We handle the indices-from-the-right case at the top of this
            // function.
            if !is_from_end {
                if let Some(i) = cache.as_mut().and_then(|c| c.lookup(curr.opaque())) {
                    return i + index
                }
            }
            index += 1;
        }
    }

    index
}

#[inline]
fn matches_first_child<E, F>(element: &E, flags_setter: &mut F) -> bool
    where E: Element,
          F: FnMut(&E, ElementSelectorFlags),
{
    flags_setter(element, ElementSelectorFlags::HAS_EDGE_CHILD_SELECTOR);
    element.prev_sibling_element().is_none()
}

#[inline]
fn matches_last_child<E, F>(element: &E, flags_setter: &mut F) -> bool
    where E: Element,
          F: FnMut(&E, ElementSelectorFlags),
{
    flags_setter(element, ElementSelectorFlags::HAS_EDGE_CHILD_SELECTOR);
    element.next_sibling_element().is_none()
}