Run rustfmt on selectors, servo_arc, and style.

This was generated with:

./mach cargo fmt --package selectors &&
./mach cargo fmt --package servo_arc &&
./mach cargo fmt --package style

Using rustfmt 0.4.1-nightly (a4462d1 2018-03-26)
This commit is contained in:
Bobby Holley 2018-04-10 17:35:15 -07:00
parent f7ae1a37e3
commit c99bcdd4b8
181 changed files with 9981 additions and 7933 deletions

View file

@ -19,9 +19,7 @@ impl<Impl: SelectorImpl> AttrSelectorWithNamespace<Impl> {
pub fn namespace(&self) -> NamespaceConstraint<&Impl::NamespaceUrl> {
match self.namespace {
NamespaceConstraint::Any => NamespaceConstraint::Any,
NamespaceConstraint::Specific((_, ref url)) => {
NamespaceConstraint::Specific(url)
}
NamespaceConstraint::Specific((_, ref url)) => NamespaceConstraint::Specific(url),
}
}
}
@ -41,7 +39,7 @@ pub enum ParsedAttrSelectorOperation<AttrValue> {
operator: AttrSelectorOperator,
case_sensitivity: ParsedCaseSensitivity,
expected_value: AttrValue,
}
},
}
#[derive(Clone, Eq, PartialEq)]
@ -51,16 +49,25 @@ pub enum AttrSelectorOperation<AttrValue> {
operator: AttrSelectorOperator,
case_sensitivity: CaseSensitivity,
expected_value: AttrValue,
}
},
}
impl<AttrValue> AttrSelectorOperation<AttrValue> {
pub fn eval_str(&self, element_attr_value: &str) -> bool where AttrValue: AsRef<str> {
pub fn eval_str(&self, element_attr_value: &str) -> bool
where
AttrValue: AsRef<str>,
{
match *self {
AttrSelectorOperation::Exists => true,
AttrSelectorOperation::WithValue { operator, case_sensitivity, ref expected_value } => {
operator.eval_str(element_attr_value, expected_value.as_ref(), case_sensitivity)
}
AttrSelectorOperation::WithValue {
operator,
case_sensitivity,
ref expected_value,
} => operator.eval_str(
element_attr_value,
expected_value.as_ref(),
case_sensitivity,
),
}
}
}
@ -76,7 +83,10 @@ pub enum AttrSelectorOperator {
}
impl ToCss for AttrSelectorOperator {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where
W: fmt::Write,
{
// https://drafts.csswg.org/cssom/#serializing-selectors
// See "attribute selector".
dest.write_str(match *self {
@ -91,34 +101,30 @@ impl ToCss for AttrSelectorOperator {
}
impl AttrSelectorOperator {
pub fn eval_str(self, element_attr_value: &str, attr_selector_value: &str,
case_sensitivity: CaseSensitivity) -> bool {
pub fn eval_str(
self,
element_attr_value: &str,
attr_selector_value: &str,
case_sensitivity: CaseSensitivity,
) -> bool {
let e = element_attr_value.as_bytes();
let s = attr_selector_value.as_bytes();
let case = case_sensitivity;
match self {
AttrSelectorOperator::Equal => {
case.eq(e, s)
}
AttrSelectorOperator::Prefix => {
e.len() >= s.len() && case.eq(&e[..s.len()], s)
}
AttrSelectorOperator::Equal => case.eq(e, s),
AttrSelectorOperator::Prefix => e.len() >= s.len() && case.eq(&e[..s.len()], s),
AttrSelectorOperator::Suffix => {
e.len() >= s.len() && case.eq(&e[(e.len() - s.len())..], s)
}
},
AttrSelectorOperator::Substring => {
case.contains(element_attr_value, attr_selector_value)
}
AttrSelectorOperator::Includes => {
element_attr_value.split(SELECTOR_WHITESPACE)
.any(|part| case.eq(part.as_bytes(), s))
}
},
AttrSelectorOperator::Includes => element_attr_value
.split(SELECTOR_WHITESPACE)
.any(|part| case.eq(part.as_bytes(), s)),
AttrSelectorOperator::DashMatch => {
case.eq(e, s) || (
e.get(s.len()) == Some(&b'-') &&
case.eq(&e[..s.len()], s)
)
}
case.eq(e, s) || (e.get(s.len()) == Some(&b'-') && case.eq(&e[..s.len()], s))
},
}
}
}
@ -137,12 +143,13 @@ impl ParsedCaseSensitivity {
pub fn to_unconditional(self, is_html_element_in_html_document: bool) -> CaseSensitivity {
match self {
ParsedCaseSensitivity::AsciiCaseInsensitiveIfInHtmlElementInHtmlDocument
if is_html_element_in_html_document => {
if is_html_element_in_html_document =>
{
CaseSensitivity::AsciiCaseInsensitive
}
},
ParsedCaseSensitivity::AsciiCaseInsensitiveIfInHtmlElementInHtmlDocument => {
CaseSensitivity::CaseSensitive
}
},
ParsedCaseSensitivity::CaseSensitive => CaseSensitivity::CaseSensitive,
ParsedCaseSensitivity::AsciiCaseInsensitive => CaseSensitivity::AsciiCaseInsensitive,
}
@ -170,14 +177,12 @@ impl CaseSensitivity {
if let Some((&n_first_byte, n_rest)) = needle.as_bytes().split_first() {
haystack.bytes().enumerate().any(|(i, byte)| {
if !byte.eq_ignore_ascii_case(&n_first_byte) {
return false
return false;
}
let after_this_byte = &haystack.as_bytes()[i + 1..];
match after_this_byte.get(..n_rest.len()) {
None => false,
Some(haystack_slice) => {
haystack_slice.eq_ignore_ascii_case(n_rest)
}
Some(haystack_slice) => haystack_slice.eq_ignore_ascii_case(n_rest),
}
})
} else {
@ -185,7 +190,7 @@ impl CaseSensitivity {
// though these cases should be handled with *NeverMatches and never go here.
true
}
}
},
}
}
}

View file

@ -72,11 +72,17 @@ pub type NonCountingBloomFilter = CountingBloomFilter<BloomStorageBool>;
/// positive rate for N == 100 and to quite bad false positive
/// rates for larger N.
#[derive(Clone)]
pub struct CountingBloomFilter<S> where S: BloomStorage {
pub struct CountingBloomFilter<S>
where
S: BloomStorage,
{
storage: S,
}
impl<S> CountingBloomFilter<S> where S: BloomStorage {
impl<S> CountingBloomFilter<S>
where
S: BloomStorage,
{
/// Creates a new bloom filter.
#[inline]
pub fn new() -> Self {
@ -128,8 +134,7 @@ impl<S> CountingBloomFilter<S> where S: BloomStorage {
#[inline]
pub fn might_contain_hash(&self, hash: u32) -> bool {
!self.storage.first_slot_is_empty(hash) &&
!self.storage.second_slot_is_empty(hash)
!self.storage.first_slot_is_empty(hash) && !self.storage.second_slot_is_empty(hash)
}
/// Check whether the filter might contain an item. This can
@ -142,7 +147,10 @@ impl<S> CountingBloomFilter<S> where S: BloomStorage {
}
}
impl<S> Debug for CountingBloomFilter<S> where S: BloomStorage {
impl<S> Debug for CountingBloomFilter<S>
where
S: BloomStorage,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut slots_used = 0;
for i in 0..ARRAY_SIZE {
@ -154,7 +162,7 @@ impl<S> Debug for CountingBloomFilter<S> where S: BloomStorage {
}
}
pub trait BloomStorage : Clone + Default {
pub trait BloomStorage: Clone + Default {
fn slot_is_empty(&self, index: usize) -> bool;
fn adjust_slot(&mut self, index: usize, increment: bool);
fn is_zeroed(&self) -> bool;
@ -199,7 +207,8 @@ impl BloomStorage for BloomStorageU8 {
#[inline]
fn adjust_slot(&mut self, index: usize, increment: bool) {
let slot = &mut self.counters[index];
if *slot != 0xff { // full
if *slot != 0xff {
// full
if increment {
*slot += 1;
} else {
@ -249,8 +258,10 @@ impl BloomStorage for BloomStorageBool {
// Since we have only one bit for storage, decrementing it
// should never do anything. Assert against an accidental
// decrementing of a bit that was never set.
assert!(increment || (*byte & bit) != 0,
"should not decrement if slot is already false");
assert!(
increment || (*byte & bit) != 0,
"should not decrement if slot is already false"
);
if increment {
*byte |= bit;
@ -314,34 +325,33 @@ fn create_and_insert_some_stuff() {
transmute::<[u8; ARRAY_SIZE % 8], [u8; 0]>([]);
}
for i in 0_usize .. 1000 {
for i in 0_usize..1000 {
bf.insert(&i);
}
for i in 0_usize .. 1000 {
for i in 0_usize..1000 {
assert!(bf.might_contain(&i));
}
let false_positives =
(1001_usize .. 2000).filter(|i| bf.might_contain(i)).count();
let false_positives = (1001_usize..2000).filter(|i| bf.might_contain(i)).count();
assert!(false_positives < 150, "{} is not < 150", false_positives); // 15%.
for i in 0_usize .. 100 {
for i in 0_usize..100 {
bf.remove(&i);
}
for i in 100_usize .. 1000 {
for i in 100_usize..1000 {
assert!(bf.might_contain(&i));
}
let false_positives = (0_usize .. 100).filter(|i| bf.might_contain(i)).count();
let false_positives = (0_usize..100).filter(|i| bf.might_contain(i)).count();
assert!(false_positives < 20, "{} is not < 20", false_positives); // 20%.
bf.clear();
for i in 0_usize .. 2000 {
for i in 0_usize..2000 {
assert!(!bf.might_contain(&i));
}
}
@ -376,13 +386,13 @@ mod bench {
let mut gen1 = HashGenerator::default();
let mut gen2 = HashGenerator::default();
let mut bf = BloomFilter::new();
for _ in 0_usize .. 1000 {
for _ in 0_usize..1000 {
bf.insert_hash(gen1.next());
}
for _ in 0_usize .. 100 {
for _ in 0_usize..100 {
bf.remove_hash(gen2.next());
}
for _ in 100_usize .. 200 {
for _ in 100_usize..200 {
test::black_box(bf.might_contain_hash(gen2.next()));
}
});
@ -392,8 +402,10 @@ mod bench {
fn might_contain_10(b: &mut test::Bencher) {
let bf = BloomFilter::new();
let mut gen = HashGenerator::default();
b.iter(|| for _ in 0..10 {
test::black_box(bf.might_contain_hash(gen.next()));
b.iter(|| {
for _ in 0..10 {
test::black_box(bf.might_contain_hash(gen.next()));
}
});
}
@ -407,8 +419,10 @@ mod bench {
fn insert_10(b: &mut test::Bencher) {
let mut bf = BloomFilter::new();
let mut gen = HashGenerator::default();
b.iter(|| for _ in 0..10 {
test::black_box(bf.insert_hash(gen.next()));
b.iter(|| {
for _ in 0..10 {
test::black_box(bf.insert_hash(gen.next()));
}
});
}
@ -417,8 +431,10 @@ mod bench {
let mut bf = BloomFilter::new();
let mut gen = HashGenerator::default();
// Note: this will underflow, and that's ok.
b.iter(|| for _ in 0..10 {
bf.remove_hash(gen.next())
b.iter(|| {
for _ in 0..10 {
bf.remove_hash(gen.next())
}
});
}
}

View file

@ -116,12 +116,13 @@ impl<Impl: SelectorImpl> SelectorBuilder<Impl> {
self.build_with_specificity_and_flags(spec)
}
/// Builds with an explicit SpecificityAndFlags. This is separated from build() so
/// that unit tests can pass an explicit specificity.
#[inline(always)]
pub fn build_with_specificity_and_flags(&mut self, spec: SpecificityAndFlags)
-> ThinArc<SpecificityAndFlags, Component<Impl>> {
pub fn build_with_specificity_and_flags(
&mut self,
spec: SpecificityAndFlags,
) -> ThinArc<SpecificityAndFlags, Component<Impl>> {
// First, compute the total number of Components we'll need to allocate
// space for.
let full_len = self.simple_selectors.len() + self.combinators.len();
@ -159,9 +160,8 @@ struct SelectorBuilderIter<'a, Impl: SelectorImpl> {
impl<'a, Impl: SelectorImpl> ExactSizeIterator for SelectorBuilderIter<'a, Impl> {
fn len(&self) -> usize {
self.current_simple_selectors.len() +
self.rest_of_simple_selectors.len() +
self.combinators.len()
self.current_simple_selectors.len() + self.rest_of_simple_selectors.len() +
self.combinators.len()
}
}
@ -173,9 +173,7 @@ impl<'a, Impl: SelectorImpl> Iterator for SelectorBuilderIter<'a, Impl> {
// Move a simple selector out of this slice iterator.
// This is safe because weve called SmallVec::set_len(0) above,
// so SmallVec::drop wont drop this simple selector.
unsafe {
Some(ptr::read(simple_selector_ref))
}
unsafe { Some(ptr::read(simple_selector_ref)) }
} else {
self.combinators.next().map(|(combinator, len)| {
let (rest, current) = split_from_end(self.rest_of_simple_selectors, len);
@ -235,10 +233,8 @@ impl Add for Specificity {
fn add(self, rhs: Specificity) -> Specificity {
Specificity {
id_selectors: self.id_selectors + rhs.id_selectors,
class_like_selectors:
self.class_like_selectors + rhs.class_like_selectors,
element_selectors:
self.element_selectors + rhs.element_selectors,
class_like_selectors: self.class_like_selectors + rhs.class_like_selectors,
element_selectors: self.element_selectors + rhs.element_selectors,
}
}
}
@ -266,28 +262,28 @@ impl From<u32> for Specificity {
impl From<Specificity> for u32 {
fn from(specificity: Specificity) -> u32 {
cmp::min(specificity.id_selectors, MAX_10BIT) << 20
| cmp::min(specificity.class_like_selectors, MAX_10BIT) << 10
| cmp::min(specificity.element_selectors, MAX_10BIT)
cmp::min(specificity.id_selectors, MAX_10BIT) << 20 |
cmp::min(specificity.class_like_selectors, MAX_10BIT) << 10 |
cmp::min(specificity.element_selectors, MAX_10BIT)
}
}
fn specificity<Impl>(iter: slice::Iter<Component<Impl>>) -> u32
where Impl: SelectorImpl
where
Impl: SelectorImpl,
{
complex_selector_specificity(iter).into()
}
fn complex_selector_specificity<Impl>(mut iter: slice::Iter<Component<Impl>>)
-> Specificity
where Impl: SelectorImpl
fn complex_selector_specificity<Impl>(mut iter: slice::Iter<Component<Impl>>) -> Specificity
where
Impl: SelectorImpl,
{
fn simple_selector_specificity<Impl>(
simple_selector: &Component<Impl>,
specificity: &mut Specificity,
)
where
Impl: SelectorImpl
) where
Impl: SelectorImpl,
{
match *simple_selector {
Component::Combinator(..) => unreachable!(),
@ -298,44 +294,41 @@ fn complex_selector_specificity<Impl>(mut iter: slice::Iter<Component<Impl>>)
//
// Though other engines compute it dynamically, so maybe we should
// do that instead, eventually.
Component::Slotted(..) |
Component::PseudoElement(..) |
Component::LocalName(..) => {
Component::Slotted(..) | Component::PseudoElement(..) | Component::LocalName(..) => {
specificity.element_selectors += 1
}
Component::ID(..) => {
specificity.id_selectors += 1
}
},
Component::ID(..) => specificity.id_selectors += 1,
Component::Class(..) |
Component::AttributeInNoNamespace { .. } |
Component::AttributeInNoNamespaceExists { .. } |
Component::AttributeOther(..) |
Component::FirstChild | Component::LastChild |
Component::OnlyChild | Component::Root |
Component::Empty | Component::Scope |
Component::FirstChild |
Component::LastChild |
Component::OnlyChild |
Component::Root |
Component::Empty |
Component::Scope |
Component::Host(..) |
Component::NthChild(..) |
Component::NthLastChild(..) |
Component::NthOfType(..) |
Component::NthLastOfType(..) |
Component::FirstOfType | Component::LastOfType |
Component::FirstOfType |
Component::LastOfType |
Component::OnlyOfType |
Component::NonTSPseudoClass(..) => {
specificity.class_like_selectors += 1
}
Component::NonTSPseudoClass(..) => specificity.class_like_selectors += 1,
Component::ExplicitUniversalType |
Component::ExplicitAnyNamespace |
Component::ExplicitNoNamespace |
Component::DefaultNamespace(..) |
Component::Namespace(..) => {
// Does not affect specificity
}
},
Component::Negation(ref negated) => {
for ss in negated.iter() {
simple_selector_specificity(&ss, specificity);
}
}
},
}
}

View file

@ -54,7 +54,7 @@ impl VisitedHandlingMode {
matches!(
*self,
VisitedHandlingMode::RelevantLinkVisited |
VisitedHandlingMode::AllLinksVisitedAndUnvisited
VisitedHandlingMode::AllLinksVisitedAndUnvisited
)
}
@ -63,7 +63,7 @@ impl VisitedHandlingMode {
matches!(
*self,
VisitedHandlingMode::AllLinksUnvisited |
VisitedHandlingMode::AllLinksVisitedAndUnvisited
VisitedHandlingMode::AllLinksVisitedAndUnvisited
)
}
}
@ -85,8 +85,7 @@ impl QuirksMode {
#[inline]
pub fn classes_and_ids_case_sensitivity(self) -> CaseSensitivity {
match self {
QuirksMode::NoQuirks |
QuirksMode::LimitedQuirks => CaseSensitivity::CaseSensitive,
QuirksMode::NoQuirks | QuirksMode::LimitedQuirks => CaseSensitivity::CaseSensitive,
QuirksMode::Quirks => CaseSensitivity::AsciiCaseInsensitive,
}
}
@ -161,7 +160,7 @@ where
bloom_filter,
nth_index_cache,
VisitedHandlingMode::AllLinksUnvisited,
quirks_mode
quirks_mode,
)
}
@ -196,8 +195,7 @@ where
#[inline]
pub fn set_quirks_mode(&mut self, quirks_mode: QuirksMode) {
self.quirks_mode = quirks_mode;
self.classes_and_ids_case_sensitivity =
quirks_mode.classes_and_ids_case_sensitivity();
self.classes_and_ids_case_sensitivity = quirks_mode.classes_and_ids_case_sensitivity();
}
/// Whether we're matching a nested selector.
@ -249,10 +247,7 @@ where
where
F: FnOnce(&mut Self) -> R,
{
debug_assert!(
!self.in_negation,
"Someone messed up parsing?"
);
debug_assert!(!self.in_negation, "Someone messed up parsing?");
self.in_negation = true;
let result = self.nest(f);
self.in_negation = false;
@ -284,11 +279,7 @@ where
/// Runs F with a given shadow host which is the root of the tree whose
/// rules we're matching.
#[inline]
pub fn with_shadow_host<F, E, R>(
&mut self,
host: Option<E>,
f: F,
) -> R
pub fn with_shadow_host<F, E, R>(&mut self, host: Option<E>, f: F) -> R
where
E: Element,
F: FnOnce(&mut Self) -> R,

View file

@ -5,11 +5,15 @@
// Make |cargo bench| work.
#![cfg_attr(feature = "bench", feature(test))]
#[macro_use] extern crate bitflags;
#[macro_use] extern crate cssparser;
#[macro_use]
extern crate bitflags;
#[macro_use]
extern crate cssparser;
extern crate fnv;
#[macro_use] extern crate log;
#[macro_use] extern crate matches;
#[macro_use]
extern crate log;
#[macro_use]
extern crate matches;
extern crate phf;
extern crate precomputed_hash;
extern crate servo_arc;
@ -27,5 +31,5 @@ mod tree;
pub mod visitor;
pub use nth_index_cache::NthIndexCache;
pub use parser::{SelectorImpl, Parser, SelectorList};
pub use parser::{Parser, SelectorImpl, SelectorList};
pub use tree::{Element, OpaqueElement};

View file

@ -2,11 +2,11 @@
* 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 attr::{ParsedAttrSelectorOperation, AttrSelectorOperation, NamespaceConstraint};
use bloom::{BLOOM_HASH_MASK, BloomFilter};
use attr::{AttrSelectorOperation, NamespaceConstraint, ParsedAttrSelectorOperation};
use bloom::{BloomFilter, BLOOM_HASH_MASK};
use nth_index_cache::NthIndexCacheInner;
use parser::{AncestorHashes, Combinator, Component, LocalName};
use parser::{Selector, SelectorImpl, SelectorIter, SelectorList, NonTSPseudoClass};
use parser::{NonTSPseudoClass, Selector, SelectorImpl, SelectorIter, SelectorList};
use std::borrow::Borrow;
use std::iter;
use tree::Element;
@ -52,8 +52,8 @@ impl ElementSelectorFlags {
/// 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)
ElementSelectorFlags::HAS_SLOW_SELECTOR_LATER_SIBLINGS |
ElementSelectorFlags::HAS_EDGE_CHILD_SELECTOR)
}
}
@ -70,19 +70,12 @@ pub fn matches_selector_list<E>(
context: &mut MatchingContext<E::Impl>,
) -> bool
where
E: Element
E: Element,
{
// This is pretty much any(..) but manually inlined because the compiler
// refuses to do so from querySelector / querySelectorAll.
for selector in &selector_list.0 {
let matches = matches_selector(
selector,
0,
None,
element,
context,
&mut |_, _| {},
);
let matches = matches_selector(selector, 0, None, element, context, &mut |_, _| {});
if matches {
return true;
@ -219,7 +212,7 @@ pub enum CompoundSelectorMatchingResult {
FullyMatched,
/// The compound selector matched, and the next combinator offset is
/// `next_combinator_offset`.
Matched { next_combinator_offset: usize, },
Matched { next_combinator_offset: usize },
/// The selector didn't match.
NotMatched,
}
@ -238,7 +231,7 @@ pub fn matches_compound_selector_from<E>(
element: &E,
) -> CompoundSelectorMatchingResult
where
E: Element
E: Element,
{
if cfg!(debug_assertions) && from_offset != 0 {
selector.combinator_at_parse_order(from_offset - 1); // This asserts.
@ -267,12 +260,12 @@ where
let iter = selector.iter_from(selector.len() - from_offset);
debug_assert!(
iter.clone().next().is_some() || (
from_offset != selector.len() && matches!(
selector.combinator_at_parse_order(from_offset),
Combinator::SlotAssignment | Combinator::PseudoElement
)
),
iter.clone().next().is_some() ||
(from_offset != selector.len() &&
matches!(
selector.combinator_at_parse_order(from_offset),
Combinator::SlotAssignment | Combinator::PseudoElement
)),
"Got the math wrong: {:?} | {:?} | {} {}",
selector,
selector.iter_raw_match_order().as_slice(),
@ -281,12 +274,7 @@ where
);
for component in iter {
if !matches_simple_selector(
component,
element,
&mut local_context,
&mut |_, _| {}
) {
if !matches_simple_selector(component, element, &mut local_context, &mut |_, _| {}) {
return CompoundSelectorMatchingResult::NotMatched;
}
}
@ -294,7 +282,7 @@ where
if from_offset != selector.len() {
return CompoundSelectorMatchingResult::Matched {
next_combinator_offset: from_offset,
}
};
}
CompoundSelectorMatchingResult::FullyMatched
@ -314,8 +302,7 @@ where
{
// If this is the special pseudo-element mode, consume the ::pseudo-element
// before proceeding, since the caller has already handled that part.
if context.matching_mode() == MatchingMode::ForStatelessPseudoElement &&
!context.is_nested() {
if context.matching_mode() == MatchingMode::ForStatelessPseudoElement && !context.is_nested() {
// Consume the pseudo.
match *iter.next().unwrap() {
Component::PseudoElement(ref pseudo) => {
@ -324,19 +311,23 @@ where
return false;
}
}
}
},
_ => {
debug_assert!(false,
"Used MatchingMode::ForStatelessPseudoElement \
in a non-pseudo selector");
}
debug_assert!(
false,
"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");
debug_assert!(
matches!(*s, Component::NonTSPseudoClass(..)),
"Someone messed up pseudo-element parsing"
);
return false;
}
@ -347,17 +338,12 @@ where
}
}
let result = matches_complex_selector_internal(
iter,
element,
context,
flags_setter,
Rightmost::Yes,
);
let result =
matches_complex_selector_internal(iter, element, context, flags_setter, Rightmost::Yes);
match result {
SelectorMatchingResult::Matched => true,
_ => false
_ => false,
}
}
@ -378,36 +364,33 @@ fn matches_hover_and_active_quirk<Impl: SelectorImpl>(
// This compound selector had a pseudo-element to the right that we
// intentionally skipped.
if rightmost == Rightmost::Yes &&
context.matching_mode() == MatchingMode::ForStatelessPseudoElement {
context.matching_mode() == MatchingMode::ForStatelessPseudoElement
{
return MatchesHoverAndActiveQuirk::No;
}
let all_match = selector_iter.clone().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) => {
pseudo_class.is_active_or_hover()
},
_ => true,
}
let all_match = selector_iter.clone().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) => pseudo_class.is_active_or_hover(),
_ => true,
});
if all_match {
@ -433,19 +416,15 @@ where
E: Element,
{
match combinator {
Combinator::NextSibling |
Combinator::LaterSibling => {
element.prev_sibling_element()
}
Combinator::Child |
Combinator::Descendant => {
Combinator::NextSibling | Combinator::LaterSibling => element.prev_sibling_element(),
Combinator::Child | Combinator::Descendant => {
if element.blocks_ancestor_combinators() {
return None;
}
match element.parent_element() {
Some(e) => return Some(e),
None => {}
None => {},
}
if !element.parent_node_is_shadow_root() {
@ -473,14 +452,16 @@ where
}
element.containing_shadow_host()
}
},
Combinator::SlotAssignment => {
debug_assert!(element.assigned_slot().map_or(true, |s| s.is_html_slot_element()));
debug_assert!(
element
.assigned_slot()
.map_or(true, |s| s.is_html_slot_element())
);
element.assigned_slot()
}
Combinator::PseudoElement => {
element.pseudo_element_originating_element()
}
},
Combinator::PseudoElement => element.pseudo_element_originating_element(),
}
}
@ -495,19 +476,25 @@ where
E: Element,
F: FnMut(&E, ElementSelectorFlags),
{
debug!("Matching complex selector {:?} for {:?}", selector_iter, element);
debug!(
"Matching complex selector {:?} for {:?}",
selector_iter, element
);
let matches_compound_selector = matches_compound_selector(
&mut selector_iter,
element,
context,
flags_setter,
rightmost
rightmost,
);
let combinator = selector_iter.next_sequence();
if combinator.map_or(false, |c| c.is_sibling()) {
flags_setter(element, ElementSelectorFlags::HAS_SLOW_SELECTOR_LATER_SIBLINGS);
flags_setter(
element,
ElementSelectorFlags::HAS_SLOW_SELECTOR_LATER_SIBLINGS,
);
}
if !matches_compound_selector {
@ -520,20 +507,16 @@ where
};
let candidate_not_found = match combinator {
Combinator::NextSibling |
Combinator::LaterSibling => {
Combinator::NextSibling | Combinator::LaterSibling => {
SelectorMatchingResult::NotMatchedAndRestartFromClosestDescendant
}
},
Combinator::Child |
Combinator::Descendant |
Combinator::SlotAssignment |
Combinator::PseudoElement => {
SelectorMatchingResult::NotMatchedGlobally
}
Combinator::PseudoElement => SelectorMatchingResult::NotMatchedGlobally,
};
let mut next_element =
next_element_for_combinator(element, combinator, &selector_iter);
let mut next_element = next_element_for_combinator(element, combinator, &selector_iter);
// Stop matching :visited as soon as we find a link, or a combinator for
// something that isn't an ancestor.
@ -549,16 +532,15 @@ where
Some(next_element) => next_element,
};
let result =
context.with_visited_handling_mode(visited_handling, |context| {
matches_complex_selector_internal(
selector_iter.clone(),
&element,
context,
flags_setter,
Rightmost::No,
)
});
let result = context.with_visited_handling_mode(visited_handling, |context| {
matches_complex_selector_internal(
selector_iter.clone(),
&element,
context,
flags_setter,
Rightmost::No,
)
});
match (result, combinator) {
// Return the status immediately.
@ -566,22 +548,24 @@ where
(SelectorMatchingResult::NotMatchedGlobally, _) |
(_, Combinator::NextSibling) => {
return result;
}
},
// Upgrade the failure status to
// NotMatchedAndRestartFromClosestDescendant.
(_, Combinator::PseudoElement) |
(_, Combinator::Child) => {
(_, Combinator::PseudoElement) | (_, Combinator::Child) => {
return SelectorMatchingResult::NotMatchedAndRestartFromClosestDescendant;
}
},
// 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) => {
(
SelectorMatchingResult::NotMatchedAndRestartFromClosestDescendant,
Combinator::LaterSibling,
) => {
return result;
}
},
// The Combinator::Descendant combinator and the status is
// NotMatchedAndRestartFromClosestLaterSibling or
@ -596,23 +580,19 @@ where
visited_handling = VisitedHandlingMode::AllLinksUnvisited;
}
next_element =
next_element_for_combinator(&element, combinator, &selector_iter);
next_element = next_element_for_combinator(&element, combinator, &selector_iter);
}
}
#[inline]
fn matches_local_name<E>(
element: &E,
local_name: &LocalName<E::Impl>
) -> bool
fn matches_local_name<E>(element: &E, local_name: &LocalName<E::Impl>) -> bool
where
E: Element,
{
let name = select_name(
element.is_html_element_in_html_document(),
&local_name.name,
&local_name.lower_name
&local_name.lower_name,
).borrow();
element.local_name() == name
}
@ -661,19 +641,13 @@ where
None => return true,
};
let mut local_context =
LocalMatchingContext {
shared: context,
matches_hover_and_active_quirk,
};
iter::once(selector).chain(selector_iter).all(|simple| {
matches_simple_selector(
simple,
element,
&mut local_context,
flags_setter,
)
})
let mut local_context = LocalMatchingContext {
shared: context,
matches_hover_and_active_quirk,
};
iter::once(selector)
.chain(selector_iter)
.all(|simple| matches_simple_selector(simple, element, &mut local_context, flags_setter))
}
/// Determines whether the given element matches the given single selector.
@ -693,49 +667,40 @@ where
Component::Combinator(_) => unreachable!(),
Component::Slotted(ref selector) => {
// <slots> are never flattened tree slottables.
!element.is_html_slot_element() &&
element.assigned_slot().is_some() &&
context.shared.nest(|context| {
matches_complex_selector(
selector.iter(),
element,
context,
flags_setter,
)
})
}
!element.is_html_slot_element() && element.assigned_slot().is_some() &&
context.shared.nest(|context| {
matches_complex_selector(selector.iter(), element, context, flags_setter)
})
},
Component::PseudoElement(ref pseudo) => {
element.match_pseudo_element(pseudo, context.shared)
}
Component::LocalName(ref local_name) => {
matches_local_name(element, local_name)
}
Component::ExplicitUniversalType |
Component::ExplicitAnyNamespace => {
true
}
Component::Namespace(_, ref url) |
Component::DefaultNamespace(ref url) => {
},
Component::LocalName(ref local_name) => matches_local_name(element, local_name),
Component::ExplicitUniversalType | Component::ExplicitAnyNamespace => true,
Component::Namespace(_, ref url) | Component::DefaultNamespace(ref url) => {
element.namespace() == url.borrow()
}
},
Component::ExplicitNoNamespace => {
let ns = ::parser::namespace_empty_string::<E::Impl>();
element.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 } => {
},
Component::AttributeInNoNamespaceExists {
ref local_name,
ref local_name_lower,
} => {
let is_html = element.is_html_element_in_html_document();
element.attr_matches(
&NamespaceConstraint::Specific(&::parser::namespace_empty_string::<E::Impl>()),
select_name(is_html, local_name, local_name_lower),
&AttrSelectorOperation::Exists
&AttrSelectorOperation::Exists,
)
}
},
Component::AttributeInNoNamespace {
ref local_name,
ref local_name_lower,
@ -745,7 +710,7 @@ where
never_matches,
} => {
if never_matches {
return false
return false;
}
let is_html = element.is_html_element_in_html_document();
element.attr_matches(
@ -755,12 +720,12 @@ where
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
return false;
}
let is_html = element.is_html_element_in_html_document();
element.attr_matches(
@ -772,105 +737,80 @@ where
operator,
case_sensitivity,
ref expected_value,
} => {
AttrSelectorOperation::WithValue {
operator: operator,
case_sensitivity: case_sensitivity.to_unconditional(is_html),
expected_value: expected_value,
}
}
}
} => AttrSelectorOperation::WithValue {
operator: operator,
case_sensitivity: case_sensitivity.to_unconditional(is_html),
expected_value: expected_value,
},
},
)
}
},
Component::NonTSPseudoClass(ref pc) => {
if context.matches_hover_and_active_quirk == MatchesHoverAndActiveQuirk::Yes &&
!context.shared.is_nested() &&
pc.is_active_or_hover() &&
!element.is_link()
!context.shared.is_nested() && pc.is_active_or_hover() &&
!element.is_link()
{
return false;
}
element.match_non_ts_pseudo_class(
pc,
&mut context.shared,
flags_setter
)
}
Component::FirstChild => {
matches_first_child(element, flags_setter)
}
Component::LastChild => {
matches_last_child(element, flags_setter)
}
element.match_non_ts_pseudo_class(pc, &mut context.shared, 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()
}
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::Host(ref selector) => {
context.shared.shadow_host().map_or(false, |host| host == element.opaque()) &&
selector.as_ref().map_or(true, |selector| {
context.shared.nest(|context| {
matches_complex_selector(
selector.iter(),
element,
context,
flags_setter,
)
context
.shared
.shadow_host()
.map_or(false, |host| host == element.opaque()) &&
selector.as_ref().map_or(true, |selector| {
context.shared.nest(|context| {
matches_complex_selector(selector.iter(), element, context, flags_setter)
})
})
})
}
Component::Scope => {
match context.shared.scope_element {
Some(ref scope_element) => element.opaque() == *scope_element,
None => element.is_root(),
}
}
},
Component::Scope => match context.shared.scope_element {
Some(ref scope_element) => element.opaque() == *scope_element,
None => element.is_root(),
},
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.shared.nest_for_negation(|context| {
let mut local_context = LocalMatchingContext {
matches_hover_and_active_quirk: MatchesHoverAndActiveQuirk::No,
shared: context,
};
!negated.iter().all(|ss| {
matches_simple_selector(
ss,
element,
&mut local_context,
flags_setter,
)
})
})
}
matches_generic_nth_child(element, context, 0, 1, true, true, flags_setter)
},
Component::Negation(ref negated) => context.shared.nest_for_negation(|context| {
let mut local_context = LocalMatchingContext {
matches_hover_and_active_quirk: MatchesHoverAndActiveQuirk::No,
shared: context,
};
!negated
.iter()
.all(|ss| matches_simple_selector(ss, element, &mut local_context, flags_setter))
}),
}
}
@ -901,26 +841,40 @@ where
return false;
}
flags_setter(element, if is_from_end {
ElementSelectorFlags::HAS_SLOW_SELECTOR
} else {
ElementSelectorFlags::HAS_SLOW_SELECTOR_LATER_SIBLINGS
});
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)
});
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));
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");
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) {
@ -934,8 +888,7 @@ where
#[inline]
fn same_type<E: Element>(a: &E, b: &E) -> bool {
a.local_name() == b.local_name() &&
a.namespace() == b.namespace()
a.local_name() == b.local_name() && a.namespace() == b.namespace()
}
#[inline]
@ -972,7 +925,13 @@ where
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() };
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) {
@ -981,7 +940,7 @@ where
// function.
if !is_from_end {
if let Some(i) = cache.as_mut().and_then(|c| c.lookup(curr.opaque())) {
return i + index
return i + index;
}
}
index += 1;

View file

@ -20,11 +20,7 @@ pub struct NthIndexCache {
impl NthIndexCache {
/// Gets the appropriate cache for the given parameters.
pub fn get(
&mut self,
is_of_type: bool,
is_from_end: bool
) -> &mut NthIndexCacheInner {
pub fn get(&mut self, is_of_type: bool, is_from_end: bool) -> &mut NthIndexCacheInner {
match (is_of_type, is_from_end) {
(false, false) => &mut self.nth,
(false, true) => &mut self.nth_last,

File diff suppressed because it is too large Load diff

View file

@ -5,7 +5,7 @@
//! Traits that nodes must implement. Breaks the otherwise-cyclic dependency
//! between layout and style.
use attr::{AttrSelectorOperation, NamespaceConstraint, CaseSensitivity};
use attr::{AttrSelectorOperation, CaseSensitivity, NamespaceConstraint};
use matching::{ElementSelectorFlags, MatchingContext};
use parser::SelectorImpl;
use servo_arc::NonZeroPtrMut;

View file

@ -38,9 +38,7 @@ pub trait SelectorVisitor {
///
/// Gets the combinator to the right of the selector, or `None` if the
/// selector is the rightmost one.
fn visit_complex_selector(&mut self,
_combinator_to_right: Option<Combinator>)
-> bool {
fn visit_complex_selector(&mut self, _combinator_to_right: Option<Combinator>) -> bool {
true
}
}