style: Rustfmt servo/. r=zrhoffman

$ find servo -name '*.rs' | xargs rustup run nightly rustfmt

Depends on D179380

Differential Revision: https://phabricator.services.mozilla.com/D179381
This commit is contained in:
Emilio Cobos Álvarez 2023-05-30 08:04:52 +00:00 committed by Martin Robinson
parent 68cbe6833d
commit ad72081ac8
70 changed files with 665 additions and 448 deletions

View file

@ -403,7 +403,10 @@ impl<T> MallocShallowSizeOf for thin_vec::ThinVec<T> {
return 0;
}
assert_eq!(std::mem::size_of::<Self>(), std::mem::size_of::<*const ()>());
assert_eq!(
std::mem::size_of::<Self>(),
std::mem::size_of::<*const ()>()
);
unsafe { ops.malloc_size_of(*(self as *const Self as *const *const ())) }
}
}

View file

@ -385,8 +385,7 @@ where
/// Finds the maximum specificity of elements in the list and returns it.
pub(crate) fn selector_list_specificity_and_flags<'a, Impl: SelectorImpl>(
itr: impl Iterator<Item = &'a Selector<Impl>>,
) -> SpecificityAndFlags
{
) -> SpecificityAndFlags {
let mut specificity = 0;
let mut flags = SelectorFlags::empty();
for selector in itr {

View file

@ -658,10 +658,13 @@ impl<Impl: SelectorImpl> Selector<Impl> {
}
fn ampersand() -> Self {
Self(ThinArc::from_header_and_iter(SpecificityAndFlags {
specificity: 0,
flags: SelectorFlags::HAS_PARENT,
}, std::iter::once(Component::ParentSelector)))
Self(ThinArc::from_header_and_iter(
SpecificityAndFlags {
specificity: 0,
flags: SelectorFlags::HAS_PARENT,
},
std::iter::once(Component::ParentSelector),
))
}
#[inline]
@ -977,8 +980,12 @@ impl<Impl: SelectorImpl> Selector<Impl> {
specificity += parent_specificity;
let iter = iter
.cloned()
.chain(std::iter::once(Component::Combinator(Combinator::Descendant)))
.chain(std::iter::once(Component::Is(parent.to_vec().into_boxed_slice())));
.chain(std::iter::once(Component::Combinator(
Combinator::Descendant,
)))
.chain(std::iter::once(Component::Is(
parent.to_vec().into_boxed_slice(),
)));
let header = HeaderWithLength::new(specificity_and_flags, len);
UniqueArc::from_header_and_iter_with_size(header, iter, len)
} else {
@ -4081,25 +4088,19 @@ pub mod tests {
let parent = parse(".bar, div .baz").unwrap();
let child = parse("#foo &.bar").unwrap();
assert_eq!(
SelectorList::from_vec(vec![child.0[0]
.replace_parent_selector(&parent.0)
]),
SelectorList::from_vec(vec![child.0[0].replace_parent_selector(&parent.0)]),
parse("#foo :is(.bar, div .baz).bar").unwrap()
);
let has_child = parse("#foo:has(&.bar)").unwrap();
assert_eq!(
SelectorList::from_vec(vec![has_child.0[0]
.replace_parent_selector(&parent.0)
]),
SelectorList::from_vec(vec![has_child.0[0].replace_parent_selector(&parent.0)]),
parse("#foo:has(:is(.bar, div .baz).bar)").unwrap()
);
let child = parse("#foo").unwrap();
assert_eq!(
SelectorList::from_vec(vec![child.0[0]
.replace_parent_selector(&parent.0)
]),
SelectorList::from_vec(vec![child.0[0].replace_parent_selector(&parent.0)]),
parse(":is(.bar, div .baz) #foo").unwrap()
);
}

View file

@ -1045,11 +1045,17 @@ impl<H, T> UniqueArc<HeaderSliceWithLength<H, [T]>> {
}
#[inline]
pub fn from_header_and_iter_with_size<I>(header: HeaderWithLength<H>, items: I, num_items: usize) -> Self
pub fn from_header_and_iter_with_size<I>(
header: HeaderWithLength<H>,
items: I,
num_items: usize,
) -> Self
where
I: Iterator<Item = T>,
{
Self(Arc::from_header_and_iter_with_size(header, items, num_items))
Self(Arc::from_header_and_iter_with_size(
header, items, num_items,
))
}
/// Returns a mutable reference to the header.

View file

@ -13,7 +13,9 @@ use crate::str::CssStringWriter;
use crate::values::specified::Integer;
use crate::values::CustomIdent;
use crate::Atom;
use cssparser::{AtRuleParser, RuleBodyParser, RuleBodyItemParser, DeclarationParser, QualifiedRuleParser};
use cssparser::{
AtRuleParser, DeclarationParser, QualifiedRuleParser, RuleBodyItemParser, RuleBodyParser,
};
use cssparser::{CowRcStr, Parser, SourceLocation, Token};
use selectors::parser::SelectorParseErrorKind;
use std::fmt::{self, Write};
@ -159,9 +161,15 @@ impl<'a, 'b, 'i> QualifiedRuleParser<'i> for CounterStyleRuleParser<'a, 'b> {
type Error = StyleParseErrorKind<'i>;
}
impl<'a, 'b, 'i> RuleBodyItemParser<'i, (), StyleParseErrorKind<'i>> for CounterStyleRuleParser<'a, 'b> {
fn parse_qualified(&self) -> bool { false }
fn parse_declarations(&self) -> bool { true }
impl<'a, 'b, 'i> RuleBodyItemParser<'i, (), StyleParseErrorKind<'i>>
for CounterStyleRuleParser<'a, 'b>
{
fn parse_qualified(&self) -> bool {
false
}
fn parse_declarations(&self) -> bool {
true
}
}
macro_rules! checker {

View file

@ -149,10 +149,7 @@ static CHROME_ENVIRONMENT_VARIABLES: [EnvironmentVariable; 6] = [
atom!("-moz-content-preferred-color-scheme"),
get_content_preferred_color_scheme
),
make_variable!(
atom!("scrollbar-inline-size"),
get_scrollbar_inline_size
),
make_variable!(atom!("scrollbar-inline-size"), get_scrollbar_inline_size),
];
impl CssEnvironment {

View file

@ -398,7 +398,9 @@ impl ElementData {
let needs_to_recascade_self = hint.intersects(RestyleHint::RECASCADE_SELF) ||
(hint.intersects(RestyleHint::RECASCADE_SELF_IF_INHERIT_RESET_STYLE) &&
style.flags.contains(ComputedValueFlags::INHERITS_RESET_STYLE));
style
.flags
.contains(ComputedValueFlags::INHERITS_RESET_STYLE));
if needs_to_recascade_self {
return Some(RestyleKind::CascadeOnly);
}
@ -442,7 +444,9 @@ impl ElementData {
let needs_to_recascade_self = hint.intersects(RestyleHint::RECASCADE_SELF) ||
(hint.intersects(RestyleHint::RECASCADE_SELF_IF_INHERIT_RESET_STYLE) &&
style.flags.contains(ComputedValueFlags::INHERITS_RESET_STYLE));
style
.flags
.contains(ComputedValueFlags::INHERITS_RESET_STYLE));
if needs_to_recascade_self {
return Some(RestyleKind::CascadeOnly);
}

View file

@ -17,8 +17,8 @@ use crate::properties::{AnimationDeclarations, ComputedValues, PropertyDeclarati
use crate::selector_parser::{AttrValue, Lang, PseudoElement, SelectorImpl};
use crate::shared_lock::{Locked, SharedRwLock};
use crate::stylist::CascadeData;
use crate::values::AtomIdent;
use crate::values::computed::Display;
use crate::values::AtomIdent;
use crate::{LocalName, Namespace, WeakAtom};
use atomic_refcell::{AtomicRef, AtomicRefMut};
use selectors::matching::{QuirksMode, VisitedHandlingMode};
@ -199,7 +199,10 @@ pub trait TNode: Sized + Copy + Clone + Debug + NodeInfo + PartialEq {
return Some(s);
}
debug_assert!(current.parent_node().is_some(), "Not a descendant of the scope?");
debug_assert!(
current.parent_node().is_some(),
"Not a descendant of the scope?"
);
current = current.parent_node()?;
}
}
@ -893,7 +896,10 @@ pub trait TElement:
/// Returns the size of the element to be used in container size queries.
/// This will usually be the size of the content area of the primary box,
/// but can be None if there is no box or if some axis lacks size containment.
fn query_container_size(&self, display: &Display) -> euclid::default::Size2D<Option<app_units::Au>>;
fn query_container_size(
&self,
display: &Display,
) -> euclid::default::Size2D<Option<app_units::Au>>;
/// Returns true if this element anchors a relative selector, now or after
/// a DOM mutation.

View file

@ -7,10 +7,10 @@
use crate::context::QuirksMode;
use crate::dom::{TDocument, TElement, TNode, TShadowRoot};
use crate::selector_parser::SelectorImpl;
use crate::invalidation::element::invalidation_map::Dependency;
use crate::invalidation::element::invalidator::{DescendantInvalidationLists, Invalidation};
use crate::invalidation::element::invalidator::{InvalidationProcessor, InvalidationVector};
use crate::selector_parser::SelectorImpl;
use crate::values::AtomIdent;
use selectors::attr::CaseSensitivity;
use selectors::matching::{self, MatchingContext, MatchingMode, NeedsSelectorFlags};
@ -381,7 +381,12 @@ fn get_id(component: &Component<SelectorImpl>) -> Option<&AtomIdent> {
use selectors::attr::AttrSelectorOperator;
Some(match component {
Component::ID(ref id) => id,
Component::AttributeInNoNamespace { ref operator, ref local_name, ref value, .. } => {
Component::AttributeInNoNamespace {
ref operator,
ref local_name,
ref value,
..
} => {
if *local_name != local_name!("id") {
return None;
}
@ -510,9 +515,19 @@ where
if combinator.is_none() {
// In the rightmost compound, just find descendants of root that match
// the selector list with that id.
collect_elements_with_id::<E, Q, _>(root, id, results, quirks_mode, |e| {
matching::matches_selector_list(selector_list, &e, matching_context)
});
collect_elements_with_id::<E, Q, _>(
root,
id,
results,
quirks_mode,
|e| {
matching::matches_selector_list(
selector_list,
&e,
matching_context,
)
},
);
return Ok(());
}

View file

@ -137,10 +137,7 @@ where
continue;
}
depth += 1;
if pool.is_some() &&
discovered.len() > parallelism_threshold &&
parallelism_threshold > 0
{
if pool.is_some() && discovered.len() > parallelism_threshold && parallelism_threshold > 0 {
let pool = pool.unwrap();
let tls = ScopedTLS::<ThreadLocalStyleContext<E>>::new(pool);
let root_opaque = root.as_node().opaque();

View file

@ -27,8 +27,8 @@ use crate::values::specified::NonNegativePercentage;
#[cfg(feature = "gecko")]
use cssparser::UnicodeRange;
use cssparser::{
AtRuleParser, CowRcStr, RuleBodyParser, RuleBodyItemParser, DeclarationParser, Parser,
QualifiedRuleParser, SourceLocation,
AtRuleParser, CowRcStr, DeclarationParser, Parser, QualifiedRuleParser, RuleBodyItemParser,
RuleBodyParser, SourceLocation,
};
use selectors::parser::SelectorParseErrorKind;
use std::fmt::{self, Write};
@ -566,9 +566,15 @@ impl<'a, 'b, 'i> QualifiedRuleParser<'i> for FontFaceRuleParser<'a, 'b> {
type Error = StyleParseErrorKind<'i>;
}
impl<'a, 'b, 'i> RuleBodyItemParser<'i, (), StyleParseErrorKind<'i>> for FontFaceRuleParser<'a, 'b> {
fn parse_qualified(&self) -> bool { false }
fn parse_declarations(&self) -> bool { true }
impl<'a, 'b, 'i> RuleBodyItemParser<'i, (), StyleParseErrorKind<'i>>
for FontFaceRuleParser<'a, 'b>
{
fn parse_qualified(&self) -> bool {
false
}
fn parse_declarations(&self) -> bool {
true
}
}
fn font_tech_enabled() -> bool {

View file

@ -94,11 +94,7 @@ impl_locked_arc_ffi!(
Servo_MediaList_AddRef,
Servo_MediaList_Release
);
impl_simple_arc_ffi!(
MediaRule,
Servo_MediaRule_AddRef,
Servo_MediaRule_Release
);
impl_simple_arc_ffi!(MediaRule, Servo_MediaRule_AddRef, Servo_MediaRule_Release);
impl_simple_arc_ffi!(
NamespaceRule,
Servo_NamespaceRule_AddRef,

View file

@ -6,7 +6,9 @@
use crate::dom::TElement;
use crate::gecko_bindings::bindings;
use crate::gecko_bindings::structs::{self, ServoStyleSetSizes, StyleSheet as DomStyleSheet, StyleSheetInfo};
use crate::gecko_bindings::structs::{
self, ServoStyleSetSizes, StyleSheet as DomStyleSheet, StyleSheetInfo,
};
use crate::invalidation::media_queries::{MediaListKey, ToMediaListKey};
use crate::media_queries::{Device, MediaList};
use crate::properties::ComputedValues;

View file

@ -239,8 +239,9 @@ fn eval_prefers_reduced_transparency(
context: &Context,
query_value: Option<PrefersReducedTransparency>,
) -> bool {
let prefers_reduced =
unsafe { bindings::Gecko_MediaFeatures_PrefersReducedTransparency(context.device().document()) };
let prefers_reduced = unsafe {
bindings::Gecko_MediaFeatures_PrefersReducedTransparency(context.device().document())
};
let query_value = match query_value {
Some(v) => v,
None => return prefers_reduced,
@ -309,10 +310,7 @@ enum InvertedColors {
}
/// https://drafts.csswg.org/mediaqueries-5/#inverted
fn eval_inverted_colors(
context: &Context,
query_value: Option<InvertedColors>,
) -> bool {
fn eval_inverted_colors(context: &Context, query_value: Option<InvertedColors>) -> bool {
let inverted_colors =
unsafe { bindings::Gecko_MediaFeatures_InvertedColors(context.device().document()) };
let query_value = match query_value {
@ -604,13 +602,12 @@ pub enum Scripting {
/// See: https://github.com/w3c/csswg-drafts/issues/8621
InitialOnly,
/// Scripting is supported and enabled
Enabled
Enabled,
}
/// https://drafts.csswg.org/mediaqueries-5/#scripting
fn eval_scripting(context: &Context, query_value: Option<Scripting>) -> bool {
let scripting =
unsafe { bindings::Gecko_MediaFeatures_Scripting(context.device().document()) };
let scripting = unsafe { bindings::Gecko_MediaFeatures_Scripting(context.device().document()) };
match query_value {
Some(v) => v == scripting,
None => scripting != Scripting::None,
@ -824,7 +821,10 @@ pub static MEDIA_FEATURES: [QueryFeatureDescription; 67] = [
feature!(
atom!("prefers-reduced-transparency"),
AllowsRanges::No,
keyword_evaluator!(eval_prefers_reduced_transparency, PrefersReducedTransparency),
keyword_evaluator!(
eval_prefers_reduced_transparency,
PrefersReducedTransparency
),
FeatureFlags::empty(),
),
feature!(

View file

@ -73,10 +73,7 @@ impl fmt::Debug for Device {
let mut doc_uri = nsCString::new();
unsafe {
bindings::Gecko_nsIURI_Debug(
(*self.document()).mDocumentURI.raw(),
&mut doc_uri,
)
bindings::Gecko_nsIURI_Debug((*self.document()).mDocumentURI.raw(), &mut doc_uri)
};
f.debug_struct("Device")
@ -132,13 +129,12 @@ impl Device {
pres_context.map_or(std::ptr::null(), |pc| pc),
vertical,
&**font,
element.map_or(std::ptr::null(), |e| e.0)
element.map_or(std::ptr::null(), |e| e.0),
)
});
NonNegativeLength::new(au.to_f32_px())
}
/// Tells the device that a new viewport rule has been found, and stores the
/// relevant viewport constraints.
pub fn account_for_viewport_rule(&mut self, _constraints: &ViewportConstraints) {
@ -208,9 +204,7 @@ impl Device {
// XXX: we could have a more reasonable default perhaps.
None => return Length::new(0.0),
};
Length::new(unsafe {
bindings::Gecko_GetScrollbarInlineSize(pc)
})
Length::new(unsafe { bindings::Gecko_GetScrollbarInlineSize(pc) })
}
/// Queries font metrics

View file

@ -14,8 +14,8 @@ use crate::properties::{ComputedValues, PropertyFlags};
use crate::selector_parser::{PseudoElementCascadeType, SelectorImpl};
use crate::str::{starts_with_ignore_ascii_case, string_as_ascii_lowercase};
use crate::string_cache::Atom;
use crate::values::AtomIdent;
use crate::values::serialize_atom_identifier;
use crate::values::AtomIdent;
use cssparser::ToCss;
use static_prefs::pref;
use std::fmt;
@ -159,7 +159,7 @@ impl PseudoElement {
pub fn highlight_name(&self) -> Option<&AtomIdent> {
match &*self {
PseudoElement::Highlight(name) => Some(&name),
_ => None
_ => None,
}
}
@ -178,7 +178,7 @@ impl PseudoElement {
if self.is_highlight() && !pref!("dom.customHighlightAPI.enabled") {
return false;
}
return self.flags() & structs::CSS_PSEUDO_ELEMENT_ENABLED_IN_UA_SHEETS_AND_CHROME == 0
return self.flags() & structs::CSS_PSEUDO_ELEMENT_ENABLED_IN_UA_SHEETS_AND_CHROME == 0;
}
/// Whether this pseudo is enabled explicitly in UA sheets.

View file

@ -59,8 +59,8 @@ use crate::selector_parser::{AttrValue, Lang};
use crate::shared_lock::{Locked, SharedRwLock};
use crate::string_cache::{Atom, Namespace, WeakAtom, WeakNamespace};
use crate::stylist::CascadeData;
use crate::values::{AtomIdent, AtomString};
use crate::values::computed::Display;
use crate::values::{AtomIdent, AtomString};
use crate::CaseSensitivityExt;
use crate::LocalName;
use app_units::Au;
@ -321,7 +321,7 @@ impl<'ln> GeckoNode<'ln> {
#[inline]
fn is_in_shadow_tree(&self) -> bool {
use crate::gecko_bindings::structs::NODE_IS_IN_SHADOW_TREE;
self.flags() & NODE_IS_IN_SHADOW_TREE != 0
self.flags() & NODE_IS_IN_SHADOW_TREE != 0
}
/// Returns true if we know for sure that `flattened_tree_parent` and `parent_node` return the
@ -824,9 +824,8 @@ impl<'le> GeckoElement<'le> {
let mut map = FxHashMap::with_capacity_and_hasher(collection_length, Default::default());
for i in 0..collection_length {
let end_value = unsafe {
Arc::from_raw_addrefed(Gecko_ElementTransitions_EndValueAt(self.0, i))
};
let end_value =
unsafe { Arc::from_raw_addrefed(Gecko_ElementTransitions_EndValueAt(self.0, i)) };
let property = end_value.id();
debug_assert!(!property.is_logical());
map.insert(property, end_value);
@ -918,13 +917,7 @@ fn get_animation_rule(
effect_count.min(ANIMATABLE_PROPERTY_COUNT),
Default::default(),
);
if unsafe {
Gecko_GetAnimationRule(
element.0,
cascade_level,
&mut animation_values,
)
} {
if unsafe { Gecko_GetAnimationRule(element.0, cascade_level, &mut animation_values) } {
let shared_lock = &GLOBAL_STYLE_DATA.shared_lock;
Some(Arc::new(shared_lock.wrap(
PropertyDeclarationBlock::from_animation_value_map(&animation_values),
@ -1326,9 +1319,12 @@ impl<'le> TElement for GeckoElement<'le> {
/// pseudo-elements).
#[inline]
fn matches_user_and_content_rules(&self) -> bool {
use crate::gecko_bindings::structs::{NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE, NODE_HAS_BEEN_IN_UA_WIDGET};
use crate::gecko_bindings::structs::{
NODE_HAS_BEEN_IN_UA_WIDGET, NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE,
};
let flags = self.flags();
(flags & NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE) == 0 || (flags & NODE_HAS_BEEN_IN_UA_WIDGET) != 0
(flags & NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE) == 0 ||
(flags & NODE_HAS_BEEN_IN_UA_WIDGET) != 0
}
#[inline]
@ -1508,7 +1504,9 @@ impl<'le> TElement for GeckoElement<'le> {
transitions_to_keep.insert(physical_longhand);
if self.needs_transitions_update_per_property(
physical_longhand,
after_change_ui_style.transition_combined_duration_at(transition_property.index).seconds(),
after_change_ui_style
.transition_combined_duration_at(transition_property.index)
.seconds(),
before_change_style,
after_change_style,
&existing_transitions,
@ -2096,7 +2094,12 @@ impl<'le> ::selectors::Element for GeckoElement<'le> {
);
return false;
}
if context.extra_data.invalidation_data.document_state.intersects(state_bit) {
if context
.extra_data
.invalidation_data
.document_state
.intersects(state_bit)
{
return !context.in_negation();
}
self.document_state().contains(state_bit)

View file

@ -402,7 +402,9 @@ where
);
if invalidated_sibling {
sibling_invalidator.processor.invalidated_sibling(sibling, self.element);
sibling_invalidator
.processor
.invalidated_sibling(sibling, self.element);
}
any_invalidated |= invalidated_sibling;

View file

@ -143,7 +143,11 @@ impl RestyleHint {
/// be replaced.
#[inline]
pub fn has_animation_hint_or_recascade(&self) -> bool {
self.intersects(Self::for_animations() | Self::RECASCADE_SELF | Self::RECASCADE_SELF_IF_INHERIT_RESET_STYLE)
self.intersects(
Self::for_animations() |
Self::RECASCADE_SELF |
Self::RECASCADE_SELF_IF_INHERIT_RESET_STYLE,
)
}
/// Returns whether the hint specifies some restyle work other than an

View file

@ -136,7 +136,11 @@ where
return;
}
}
debug_assert!(false, "Should've found {:?} as an ancestor of {:?}", ancestor, child);
debug_assert!(
false,
"Should've found {:?} as an ancestor of {:?}",
ancestor, child
);
}
/// Propagates the bits after invalidating a descendant child, if needed.
@ -169,13 +173,20 @@ pub fn invalidated_sibling<E>(element: E, of: E)
where
E: TElement,
{
debug_assert_eq!(element.as_node().parent_node(), of.as_node().parent_node(), "Should be siblings");
debug_assert_eq!(
element.as_node().parent_node(),
of.as_node().parent_node(),
"Should be siblings"
);
if !invalidated_self(element) {
return;
}
if element.traversal_parent() != of.traversal_parent() {
let parent = element.as_node().parent_element_or_host();
debug_assert!(parent.is_some(), "How can we have siblings without parent nodes?");
debug_assert!(
parent.is_some(),
"How can we have siblings without parent nodes?"
);
if let Some(e) = parent {
propagate_dirty_bit_up_to(e, element)
}

View file

@ -36,7 +36,10 @@ where
let usage = data.styles.viewport_unit_usage();
let uses_viewport_units = usage != ViewportUnitUsage::None;
if uses_viewport_units {
debug!("invalidate_recursively: {:?} uses viewport units {:?}", element, usage);
debug!(
"invalidate_recursively: {:?} uses viewport units {:?}",
element, usage
);
}
match usage {
@ -46,7 +49,7 @@ where
},
ViewportUnitUsage::FromDeclaration => {
data.hint.insert(RestyleHint::RECASCADE_SELF);
}
},
}
let mut any_children_invalid = false;

View file

@ -10,8 +10,8 @@ use super::{Device, MediaQuery, Qualifier};
use crate::context::QuirksMode;
use crate::error_reporting::ContextualParseError;
use crate::parser::ParserContext;
use crate::values::computed;
use crate::queries::condition::KleeneValue;
use crate::values::computed;
use cssparser::{Delimiter, Parser};
use cssparser::{ParserInput, Token};
@ -83,7 +83,9 @@ impl MediaList {
computed::Context::for_media_query_evaluation(device, quirks_mode, |context| {
self.media_queries.iter().any(|mq| {
let mut query_match = if mq.media_type.matches(device.media_type()) {
mq.condition.as_ref().map_or(KleeneValue::True, |c| c.matches(context))
mq.condition
.as_ref()
.map_or(KleeneValue::True, |c| c.matches(context))
} else {
KleeneValue::False
};

View file

@ -120,7 +120,9 @@ impl MediaQuery {
/// Returns whether this media query depends on the viewport.
pub fn is_viewport_dependent(&self) -> bool {
self.condition.as_ref().map_or(false, |c| {
return c.cumulative_flags().contains(FeatureFlags::VIEWPORT_DEPENDENT)
return c
.cumulative_flags()
.contains(FeatureFlags::VIEWPORT_DEPENDENT);
})
}

View file

@ -85,7 +85,11 @@ impl<'a> ParserContext<'a> {
}
/// Temporarily sets the rule_type and executes the callback function, returning its result.
pub fn nest_for_rule<R>(&mut self, rule_type: CssRuleType, cb: impl FnOnce(&mut Self) -> R) -> R {
pub fn nest_for_rule<R>(
&mut self,
rule_type: CssRuleType,
cb: impl FnOnce(&mut Self) -> R,
) -> R {
let old_rule_types = self.rule_types;
self.rule_types.insert(rule_type);
let r = cb(self);

View file

@ -370,7 +370,7 @@ where
} else {
LonghandIdSet::late_group()
}
}
},
};
cascade.apply_properties(
@ -430,7 +430,10 @@ fn tweak_when_ignoring_colors(
// Always honor colors if forced-color-adjust is set to none.
#[cfg(feature = "gecko")] {
let forced = context.builder.get_inherited_text().clone_forced_color_adjust();
let forced = context
.builder
.get_inherited_text()
.clone_forced_color_adjust();
if forced == computed::ForcedColorAdjust::None {
return;
}
@ -439,7 +442,10 @@ fn tweak_when_ignoring_colors(
// Don't override background-color on ::-moz-color-swatch. It is set as an
// author style (via the style attribute), but it's pretty important for it
// to show up for obvious reasons :)
if context.builder.pseudo.map_or(false, |p| p.is_color_swatch()) &&
if context
.builder
.pseudo
.map_or(false, |p| p.is_color_swatch()) &&
longhand_id == LonghandId::BackgroundColor
{
return;
@ -482,13 +488,22 @@ fn tweak_when_ignoring_colors(
},
PropertyDeclaration::Color(ref color) => {
// We honor color: transparent and system colors.
if color.0.honored_in_forced_colors_mode(/* allow_transparent = */ true) {
if color
.0
.honored_in_forced_colors_mode(/* allow_transparent = */ true)
{
return;
}
// If the inherited color would be transparent, but we would
// override this with a non-transparent color, then override it with
// the default color. Otherwise just let it inherit through.
if context.builder.get_parent_inherited_text().clone_color().alpha == 0.0 {
if context
.builder
.get_parent_inherited_text()
.clone_color()
.alpha ==
0.0
{
let color = context.builder.device.default_color();
declarations_to_apply_unless_overriden.push(PropertyDeclaration::Color(
specified::ColorPropertyValue(color.into()),
@ -500,7 +515,11 @@ fn tweak_when_ignoring_colors(
PropertyDeclaration::BackgroundImage(ref bkg) => {
use crate::values::generics::image::Image;
if static_prefs::pref!("browser.display.permit_backplate") {
if bkg.0.iter().all(|image| matches!(*image, Image::Url(..) | Image::None)) {
if bkg
.0
.iter()
.all(|image| matches!(*image, Image::Url(..) | Image::None))
{
return;
}
}
@ -632,7 +651,8 @@ impl<'a, 'b: 'a> Cascade<'a, 'b> {
return false;
}
let can_have_logical_properties = can_have_logical_properties == CanHaveLogicalProperties::Yes;
let can_have_logical_properties =
can_have_logical_properties == CanHaveLogicalProperties::Yes;
let ignore_colors = !self.context.builder.device.use_document_colors();
let mut declarations_to_apply_unless_overriden = DeclarationsToApplyUnlessOverriden::new();
@ -662,7 +682,9 @@ impl<'a, 'b: 'a> Cascade<'a, 'b> {
}
if self.reverted_set.contains(physical_longhand_id) {
if let Some(&(reverted_priority, is_origin_revert)) = self.reverted.get(&physical_longhand_id) {
if let Some(&(reverted_priority, is_origin_revert)) =
self.reverted.get(&physical_longhand_id)
{
if !reverted_priority.allows_when_reverted(&priority, is_origin_revert) {
continue;
}
@ -691,14 +713,14 @@ impl<'a, 'b: 'a> Cascade<'a, 'b> {
let is_unset = match declaration.get_css_wide_keyword() {
Some(keyword) => match keyword {
CSSWideKeyword::RevertLayer |
CSSWideKeyword::Revert => {
CSSWideKeyword::RevertLayer | CSSWideKeyword::Revert => {
let origin_revert = keyword == CSSWideKeyword::Revert;
// We intentionally don't want to insert it into
// `self.seen`, `reverted` takes care of rejecting other
// declarations as needed.
self.reverted_set.insert(physical_longhand_id);
self.reverted.insert(physical_longhand_id, (priority, origin_revert));
self.reverted
.insert(physical_longhand_id, (priority, origin_revert));
continue;
},
CSSWideKeyword::Unset => true,
@ -834,12 +856,18 @@ impl<'a, 'b: 'a> Cascade<'a, 'b> {
}
#[cfg(feature = "gecko")]
if self.author_specified.contains(LonghandId::FontSynthesisWeight) {
if self
.author_specified
.contains(LonghandId::FontSynthesisWeight)
{
builder.add_flags(ComputedValueFlags::HAS_AUTHOR_SPECIFIED_FONT_SYNTHESIS_WEIGHT);
}
#[cfg(feature = "gecko")]
if self.author_specified.contains(LonghandId::FontSynthesisStyle) {
if self
.author_specified
.contains(LonghandId::FontSynthesisStyle)
{
builder.add_flags(ComputedValueFlags::HAS_AUTHOR_SPECIFIED_FONT_SYNTHESIS_STYLE);
}
@ -918,7 +946,10 @@ impl<'a, 'b: 'a> Cascade<'a, 'b> {
};
let initial_generic = font.mFont.family.families.single_generic();
debug_assert!(initial_generic.is_some(), "Initial font should be just one generic font");
debug_assert!(
initial_generic.is_some(),
"Initial font should be just one generic font"
);
if initial_generic == Some(default_font_type) {
return;
}
@ -927,7 +958,8 @@ impl<'a, 'b: 'a> Cascade<'a, 'b> {
};
// NOTE: Leaves is_initial untouched.
builder.mutate_font().mFont.family.families = FontFamily::generic(default_font_type).families.clone();
builder.mutate_font().mFont.family.families =
FontFamily::generic(default_font_type).families.clone();
}
/// Prioritize user fonts if needed by pref.
@ -1107,7 +1139,8 @@ impl<'a, 'b: 'a> Cascade<'a, 'b> {
let mut b = computed_math_depth;
let c = SCALE_FACTOR_WHEN_INCREMENTING_MATH_DEPTH_BY_ONE;
let scale_between_0_and_1 = parent_script_percent_scale_down.unwrap_or_else(|| c);
let scale_between_0_and_2 = parent_script_script_percent_scale_down.unwrap_or_else(|| c * c);
let scale_between_0_and_2 =
parent_script_script_percent_scale_down.unwrap_or_else(|| c * c);
let mut s = 1.0;
let mut invert_scale_factor = false;
if a == b {
@ -1156,7 +1189,8 @@ impl<'a, 'b: 'a> Cascade<'a, 'b> {
// the default scale, use MathML3's implementation for backward
// compatibility. Otherwise, follow MathML Core's algorithm.
let scale = if parent_font.mScriptSizeMultiplier !=
SCALE_FACTOR_WHEN_INCREMENTING_MATH_DEPTH_BY_ONE {
SCALE_FACTOR_WHEN_INCREMENTING_MATH_DEPTH_BY_ONE
{
(parent_font.mScriptSizeMultiplier as f32).powi(delta as i32)
} else {
// Script scale factors are independent of orientation.

View file

@ -594,9 +594,8 @@ impl PropertyDeclarationBlock {
.all_shorthand
.declarations()
.any(|decl| {
!self.contains(decl.id())
|| self
.declarations
!self.contains(decl.id()) ||
self.declarations
.iter()
.enumerate()
.find(|&(_, ref d)| d.id() == decl.id())
@ -638,9 +637,9 @@ impl PropertyDeclarationBlock {
}
return DeclarationUpdate::UpdateInPlace { pos };
}
if !needs_append
&& id.logical_group() == Some(logical_group)
&& id.is_logical() != longhand_id.is_logical()
if !needs_append &&
id.logical_group() == Some(logical_group) &&
id.is_logical() != longhand_id.is_logical()
{
needs_append = true;
}
@ -1428,7 +1427,8 @@ impl<'i> DeclarationParserState<'i> {
};
// In case there is still unparsed text in the declaration, we should roll back.
input.expect_exhausted()?;
self.output_block.extend(self.declarations.drain(), self.importance);
self.output_block
.extend(self.declarations.drain(), self.importance);
// We've successfully parsed a declaration, so forget about
// `last_parsed_property_id`. It'd be wrong to associate any
// following error with this property.

View file

@ -4,8 +4,8 @@
//! Supported CSS properties and the cascade.
pub mod declaration_block;
pub mod cascade;
pub mod declaration_block;
/// The CSS properties supported by the style system.
/// Generated from the properties.mako.rs template by build.rs

View file

@ -310,9 +310,10 @@ impl QueryCondition {
// We're about to swallow the error in a `<general-enclosed>`
// condition, so report it while we can.
let loc = e.location;
let error = ContextualParseError::InvalidMediaRule(input.slice_from(start), e);
let error =
ContextualParseError::InvalidMediaRule(input.slice_from(start), e);
context.log_css_error(loc, error);
}
},
}
},
Token::Function(..) => {

View file

@ -4,11 +4,11 @@
//! Query features.
use super::condition::KleeneValue;
use crate::parser::ParserContext;
use crate::values::computed::{self, CSSPixelLength, Ratio, Resolution};
use crate::Atom;
use cssparser::Parser;
use super::condition::KleeneValue;
use std::fmt;
use style_traits::ParseError;

View file

@ -651,7 +651,7 @@ impl QueryFeatureExpression {
.kind
.non_ranged_value()
.map(|v| *expect!(Enumerated, v));
return evaluator(context, computed)
return evaluator(context, computed);
},
Evaluator::BoolInteger(eval) => {
let computed = self

View file

@ -66,8 +66,8 @@
use crate::applicable_declarations::ApplicableDeclarationBlock;
use crate::bloom::StyleBloom;
use crate::context::{SharedStyleContext, StyleContext};
use crate::computed_value_flags::ComputedValueFlags;
use crate::context::{SharedStyleContext, StyleContext};
use crate::dom::{SendElement, TElement};
use crate::properties::ComputedValues;
use crate::rule_tree::StrongRuleNode;

View file

@ -293,10 +293,7 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
.add_flags(ComputedValueFlags::SELF_OR_ANCESTOR_HAS_CONTAIN_STYLE);
}
if box_style
.clone_container_type()
.is_size_container_type()
{
if box_style.clone_container_type().is_size_container_type() {
self.style
.add_flags(ComputedValueFlags::SELF_OR_ANCESTOR_HAS_SIZE_CONTAINER_TYPE);
}
@ -446,7 +443,9 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
if !column_style.column_rule_has_nonzero_width() {
return;
}
self.style.mutate_column().set_column_rule_width(crate::Zero::zero());
self.style
.mutate_column()
.set_column_rule_width(crate::Zero::zero());
}
/// outline-style: none causes a computed outline-width of zero at computed
@ -459,7 +458,9 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
if !outline.outline_has_nonzero_width() {
return;
}
self.style.mutate_outline().set_outline_width(crate::Zero::zero());
self.style
.mutate_outline()
.set_outline_width(crate::Zero::zero());
}
/// CSS overflow-x and overflow-y require some fixup as well in some cases.
@ -484,7 +485,10 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
#[cfg(feature = "gecko")]
fn adjust_for_contain(&mut self) {
let box_style = self.style.get_box();
debug_assert_eq!(box_style.clone_contain(), box_style.clone_effective_containment());
debug_assert_eq!(
box_style.clone_contain(),
box_style.clone_effective_containment()
);
let container_type = box_style.clone_container_type();
let content_visibility = box_style.clone_content_visibility();
if container_type == ContainerType::Normal &&
@ -499,28 +503,33 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
// `content-visibility:auto` also applies size containment when content
// is not relevant (and therefore skipped). This is checked in
// nsIFrame::GetContainSizeAxes.
ContentVisibility::Auto => new_contain.insert(
Contain::LAYOUT | Contain::PAINT | Contain::STYLE),
ContentVisibility::Hidden => new_contain.insert(
Contain::LAYOUT | Contain::PAINT | Contain::SIZE | Contain::STYLE),
ContentVisibility::Auto => {
new_contain.insert(Contain::LAYOUT | Contain::PAINT | Contain::STYLE)
},
ContentVisibility::Hidden => new_contain
.insert(Contain::LAYOUT | Contain::PAINT | Contain::SIZE | Contain::STYLE),
}
match container_type {
ContainerType::Normal => {},
// https://drafts.csswg.org/css-contain-3/#valdef-container-type-inline-size:
// Applies layout containment, style containment, and inline-size
// containment to the principal box.
ContainerType::InlineSize => new_contain.insert(
Contain::LAYOUT | Contain::STYLE | Contain::INLINE_SIZE),
ContainerType::InlineSize => {
new_contain.insert(Contain::LAYOUT | Contain::STYLE | Contain::INLINE_SIZE)
},
// https://drafts.csswg.org/css-contain-3/#valdef-container-type-size:
// Applies layout containment, style containment, and size
// containment to the principal box.
ContainerType::Size => new_contain.insert(
Contain::LAYOUT | Contain::STYLE | Contain::SIZE),
ContainerType::Size => {
new_contain.insert(Contain::LAYOUT | Contain::STYLE | Contain::SIZE)
},
}
if new_contain == old_contain {
return;
}
self.style.mutate_box().set_effective_containment(new_contain);
self.style
.mutate_box()
.set_effective_containment(new_contain);
}
/// Handles the relevant sections in:

View file

@ -420,7 +420,10 @@ where
originating_element_style: &PrimaryStyle,
layout_parent_style: Option<&ComputedValues>,
) -> Option<ResolvedStyle> {
let MatchingResults { rule_node, mut flags } = self.match_pseudo(
let MatchingResults {
rule_node,
mut flags,
} = self.match_pseudo(
&originating_element_style.style.0,
pseudo,
VisitedHandlingMode::AllLinksUnvisited,
@ -428,14 +431,16 @@ where
let mut visited_rules = None;
if originating_element_style.style().visited_style().is_some() {
visited_rules = self.match_pseudo(
&originating_element_style.style.0,
pseudo,
VisitedHandlingMode::RelevantLinkVisited,
).map(|results| {
flags |= results.flags;
results.rule_node
});
visited_rules = self
.match_pseudo(
&originating_element_style.style.0,
pseudo,
VisitedHandlingMode::RelevantLinkVisited,
)
.map(|results| {
flags |= results.flags;
results.rule_node
});
}
Some(self.cascade_style_and_visited(
@ -553,8 +558,7 @@ where
self.context.shared.quirks_mode(),
NeedsSelectorFlags::Yes,
);
matching_context.extra_data.originating_element_style =
Some(originating_element_style);
matching_context.extra_data.originating_element_style = Some(originating_element_style);
// NB: We handle animation rules for ::before and ::after when
// traversing them.

View file

@ -13,7 +13,7 @@ use crate::shared_lock::{SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard};
use crate::str::CssStringWriter;
use crate::stylesheets::CssRules;
use crate::values::CssUrl;
use cssparser::{Parser, SourceLocation, BasicParseErrorKind};
use cssparser::{BasicParseErrorKind, Parser, SourceLocation};
#[cfg(feature = "gecko")]
use malloc_size_of::{MallocSizeOfOps, MallocUnconditionalShallowSizeOf};
use servo_arc::Arc;
@ -260,9 +260,7 @@ impl DocumentCondition {
let condition = DocumentCondition(conditions);
if !condition.allowed_in(context) {
return Err(input.new_error(BasicParseErrorKind::AtRuleInvalid(
"-moz-document".into(),
)));
return Err(input.new_error(BasicParseErrorKind::AtRuleInvalid("-moz-document".into())));
}
Ok(condition)
}

View file

@ -19,8 +19,8 @@ use crate::values::computed::font::FamilyName;
use crate::values::serialize_atom_identifier;
use crate::Atom;
use cssparser::{
AtRuleParser, BasicParseErrorKind, CowRcStr, RuleBodyParser, RuleBodyItemParser, Parser,
ParserState, QualifiedRuleParser, DeclarationParser, SourceLocation, Token,
AtRuleParser, BasicParseErrorKind, CowRcStr, DeclarationParser, Parser, ParserState,
QualifiedRuleParser, RuleBodyItemParser, RuleBodyParser, SourceLocation, Token,
};
use std::fmt::{self, Write};
use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
@ -222,12 +222,17 @@ where
}
}
impl<'a, 'b, 'i, T> RuleBodyItemParser<'i, (), StyleParseErrorKind<'i>> for FFVDeclarationsParser<'a, 'b, T>
impl<'a, 'b, 'i, T> RuleBodyItemParser<'i, (), StyleParseErrorKind<'i>>
for FFVDeclarationsParser<'a, 'b, T>
where
T: Parse,
{
fn parse_declarations(&self) -> bool { true }
fn parse_qualified(&self) -> bool { false }
fn parse_declarations(&self) -> bool {
true
}
fn parse_qualified(&self) -> bool {
false
}
}
macro_rules! font_feature_values_blocks {

View file

@ -13,8 +13,8 @@ use crate::shared_lock::{
};
use crate::str::CssStringWriter;
use crate::stylesheets::{
layer_rule::LayerName, supports_rule::SupportsCondition, CssRule,
CssRuleType, StylesheetInDocument,
layer_rule::LayerName, supports_rule::SupportsCondition, CssRule, CssRuleType,
StylesheetInDocument,
};
use crate::values::CssUrl;
use cssparser::{Parser, SourceLocation};
@ -258,7 +258,8 @@ impl ImportRule {
.parse_nested_block(|input| LayerName::parse(context, input))
.map(|name| ImportLayer::Named(name))
})
.ok().unwrap_or(ImportLayer::None)
.ok()
.unwrap_or(ImportLayer::None)
};
#[cfg(feature = "gecko")]
@ -272,9 +273,8 @@ impl ImportRule {
input
.try_parse(SupportsCondition::parse_for_import)
.map(|condition| {
let enabled = context.nest_for_rule(CssRuleType::Style, |context| {
condition.eval(context)
});
let enabled = context
.nest_for_rule(CssRuleType::Style, |context| condition.eval(context));
ImportSupportsCondition { condition, enabled }
})
.ok()

View file

@ -23,8 +23,8 @@ use cssparser::{
QualifiedRuleParser, RuleBodyItemParser, RuleBodyParser, SourceLocation, Token,
};
use servo_arc::Arc;
use std::fmt::{self, Write};
use std::borrow::Cow;
use std::fmt::{self, Write};
use style_traits::{CssWriter, ParseError, ParsingMode, StyleParseErrorKind, ToCss};
/// A [`@keyframes`][keyframes] rule.
@ -545,7 +545,9 @@ pub fn parse_keyframe_list<'a>(
shared_lock,
declarations: &mut declarations,
};
RuleBodyParser::new(input, &mut parser).filter_map(Result::ok) .collect()
RuleBodyParser::new(input, &mut parser)
.filter_map(Result::ok)
.collect()
}
impl<'a, 'b, 'i> AtRuleParser<'i> for KeyframeListParser<'a, 'b> {
@ -588,28 +590,31 @@ impl<'a, 'b, 'i> QualifiedRuleParser<'i> for KeyframeListParser<'a, 'b> {
) -> Result<Self::QualifiedRule, ParseError<'i>> {
let mut block = PropertyDeclarationBlock::new();
let declarations = &mut self.declarations;
self.context.nest_for_rule(CssRuleType::Keyframe, |context| {
let mut parser = KeyframeDeclarationParser {
context: &context,
declarations,
};
let mut iter = RuleBodyParser::new(input, &mut parser);
while let Some(declaration) = iter.next() {
match declaration {
Ok(()) => {
block.extend(iter.parser.declarations.drain(), Importance::Normal);
},
Err((error, slice)) => {
iter.parser.declarations.clear();
let location = error.location;
let error =
ContextualParseError::UnsupportedKeyframePropertyDeclaration(slice, error);
context.log_css_error(location, error);
},
self.context
.nest_for_rule(CssRuleType::Keyframe, |context| {
let mut parser = KeyframeDeclarationParser {
context: &context,
declarations,
};
let mut iter = RuleBodyParser::new(input, &mut parser);
while let Some(declaration) = iter.next() {
match declaration {
Ok(()) => {
block.extend(iter.parser.declarations.drain(), Importance::Normal);
},
Err((error, slice)) => {
iter.parser.declarations.clear();
let location = error.location;
let error =
ContextualParseError::UnsupportedKeyframePropertyDeclaration(
slice, error,
);
context.log_css_error(location, error);
},
}
// `parse_important` is not called here, `!important` is not allowed in keyframe blocks.
}
// `parse_important` is not called here, `!important` is not allowed in keyframe blocks.
}
});
});
Ok(Arc::new(self.shared_lock.wrap(Keyframe {
selector,
block: Arc::new(self.shared_lock.wrap(block)),
@ -618,9 +623,15 @@ impl<'a, 'b, 'i> QualifiedRuleParser<'i> for KeyframeListParser<'a, 'b> {
}
}
impl<'a, 'b, 'i> RuleBodyItemParser<'i, Arc<Locked<Keyframe>>, StyleParseErrorKind<'i>> for KeyframeListParser<'a, 'b> {
fn parse_qualified(&self) -> bool { true }
fn parse_declarations(&self) -> bool { false }
impl<'a, 'b, 'i> RuleBodyItemParser<'i, Arc<Locked<Keyframe>>, StyleParseErrorKind<'i>>
for KeyframeListParser<'a, 'b>
{
fn parse_qualified(&self) -> bool {
true
}
fn parse_declarations(&self) -> bool {
false
}
}
struct KeyframeDeclarationParser<'a, 'b: 'a> {
@ -668,7 +679,13 @@ impl<'a, 'b, 'i> DeclarationParser<'i> for KeyframeDeclarationParser<'a, 'b> {
}
}
impl<'a, 'b, 'i> RuleBodyItemParser<'i, (), StyleParseErrorKind<'i>> for KeyframeDeclarationParser<'a, 'b> {
fn parse_qualified(&self) -> bool { false }
fn parse_declarations(&self) -> bool { true }
impl<'a, 'b, 'i> RuleBodyItemParser<'i, (), StyleParseErrorKind<'i>>
for KeyframeDeclarationParser<'a, 'b>
{
fn parse_qualified(&self) -> bool {
false
}
fn parse_declarations(&self) -> bool {
true
}
}

View file

@ -8,7 +8,7 @@
use crate::media_queries::MediaList;
use crate::parser::ParserContext;
use crate::shared_lock::{Locked, SharedRwLock};
use crate::stylesheets::import_rule::{ImportLayer, ImportSupportsCondition, ImportRule};
use crate::stylesheets::import_rule::{ImportLayer, ImportRule, ImportSupportsCondition};
use crate::values::CssUrl;
use cssparser::SourceLocation;
use servo_arc::Arc;

View file

@ -225,10 +225,7 @@ impl fmt::Debug for UrlExtraData {
formatter
.debug_struct("URLExtraData")
.field("chrome_rules_enabled", &self.chrome_rules_enabled())
.field(
"base",
&DebugURI(self.as_ref().mBaseURI.raw()),
)
.field("base", &DebugURI(self.as_ref().mBaseURI.raw()))
.field(
"referrer",
&DebugReferrerInfo(self.as_ref().mReferrerInfo.raw()),
@ -481,9 +478,7 @@ impl DeepCloneWithLock for CssRule {
params: &DeepCloneParams,
) -> CssRule {
match *self {
CssRule::Namespace(ref arc) => {
CssRule::Namespace(arc.clone())
},
CssRule::Namespace(ref arc) => CssRule::Namespace(arc.clone()),
CssRule::Import(ref arc) => {
let rule = arc
.read_with(guard)
@ -506,19 +501,13 @@ impl DeepCloneWithLock for CssRule {
let rule = arc.read_with(guard);
CssRule::FontFace(Arc::new(lock.wrap(rule.clone())))
},
CssRule::FontFeatureValues(ref arc) => {
CssRule::FontFeatureValues(arc.clone())
},
CssRule::FontPaletteValues(ref arc) => {
CssRule::FontPaletteValues(arc.clone())
},
CssRule::FontFeatureValues(ref arc) => CssRule::FontFeatureValues(arc.clone()),
CssRule::FontPaletteValues(ref arc) => CssRule::FontPaletteValues(arc.clone()),
CssRule::CounterStyle(ref arc) => {
let rule = arc.read_with(guard);
CssRule::CounterStyle(Arc::new(lock.wrap(rule.clone())))
},
CssRule::Viewport(ref arc) => {
CssRule::Viewport(arc.clone())
},
CssRule::Viewport(ref arc) => CssRule::Viewport(arc.clone()),
CssRule::Keyframes(ref arc) => {
let rule = arc.read_with(guard);
CssRule::Keyframes(Arc::new(
@ -542,9 +531,7 @@ impl DeepCloneWithLock for CssRule {
CssRule::Document(ref arc) => {
CssRule::Document(Arc::new(arc.deep_clone_with_lock(lock, guard, params)))
},
CssRule::LayerStatement(ref arc) => {
CssRule::LayerStatement(arc.clone())
},
CssRule::LayerStatement(ref arc) => CssRule::LayerStatement(arc.clone()),
CssRule::LayerBlock(ref arc) => {
CssRule::LayerBlock(Arc::new(arc.deep_clone_with_lock(lock, guard, params)))
},

View file

@ -147,8 +147,8 @@ impl<'a, 'i> TopLevelRuleParser<'a, 'i> {
// If there's anything that isn't a namespace rule (or import rule, but
// we checked that already at the beginning), reject with a
// StateError.
if new_state == State::Namespaces
&& ctx.rule_list[ctx.index..]
if new_state == State::Namespaces &&
ctx.rule_list[ctx.index..]
.iter()
.any(|r| !matches!(*r, CssRule::Namespace(..)))
{
@ -356,12 +356,11 @@ impl<'a, 'i> AtRuleParser<'i> for TopLevelRuleParser<'a, 'i> {
};
self.state = State::Namespaces;
self.rules
.push(CssRule::Namespace(Arc::new(NamespaceRule {
prefix,
url,
source_location: start.source_location(),
})));
self.rules.push(CssRule::Namespace(Arc::new(NamespaceRule {
prefix,
url,
source_location: start.source_location(),
})));
},
AtRulePrelude::Layer(..) => {
AtRuleParser::rule_without_block(&mut self.nested(), prelude, start)?;
@ -489,7 +488,11 @@ impl<'a, 'b, 'i> NestedRuleParser<'a, 'b, 'i> {
Ok(()) => {},
Err((error, slice)) => {
if parse_declarations {
iter.parser.declaration_parser_state.did_error(iter.parser.context, error, slice);
iter.parser.declaration_parser_state.did_error(
iter.parser.context,
error,
slice,
);
} else {
let location = error.location;
let error = ContextualParseError::InvalidRule(slice, error);
@ -541,7 +544,7 @@ impl<'a, 'b, 'i> AtRuleParser<'i> for NestedRuleParser<'a, 'b, 'i> {
input: &mut Parser<'i, 't>,
) -> Result<Self::Prelude, ParseError<'i>> {
if !self.allow_at_and_qualified_rules() {
return Err(input.new_error(BasicParseErrorKind::AtRuleInvalid(name)))
return Err(input.new_error(BasicParseErrorKind::AtRuleInvalid(name)));
}
Ok(match_ignore_ascii_case! { &*name,
"media" => {
@ -874,7 +877,8 @@ impl<'a, 'b, 'i> DeclarationParser<'i> for NestedRuleParser<'a, 'b, 'i> {
name: CowRcStr<'i>,
input: &mut Parser<'i, 't>,
) -> Result<(), ParseError<'i>> {
self.declaration_parser_state.parse_value(self.context, name, input)
self.declaration_parser_state
.parse_value(self.context, name, input)
}
}

View file

@ -74,7 +74,10 @@ where
CssRule::FontPaletteValues(_) => None,
CssRule::Style(ref style_rule) => {
let style_rule = style_rule.read_with(guard);
style_rule.rules.as_ref().map(|r| r.read_with(guard).0.iter())
style_rule
.rules
.as_ref()
.map(|r| r.read_with(guard).0.iter())
},
CssRule::Import(ref import_rule) => {
let import_rule = import_rule.read_with(guard);
@ -108,9 +111,7 @@ where
}
Some(supports_rule.rules.read_with(guard).0.iter())
},
CssRule::LayerBlock(ref layer_rule) => {
Some(layer_rule.rules.read_with(guard).0.iter())
},
CssRule::LayerBlock(ref layer_rule) => Some(layer_rule.rules.read_with(guard).0.iter()),
}
}
}

View file

@ -6,9 +6,11 @@
use crate::properties::PropertyDeclarationBlock;
use crate::selector_parser::SelectorImpl;
use crate::shared_lock::{DeepCloneParams, DeepCloneWithLock, Locked, SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard};
use crate::stylesheets::CssRules;
use crate::shared_lock::{
DeepCloneParams, DeepCloneWithLock, Locked, SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard,
};
use crate::str::CssStringWriter;
use crate::stylesheets::CssRules;
use cssparser::SourceLocation;
#[cfg(feature = "gecko")]
use malloc_size_of::MallocUnconditionalShallowSizeOf;
@ -60,7 +62,8 @@ impl StyleRule {
n += self.block.unconditional_shallow_size_of(ops) +
self.block.read_with(guard).size_of(ops);
if let Some(ref rules) = self.rules {
n += rules.unconditional_shallow_size_of(ops) + rules.read_with(guard).size_of(guard, ops)
n += rules.unconditional_shallow_size_of(ops) +
rules.read_with(guard).size_of(guard, ops)
}
n
}
@ -87,7 +90,7 @@ impl ToCssWithGuard for StyleRule {
dest.write_str("\n ")?;
declaration_block.to_css(dest)?;
}
return rules.to_css_block_without_opening(guard, dest)
return rules.to_css_block_without_opening(guard, dest);
}
}

View file

@ -537,7 +537,12 @@ impl Stylesheet {
let source_map_url = input.current_source_map_url().map(String::from);
let source_url = input.current_source_url().map(String::from);
(rule_parser.context.namespaces.into_owned(), rule_parser.rules, source_map_url, source_url)
(
rule_parser.context.namespaces.into_owned(),
rule_parser.rules,
source_map_url,
source_url,
)
}
/// Creates an empty stylesheet and parses it with a given base url, origin

View file

@ -329,9 +329,7 @@ impl ToCss for SupportsCondition {
}
Ok(())
},
SupportsCondition::Declaration(ref decl) => {
decl.to_css(dest)
},
SupportsCondition::Declaration(ref decl) => decl.to_css(dest),
SupportsCondition::Selector(ref selector) => {
dest.write_str("selector(")?;
selector.to_css(dest)?;

View file

@ -310,9 +310,15 @@ impl<'a, 'b, 'i> DeclarationParser<'i> for ViewportRuleParser<'a, 'b> {
}
}
impl<'a, 'b, 'i> RuleBodyItemParser<'i, ViewportDeclarations, StyleParseErrorKind<'i>> for ViewportRuleParser<'a, 'b> {
fn parse_declarations(&self) -> bool { true }
fn parse_qualified(&self) -> bool { false }
impl<'a, 'b, 'i> RuleBodyItemParser<'i, ViewportDeclarations, StyleParseErrorKind<'i>>
for ViewportRuleParser<'a, 'b>
{
fn parse_declarations(&self) -> bool {
true
}
fn parse_qualified(&self) -> bool {
false
}
}
/// A `@viewport` rule.

View file

@ -50,7 +50,9 @@ use selectors::attr::{CaseSensitivity, NamespaceConstraint};
use selectors::bloom::BloomFilter;
use selectors::matching::VisitedHandlingMode;
use selectors::matching::{matches_selector, MatchingContext, MatchingMode, NeedsSelectorFlags};
use selectors::parser::{AncestorHashes, Combinator, Component, Selector, SelectorList, SelectorIter};
use selectors::parser::{
AncestorHashes, Combinator, Component, Selector, SelectorIter, SelectorList,
};
use selectors::visitor::{SelectorListKind, SelectorVisitor};
use selectors::NthIndexCache;
use servo_arc::{Arc, ArcBorrow};
@ -593,7 +595,8 @@ impl<'a> ContainingRuleState<'a> {
fn restore(&mut self, saved: &SavedContainingRuleState) {
debug_assert!(self.layer_name.0.len() >= saved.layer_name_len);
debug_assert!(self.ancestor_selector_lists.len() >= saved.ancestor_selector_lists_len);
self.ancestor_selector_lists.truncate(saved.ancestor_selector_lists_len);
self.ancestor_selector_lists
.truncate(saved.ancestor_selector_lists_len);
self.layer_name.0.truncate(saved.layer_name_len);
self.layer_id = saved.layer_id;
self.container_condition_id = saved.container_condition_id;
@ -1154,8 +1157,7 @@ impl Stylist {
);
matching_context.pseudo_element_matching_fn = matching_fn;
matching_context.extra_data.originating_element_style =
Some(originating_element_style);
matching_context.extra_data.originating_element_style = Some(originating_element_style);
self.push_applicable_declarations(
element,
@ -1188,8 +1190,7 @@ impl Stylist {
needs_selector_flags,
);
matching_context.pseudo_element_matching_fn = matching_fn;
matching_context.extra_data.originating_element_style =
Some(originating_element_style);
matching_context.extra_data.originating_element_style = Some(originating_element_style);
self.push_applicable_declarations(
element,
@ -1733,20 +1734,12 @@ impl ExtraStyleData {
}
/// Add the given @font-feature-values rule.
fn add_font_feature_values(
&mut self,
rule: &Arc<FontFeatureValuesRule>,
layer: LayerId,
) {
fn add_font_feature_values(&mut self, rule: &Arc<FontFeatureValuesRule>, layer: LayerId) {
self.font_feature_values.push(rule.clone(), layer);
}
/// Add the given @font-palette-values rule.
fn add_font_palette_values(
&mut self,
rule: &Arc<FontPaletteValuesRule>,
layer: LayerId,
) {
fn add_font_palette_values(&mut self, rule: &Arc<FontPaletteValuesRule>, layer: LayerId) {
self.font_palette_values.push(rule.clone(), layer);
}
@ -2666,13 +2659,11 @@ impl CascadeData {
let has_nested_rules = style_rule.rules.is_some();
let ancestor_selectors = containing_rule_state.ancestor_selector_lists.last();
if has_nested_rules {
selectors_for_nested_rules = Some(
if ancestor_selectors.is_some() {
Cow::Owned(SelectorList(Default::default()))
} else {
Cow::Borrowed(&style_rule.selectors)
}
);
selectors_for_nested_rules = Some(if ancestor_selectors.is_some() {
Cow::Owned(SelectorList(Default::default()))
} else {
Cow::Borrowed(&style_rule.selectors)
});
}
for selector in &style_rule.selectors.0 {
@ -2721,12 +2712,15 @@ impl CascadeData {
containing_rule_state.container_condition_id,
);
if let Some(Cow::Owned(ref mut nested_selectors)) = selectors_for_nested_rules {
if let Some(Cow::Owned(ref mut nested_selectors)) =
selectors_for_nested_rules
{
nested_selectors.0.push(rule.selector.clone())
}
if rebuild_kind.should_rebuild_invalidation() {
self.invalidation_map.note_selector(&rule.selector, quirks_mode)?;
self.invalidation_map
.note_selector(&rule.selector, quirks_mode)?;
let mut needs_revalidation = false;
let mut visitor = StylistSelectorVisitor {
needs_revalidation: &mut needs_revalidation,
@ -2777,17 +2771,19 @@ impl CascadeData {
// NOTE(emilio): It's fine to look at :host and then at
// ::slotted(..), since :host::slotted(..) could never
// possibly match, as <slot> is not a valid shadow host.
let rules =
if rule.selector.is_featureless_host_selector_or_pseudo_element() {
self.host_rules
.get_or_insert_with(|| Box::new(Default::default()))
} else if rule.selector.is_slotted() {
self.slotted_rules
.get_or_insert_with(|| Box::new(Default::default()))
} else {
&mut self.normal_rules
}
.for_insertion(pseudo_element);
let rules = if rule
.selector
.is_featureless_host_selector_or_pseudo_element()
{
self.host_rules
.get_or_insert_with(|| Box::new(Default::default()))
} else if rule.selector.is_slotted() {
self.slotted_rules
.get_or_insert_with(|| Box::new(Default::default()))
} else {
&mut self.normal_rules
}
.for_insertion(pseudo_element);
rules.insert(rule, quirks_mode)?;
}
}
@ -2946,14 +2942,19 @@ impl CascadeData {
.saw_effective(import_rule);
}
match import_rule.layer {
ImportLayer::Named(ref name) => maybe_register_layers(self, Some(name), containing_rule_state),
ImportLayer::Anonymous => maybe_register_layers(self, None, containing_rule_state),
ImportLayer::Named(ref name) => {
maybe_register_layers(self, Some(name), containing_rule_state)
},
ImportLayer::Anonymous => {
maybe_register_layers(self, None, containing_rule_state)
},
ImportLayer::None => {},
}
},
CssRule::Media(ref media_rule) => {
if rebuild_kind.should_rebuild_invalidation() {
self.effective_media_query_results.saw_effective(&**media_rule);
self.effective_media_query_results
.saw_effective(&**media_rule);
}
},
CssRule::LayerBlock(ref rule) => {
@ -2970,7 +2971,7 @@ impl CascadeData {
if let Some(s) = selectors_for_nested_rules {
containing_rule_state.ancestor_selector_lists.push(s);
}
}
},
CssRule::Container(ref rule) => {
let id = ContainerConditionId(self.container_conditions.len() as u16);
self.container_conditions.push(ContainerConditionReference {
@ -3122,8 +3123,9 @@ impl CascadeData {
CssRule::Media(ref media_rule) => {
let mq = media_rule.media_queries.read_with(guard);
let effective_now = mq.evaluate(device, quirks_mode);
let effective_then =
self.effective_media_query_results.was_effective(&**media_rule);
let effective_then = self
.effective_media_query_results
.was_effective(&**media_rule);
if effective_now != effective_then {
debug!(

View file

@ -16,7 +16,8 @@ use crate::values::distance::{ComputeSquaredDistance, SquaredDistance};
impl Animate for FontVariationSettings {
#[inline]
fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> {
let result: Vec<_> = super::lists::by_computed_value::animate(&self.0, &other.0, procedure)?;
let result: Vec<_> =
super::lists::by_computed_value::animate(&self.0, &other.0, procedure)?;
Ok(Self(result.into_boxed_slice()))
}
}

View file

@ -82,7 +82,11 @@ impl Animate for generics::TrackRepeat<LengthPercentage, Integer> {
}
let count = self.count;
let track_sizes = super::lists::by_computed_value::animate(&self.track_sizes, &other.track_sizes, procedure)?;
let track_sizes = super::lists::by_computed_value::animate(
&self.track_sizes,
&other.track_sizes,
procedure,
)?;
// The length of |line_names| is always 0 or N+1, where N is the length
// of |track_sizes|. Besides, <line-names> is always discrete.
@ -120,7 +124,8 @@ impl Animate for TrackList {
return Err(());
}
let values = super::lists::by_computed_value::animate(&self.values, &other.values, procedure)?;
let values =
super::lists::by_computed_value::animate(&self.values, &other.values, procedure)?;
// The length of |line_names| is always 0 or N+1, where N is the length
// of |track_sizes|. Besides, <line-names> is always discrete.

View file

@ -8,7 +8,10 @@
/// https://drafts.csswg.org/web-animations-1/#by-computed-value
pub mod by_computed_value {
use crate::values::{animated::{Animate, Procedure}, distance::{ComputeSquaredDistance, SquaredDistance}};
use crate::values::{
animated::{Animate, Procedure},
distance::{ComputeSquaredDistance, SquaredDistance},
};
use std::iter::FromIterator;
#[allow(missing_docs)]
@ -18,11 +21,12 @@ pub mod by_computed_value {
C: FromIterator<T>,
{
if left.len() != right.len() {
return Err(())
return Err(());
}
left.iter().zip(right.iter()).map(|(left, right)| {
left.animate(right, procedure)
}).collect()
left.iter()
.zip(right.iter())
.map(|(left, right)| left.animate(right, procedure))
.collect()
}
#[allow(missing_docs)]
@ -31,11 +35,12 @@ pub mod by_computed_value {
T: ComputeSquaredDistance,
{
if left.len() != right.len() {
return Err(())
return Err(());
}
left.iter().zip(right.iter()).map(|(left, right)| {
left.compute_squared_distance(right)
}).sum()
left.iter()
.zip(right.iter())
.map(|(left, right)| left.compute_squared_distance(right))
.sum()
}
}
@ -44,8 +49,11 @@ pub mod by_computed_value {
///
/// https://drafts.csswg.org/web-animations-1/#animating-shadow-lists
pub mod with_zero {
use crate::values::{animated::{Animate, Procedure}, distance::{ComputeSquaredDistance, SquaredDistance}};
use crate::values::animated::ToAnimatedZero;
use crate::values::{
animated::{Animate, Procedure},
distance::{ComputeSquaredDistance, SquaredDistance},
};
use itertools::{EitherOrBoth, Itertools};
use std::iter::FromIterator;
@ -56,23 +64,16 @@ pub mod with_zero {
C: FromIterator<T>,
{
if procedure == Procedure::Add {
return Ok(
left.iter().chain(right.iter()).cloned().collect()
);
return Ok(left.iter().chain(right.iter()).cloned().collect());
}
left.iter().zip_longest(right.iter()).map(|it| {
match it {
EitherOrBoth::Both(left, right) => {
left.animate(right, procedure)
},
EitherOrBoth::Left(left) => {
left.animate(&left.to_animated_zero()?, procedure)
},
EitherOrBoth::Right(right) => {
right.to_animated_zero()?.animate(right, procedure)
}
}
}).collect()
left.iter()
.zip_longest(right.iter())
.map(|it| match it {
EitherOrBoth::Both(left, right) => left.animate(right, procedure),
EitherOrBoth::Left(left) => left.animate(&left.to_animated_zero()?, procedure),
EitherOrBoth::Right(right) => right.to_animated_zero()?.animate(right, procedure),
})
.collect()
}
#[allow(missing_docs)]
@ -80,22 +81,24 @@ pub mod with_zero {
where
T: ToAnimatedZero + ComputeSquaredDistance,
{
left.iter().zip_longest(right.iter()).map(|it| {
match it {
EitherOrBoth::Both(left, right) => {
left.compute_squared_distance(right)
},
left.iter()
.zip_longest(right.iter())
.map(|it| match it {
EitherOrBoth::Both(left, right) => left.compute_squared_distance(right),
EitherOrBoth::Left(item) | EitherOrBoth::Right(item) => {
item.to_animated_zero()?.compute_squared_distance(item)
},
}
}).sum()
})
.sum()
}
}
/// https://drafts.csswg.org/web-animations-1/#repeatable-list
pub mod repeatable_list {
use crate::values::{animated::{Animate, Procedure}, distance::{ComputeSquaredDistance, SquaredDistance}};
pub mod repeatable_list {
use crate::values::{
animated::{Animate, Procedure},
distance::{ComputeSquaredDistance, SquaredDistance},
};
use std::iter::FromIterator;
#[allow(missing_docs)]
@ -110,9 +113,12 @@ pub mod repeatable_list {
return Err(());
}
let len = lcm(left.len(), right.len());
left.iter().cycle().zip(right.iter().cycle()).take(len).map(|(left, right)| {
left.animate(right, procedure)
}).collect()
left.iter()
.cycle()
.zip(right.iter().cycle())
.take(len)
.map(|(left, right)| left.animate(right, procedure))
.collect()
}
#[allow(missing_docs)]
@ -125,8 +131,11 @@ pub mod repeatable_list {
return Err(());
}
let len = lcm(left.len(), right.len());
left.iter().cycle().zip(right.iter().cycle()).take(len).map(|(left, right)| {
left.compute_squared_distance(right)
}).sum()
left.iter()
.cycle()
.zip(right.iter().cycle())
.take(len)
.map(|(left, right)| left.compute_squared_distance(right))
.sum()
}
}

View file

@ -22,9 +22,9 @@ use std::cmp;
pub mod color;
pub mod effects;
pub mod lists;
mod font;
mod grid;
pub mod lists;
mod svg;
pub mod transform;

View file

@ -20,9 +20,11 @@ where
return Err(());
}
match (self, other) {
(&SVGStrokeDashArray::Values(ref this), &SVGStrokeDashArray::Values(ref other)) => Ok(
SVGStrokeDashArray::Values(super::lists::repeatable_list::animate(this, other, procedure)?),
),
(&SVGStrokeDashArray::Values(ref this), &SVGStrokeDashArray::Values(ref other)) => {
Ok(SVGStrokeDashArray::Values(
super::lists::repeatable_list::animate(this, other, procedure)?,
))
},
_ => Err(()),
}
}

View file

@ -26,8 +26,8 @@ use std::fmt::{self, Write};
use style_traits::{CssWriter, ParseError, ToCss};
pub use crate::values::computed::Length as MozScriptMinSize;
pub use crate::values::specified::font::{FontPalette, FontSynthesis};
pub use crate::values::specified::font::MozScriptSizeMultiplier;
pub use crate::values::specified::font::{FontPalette, FontSynthesis};
pub use crate::values::specified::font::{
FontVariantAlternates, FontVariantEastAsian, FontVariantLigatures, FontVariantNumeric, XLang,
XTextScale,
@ -869,7 +869,7 @@ where
SpecifiedValueInfo,
ToComputedValue,
ToResolvedValue,
ToShmem
ToShmem,
)]
#[repr(C)]
#[value_info(other_values = "normal")]

View file

@ -48,18 +48,11 @@ impl specified::NoCalcLength {
) -> Length {
match *self {
Self::Absolute(length) => length.to_computed_value(context),
Self::FontRelative(length) => {
length.to_computed_value(context, base_size)
},
Self::ViewportPercentage(length) => {
length.to_computed_value(context)
},
Self::ContainerRelative(length) => {
length.to_computed_value(context)
},
Self::ServoCharacterWidth(length) => {
length.to_computed_value(context.style().get_font().clone_font_size().computed_size())
},
Self::FontRelative(length) => length.to_computed_value(context, base_size),
Self::ViewportPercentage(length) => length.to_computed_value(context),
Self::ContainerRelative(length) => length.to_computed_value(context),
Self::ServoCharacterWidth(length) => length
.to_computed_value(context.style().get_font().clone_font_size().computed_size()),
}
}
}
@ -71,9 +64,7 @@ impl ToComputedValue for specified::Length {
fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
match *self {
Self::NoCalc(l) => l.to_computed_value(context),
Self::Calc(ref calc) => {
calc.to_computed_value(context).to_length().unwrap()
},
Self::Calc(ref calc) => calc.to_computed_value(context).to_length().unwrap(),
}
}
@ -92,9 +83,7 @@ macro_rules! computed_length_percentage_or_auto {
pub fn to_used_value(&self, percentage_basis: Au) -> Option<Au> {
match *self {
Self::Auto => None,
Self::LengthPercentage(ref lp) => {
Some(lp.to_used_value(percentage_basis))
},
Self::LengthPercentage(ref lp) => Some(lp.to_used_value(percentage_basis)),
}
}

View file

@ -42,6 +42,8 @@ pub use self::align::{
#[cfg(feature = "gecko")]
pub use self::align::{AlignSelf, JustifySelf};
pub use self::angle::Angle;
pub use self::animation::{AnimationIterationCount, AnimationName, AnimationTimeline};
pub use self::animation::{ScrollAxis, ScrollTimelineName, TransitionProperty, ViewTimelineInset};
pub use self::background::{BackgroundRepeat, BackgroundSize};
pub use self::basic_shape::FillRule;
pub use self::border::{BorderCornerRadius, BorderRadius, BorderSpacing};
@ -50,6 +52,7 @@ pub use self::border::{BorderImageSlice, BorderImageWidth};
pub use self::box_::{
Appearance, BreakBetween, BreakWithin, Clear, ContainIntrinsicSize, ContentVisibility, Float,
};
pub use self::box_::{BaselineSource, TouchAction, VerticalAlign, WillChange};
pub use self::box_::{
Contain, ContainerName, ContainerType, Display, LineClamp, Overflow, OverflowAnchor,
};
@ -57,7 +60,6 @@ pub use self::box_::{OverflowClipBox, OverscrollBehavior, Perspective, Resize, S
pub use self::box_::{
ScrollSnapAlign, ScrollSnapAxis, ScrollSnapStop, ScrollSnapStrictness, ScrollSnapType,
};
pub use self::box_::{BaselineSource, TouchAction, VerticalAlign, WillChange};
pub use self::color::{
Color, ColorOrAuto, ColorPropertyValue, ColorScheme, ForcedColorAdjust, PrintColorAdjust,
};
@ -106,8 +108,6 @@ pub use self::transform::{TransformOrigin, TransformStyle, Translate};
#[cfg(feature = "gecko")]
pub use self::ui::CursorImage;
pub use self::ui::{BoolInteger, Cursor, UserSelect};
pub use self::animation::{AnimationIterationCount, AnimationName, AnimationTimeline};
pub use self::animation::{ScrollAxis, ScrollTimelineName, TransitionProperty, ViewTimelineInset};
pub use super::specified::TextTransform;
pub use super::specified::ViewportVariant;
pub use super::specified::{BorderStyle, TextDecorationLine};
@ -390,7 +390,12 @@ impl<'a> Context<'a> {
/// Apply text-zoom if enabled.
#[cfg(feature = "gecko")]
pub fn maybe_zoom_text(&self, size: CSSPixelLength) -> CSSPixelLength {
if self.style().get_font().clone__x_text_scale().text_zoom_enabled() {
if self
.style()
.get_font()
.clone__x_text_scale()
.text_zoom_enabled()
{
self.device().zoom_text(size)
} else {
size

View file

@ -125,7 +125,12 @@ impl ToResolvedValue for LineHeight {
}
let wm = context.style.writing_mode;
let vertical = wm.is_vertical() && !wm.is_sideways();
return Self::Length(context.device.calc_line_height(&self, vertical, context.style.get_font(), Some(context.element_info.element)));
return Self::Length(context.device.calc_line_height(
&self,
vertical,
context.style.get_font(),
Some(context.element_info.element),
));
}
if let LineHeight::Number(num) = &self {
let size = context.style.get_font().clone_font_size().computed_size();

View file

@ -5,7 +5,7 @@
//! CSS handling for the [`basic-shape`](https://drafts.csswg.org/css-shapes/#typedef-basic-shape)
//! types that are generic over their `ToCss` implementations.
use crate::values::animated::{Animate, Procedure, ToAnimatedZero, lists};
use crate::values::animated::{lists, Animate, Procedure, ToAnimatedZero};
use crate::values::distance::{ComputeSquaredDistance, SquaredDistance};
use crate::values::generics::border::GenericBorderRadius;
use crate::values::generics::position::GenericPosition;
@ -479,7 +479,8 @@ where
if self.fill != other.fill {
return Err(());
}
let coordinates = lists::by_computed_value::animate(&self.coordinates, &other.coordinates, procedure)?;
let coordinates =
lists::by_computed_value::animate(&self.coordinates, &other.coordinates, procedure)?;
Ok(Polygon {
fill: self.fill,
coordinates,

View file

@ -237,7 +237,16 @@ impl<Image> Content<Image> {
/// Items for the `content` property.
#[derive(
Clone, Debug, Eq, MallocSizeOf, PartialEq, ToComputedValue, SpecifiedValueInfo, ToCss, ToResolvedValue, ToShmem,
Clone,
Debug,
Eq,
MallocSizeOf,
PartialEq,
ToComputedValue,
SpecifiedValueInfo,
ToCss,
ToResolvedValue,
ToShmem,
)]
#[repr(u8)]
pub enum GenericContentItem<I> {

View file

@ -699,10 +699,8 @@ impl Parse for LineNameList {
// FIXME(emilio): we shouldn't expand repeat() at
// parse time for subgrid. (bug 1583429)
RepeatCount::Number(num) => {
let n = handle_size(
num.value() as usize * names_list.len());
line_names.extend(
names_list.iter().cloned().cycle().take(n));
let n = handle_size(num.value() as usize * names_list.len());
line_names.extend(names_list.iter().cloned().cycle().take(n));
},
RepeatCount::AutoFill if fill_data.is_none() => {
let fill_idx = line_names.len();

View file

@ -74,7 +74,18 @@ impl PaperSize {
///
/// https://drafts.csswg.org/css-page-3/#page-orientation-prop
#[derive(
Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss, ToResolvedValue, ToShmem,
Clone,
Copy,
Debug,
Eq,
MallocSizeOf,
Parse,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
#[repr(u8)]
pub enum PageOrientation {
@ -128,7 +139,10 @@ pub enum GenericPageSize<S> {
/// An orientation with no size.
Orientation(PageSizeOrientation),
/// Paper size by name
PaperSize(PaperSize, #[css(skip_if = "is_portrait")] PageSizeOrientation),
PaperSize(
PaperSize,
#[css(skip_if = "is_portrait")] PageSizeOrientation,
),
}
pub use self::GenericPageSize as PageSize;

View file

@ -100,7 +100,12 @@ fn nan_inf_enabled() -> bool {
}
/// Serialize a specified dimension with unit, calc, and NaN/infinity handling (if enabled)
pub fn serialize_specified_dimension<W>(v: f32, unit: &str, was_calc: bool, dest: &mut CssWriter<W>) -> fmt::Result
pub fn serialize_specified_dimension<W>(
v: f32,
unit: &str,
was_calc: bool,
dest: &mut CssWriter<W>,
) -> fmt::Result
where
W: Write,
{
@ -567,7 +572,10 @@ impl ToCss for CustomIdent {
pub struct DashedIdent(pub Atom);
impl Parse for DashedIdent {
fn parse<'i, 't>(_: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
fn parse<'i, 't>(
_: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
let location = input.current_source_location();
let ident = input.expect_ident()?;
if ident.starts_with("--") {

View file

@ -73,7 +73,7 @@ impl AngleDimension {
AngleDimension::Deg(_) => "deg",
AngleDimension::Rad(_) => "rad",
AngleDimension::Turn(_) => "turn",
AngleDimension::Grad(_) => "grad"
AngleDimension::Grad(_) => "grad",
}
}
}
@ -105,7 +105,12 @@ impl ToCss for Angle {
where
W: Write,
{
crate::values::serialize_specified_dimension(self.value.unitless_value(), self.value.unit(), self.was_calc, dest)
crate::values::serialize_specified_dimension(
self.value.unitless_value(),
self.value.unit(),
self.was_calc,
dest,
)
}
}
@ -117,11 +122,7 @@ impl ToComputedValue for Angle {
let degrees = self.degrees();
// NaN and +-infinity should degenerate to 0: https://github.com/w3c/csswg-drafts/issues/6105
ComputedAngle::from_degrees(if degrees.is_finite() {
degrees
} else {
0.0
})
ComputedAngle::from_degrees(if degrees.is_finite() { degrees } else { 0.0 })
}
#[inline]

View file

@ -19,7 +19,7 @@ use crate::values::generics::NonNegative;
use crate::values::specified::length::{FontBaseSize, PX_PER_PT};
use crate::values::specified::{AllowQuirks, Angle, Integer, LengthPercentage};
use crate::values::specified::{NoCalcLength, NonNegativeNumber, NonNegativePercentage, Number};
use crate::values::{CustomIdent, SelectorParseErrorKind, serialize_atom_identifier};
use crate::values::{serialize_atom_identifier, CustomIdent, SelectorParseErrorKind};
use crate::Atom;
use cssparser::{Parser, Token};
#[cfg(feature = "gecko")]
@ -1034,7 +1034,15 @@ bitflags! {
}
#[derive(
Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss, ToComputedValue, ToResolvedValue, ToShmem,
Clone,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToCss,
ToComputedValue,
ToResolvedValue,
ToShmem,
)]
#[repr(C, u8)]
/// Set of variant alternates
@ -1817,9 +1825,15 @@ pub struct FontPalette(Atom);
#[allow(missing_docs)]
impl FontPalette {
pub fn normal() -> Self { Self(atom!("normal")) }
pub fn light() -> Self { Self(atom!("light")) }
pub fn dark() -> Self { Self(atom!("dark")) }
pub fn normal() -> Self {
Self(atom!("normal"))
}
pub fn light() -> Self {
Self(atom!("light"))
}
pub fn dark() -> Self {
Self(atom!("dark"))
}
}
impl Parse for FontPalette {

View file

@ -190,12 +190,7 @@ impl Parse for Image {
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Image, ParseError<'i>> {
Image::parse_with_cors_mode(
context,
input,
CorsMode::None,
ParseImageFlags::empty()
)
Image::parse_with_cors_mode(context, input, CorsMode::None, ParseImageFlags::empty())
}
}
@ -204,9 +199,11 @@ impl Image {
context: &ParserContext,
input: &mut Parser<'i, 't>,
cors_mode: CorsMode,
flags: ParseImageFlags
flags: ParseImageFlags,
) -> Result<Image, ParseError<'i>> {
if !flags.contains(ParseImageFlags::FORBID_NONE) && input.try_parse(|i| i.expect_ident_matching("none")).is_ok() {
if !flags.contains(ParseImageFlags::FORBID_NONE) &&
input.try_parse(|i| i.expect_ident_matching("none")).is_ok()
{
return Ok(generic::Image::None);
}
@ -233,7 +230,9 @@ impl Image {
}
if cross_fade_enabled() {
if let Ok(cf) = input.try_parse(|input| CrossFade::parse(context, input, cors_mode, flags)) {
if let Ok(cf) =
input.try_parse(|input| CrossFade::parse(context, input, cors_mode, flags))
{
return Ok(generic::Image::CrossFade(Box::new(cf)));
}
}
@ -287,7 +286,7 @@ impl Image {
context,
input,
CorsMode::Anonymous,
ParseImageFlags::empty()
ParseImageFlags::empty(),
)
}
@ -296,12 +295,7 @@ impl Image {
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Image, ParseError<'i>> {
Self::parse_with_cors_mode(
context,
input,
CorsMode::None,
ParseImageFlags::FORBID_NONE
)
Self::parse_with_cors_mode(context, input, CorsMode::None, ParseImageFlags::FORBID_NONE)
}
/// Provides an alternate method for parsing, but only for urls.
@ -313,7 +307,7 @@ impl Image {
context,
input,
CorsMode::None,
ParseImageFlags::FORBID_NONE | ParseImageFlags::FORBID_NON_URL
ParseImageFlags::FORBID_NONE | ParseImageFlags::FORBID_NON_URL,
)
}
}
@ -324,11 +318,13 @@ impl CrossFade {
context: &ParserContext,
input: &mut Parser<'i, 't>,
cors_mode: CorsMode,
flags: ParseImageFlags
flags: ParseImageFlags,
) -> Result<Self, ParseError<'i>> {
input.expect_function_matching("cross-fade")?;
let elements = input.parse_nested_block(|input| {
input.parse_comma_separated(|input| CrossFadeElement::parse(context, input, cors_mode, flags))
input.parse_comma_separated(|input| {
CrossFadeElement::parse(context, input, cors_mode, flags)
})
})?;
let elements = crate::OwnedSlice::from(elements);
Ok(Self { elements })
@ -355,7 +351,7 @@ impl CrossFadeElement {
context: &ParserContext,
input: &mut Parser<'i, 't>,
cors_mode: CorsMode,
flags: ParseImageFlags
flags: ParseImageFlags,
) -> Result<Self, ParseError<'i>> {
// Try and parse a leading percent sign.
let mut percent = Self::parse_percentage(context, input);
@ -377,12 +373,14 @@ impl CrossFadeImage {
context: &ParserContext,
input: &mut Parser<'i, 't>,
cors_mode: CorsMode,
flags: ParseImageFlags
flags: ParseImageFlags,
) -> Result<Self, ParseError<'i>> {
if let Ok(image) = input.try_parse(|input| {
Image::parse_with_cors_mode(
context, input, cors_mode,
flags | ParseImageFlags::FORBID_NONE
context,
input,
cors_mode,
flags | ParseImageFlags::FORBID_NONE,
)
}) {
return Ok(Self::Image(image));
@ -396,7 +394,7 @@ impl ImageSet {
context: &ParserContext,
input: &mut Parser<'i, 't>,
cors_mode: CorsMode,
flags: ParseImageFlags
flags: ParseImageFlags,
) -> Result<Self, ParseError<'i>> {
let function = input.expect_function()?;
match_ignore_ascii_case! { &function,
@ -428,7 +426,7 @@ impl ImageSetItem {
context: &ParserContext,
input: &mut Parser<'i, 't>,
cors_mode: CorsMode,
flags: ParseImageFlags
flags: ParseImageFlags,
) -> Result<Self, ParseError<'i>> {
let image = match input.try_parse(|i| i.expect_url_or_string()) {
Ok(url) => Image::Url(SpecifiedImageUrl::parse_from_string(
@ -437,8 +435,10 @@ impl ImageSetItem {
cors_mode,
)),
Err(..) => Image::parse_with_cors_mode(
context, input, cors_mode,
flags | ParseImageFlags::FORBID_NONE | ParseImageFlags::FORBID_IMAGE_SET
context,
input,
cors_mode,
flags | ParseImageFlags::FORBID_NONE | ParseImageFlags::FORBID_IMAGE_SET,
)?,
};

View file

@ -22,9 +22,9 @@ use crate::{Zero, ZeroNoPercent};
use app_units::Au;
use cssparser::{Parser, Token};
use std::cmp;
use style_traits::values::specified::AllowedNumericType;
use std::fmt::{self, Write};
use style_traits::{ParseError, SpecifiedValueInfo, StyleParseErrorKind, CssWriter, ToCss};
use style_traits::values::specified::AllowedNumericType;
use style_traits::{CssWriter, ParseError, SpecifiedValueInfo, StyleParseErrorKind, ToCss};
pub use super::image::Image;
pub use super::image::{EndingShape as GradientEndingShape, Gradient};
@ -89,12 +89,9 @@ impl FontRelativeLength {
/// Return the unitless, raw value.
fn unitless_value(&self) -> CSSFloat {
match *self {
Self::Em(v) |
Self::Ex(v) |
Self::Ch(v) |
Self::Cap(v) |
Self::Ic(v) |
Self::Rem(v) => v,
Self::Em(v) | Self::Ex(v) | Self::Ch(v) | Self::Cap(v) | Self::Ic(v) | Self::Rem(v) => {
v
},
}
}
@ -574,7 +571,12 @@ impl ViewportPercentageLength {
// See bug 989802. We truncate so that adding multiple viewport units
// that add up to 100 does not overflow due to rounding differences
let trunc_scaled = ((length.0 as f64) * factor as f64 / 100.).trunc();
Au::from_f64_au(if trunc_scaled.is_nan() { 0.0f64 } else { trunc_scaled }).into()
Au::from_f64_au(if trunc_scaled.is_nan() {
0.0f64
} else {
trunc_scaled
})
.into()
}
}
@ -901,11 +903,8 @@ impl NoCalcLength {
/// because the font they're relative to should be zoomed already.
pub fn should_zoom_text(&self) -> bool {
match *self {
Self::Absolute(..) |
Self::ViewportPercentage(..) |
Self::ContainerRelative(..) => true,
Self::ServoCharacterWidth(..) |
Self::FontRelative(..) => false,
Self::Absolute(..) | Self::ViewportPercentage(..) | Self::ContainerRelative(..) => true,
Self::ServoCharacterWidth(..) | Self::FontRelative(..) => false,
}
}
@ -1101,7 +1100,12 @@ impl ToCss for NoCalcLength {
where
W: Write,
{
crate::values::serialize_specified_dimension(self.unitless_value(), self.unit(), false, dest)
crate::values::serialize_specified_dimension(
self.unitless_value(),
self.unit(),
false,
dest,
)
}
}

View file

@ -30,12 +30,15 @@ pub use self::align::{AlignContent, AlignItems, AlignSelf, AlignTracks, ContentD
#[cfg(feature = "gecko")]
pub use self::align::{JustifyContent, JustifyItems, JustifySelf, JustifyTracks, SelfAlignment};
pub use self::angle::{AllowUnitlessZeroAngle, Angle};
pub use self::animation::{AnimationIterationCount, AnimationName, AnimationTimeline};
pub use self::animation::{ScrollAxis, ScrollTimelineName, TransitionProperty, ViewTimelineInset};
pub use self::background::{BackgroundRepeat, BackgroundSize};
pub use self::basic_shape::FillRule;
pub use self::border::{BorderCornerRadius, BorderImageSlice, BorderImageWidth};
pub use self::border::{BorderImageRepeat, BorderImageSideWidth};
pub use self::border::{BorderRadius, BorderSideWidth, BorderSpacing, BorderStyle};
pub use self::box_::{Appearance, BreakBetween, BreakWithin, ContainerName, ContainerType};
pub use self::box_::{BaselineSource, TouchAction, VerticalAlign, WillChange};
pub use self::box_::{
Clear, ContainIntrinsicSize, ContentVisibility, Float, LineClamp, Overflow, OverflowAnchor,
};
@ -43,7 +46,6 @@ pub use self::box_::{Contain, Display};
pub use self::box_::{OverflowClipBox, OverscrollBehavior, Perspective, Resize, ScrollbarGutter};
pub use self::box_::{ScrollSnapAlign, ScrollSnapAxis, ScrollSnapStop};
pub use self::box_::{ScrollSnapStrictness, ScrollSnapType};
pub use self::box_::{BaselineSource, TouchAction, VerticalAlign, WillChange};
pub use self::color::{
Color, ColorOrAuto, ColorPropertyValue, ColorScheme, ForcedColorAdjust, PrintColorAdjust,
};
@ -100,8 +102,6 @@ pub use self::transform::{TransformOrigin, TransformStyle, Translate};
#[cfg(feature = "gecko")]
pub use self::ui::CursorImage;
pub use self::ui::{BoolInteger, Cursor, UserSelect};
pub use self::animation::{AnimationIterationCount, AnimationName, AnimationTimeline};
pub use self::animation::{ScrollAxis, ScrollTimelineName, TransitionProperty, ViewTimelineInset};
pub use super::generics::grid::GridTemplateComponent as GenericGridTemplateComponent;
#[cfg(feature = "gecko")]

View file

@ -10,7 +10,7 @@ use crate::values::computed::{Context, ToComputedValue};
use crate::values::generics::NonNegative;
use crate::values::specified::calc::CalcNode;
use crate::values::specified::Number;
use crate::values::{serialize_percentage, normalize, CSSFloat};
use crate::values::{normalize, serialize_percentage, CSSFloat};
use cssparser::{Parser, Token};
use std::fmt::{self, Write};
use style_traits::values::specified::AllowedNumericType;

View file

@ -55,10 +55,12 @@ impl SourceSizeList {
/// Evaluate this <source-size-list> to get the final viewport length.
pub fn evaluate(&self, device: &Device, quirks_mode: QuirksMode) -> Au {
computed::Context::for_media_query_evaluation(device, quirks_mode, |context| {
let matching_source_size = self
.source_sizes
.iter()
.find(|source_size| source_size.condition.matches(context).to_bool(/* unknown = */ false));
let matching_source_size = self.source_sizes.iter().find(|source_size| {
source_size
.condition
.matches(context)
.to_bool(/* unknown = */ false)
});
match matching_source_size {
Some(source_size) => source_size.value.to_computed_value(context),

View file

@ -995,9 +995,7 @@ fn parse_number(iter: &mut Peekable<Cloned<slice::Iter<u8>>>) -> Result<CSSFloat
}
if value.is_finite() {
Ok(value
.min(f32::MAX as f64)
.max(f32::MIN as f64) as CSSFloat)
Ok(value.min(f32::MAX as f64).max(f32::MIN as f64) as CSSFloat)
} else {
Err(())
}

View file

@ -33,7 +33,10 @@ pub enum TimeUnit {
impl Time {
/// Returns a time value that represents `seconds` seconds.
pub fn from_seconds_with_calc_clamping_mode(seconds: CSSFloat, calc_clamping_mode: Option<AllowedNumericType>) -> Self {
pub fn from_seconds_with_calc_clamping_mode(
seconds: CSSFloat,
calc_clamping_mode: Option<AllowedNumericType>,
) -> Self {
Time {
seconds,
unit: TimeUnit::Second,
@ -61,7 +64,7 @@ impl Time {
pub fn unit(&self) -> &'static str {
match self.unit {
TimeUnit::Second => "s",
TimeUnit::Millisecond => "ms"
TimeUnit::Millisecond => "ms",
}
}
@ -69,7 +72,7 @@ impl Time {
fn unitless_value(&self) -> CSSFloat {
match self.unit {
TimeUnit::Second => self.seconds,
TimeUnit::Millisecond => self.seconds * 1000.
TimeUnit::Millisecond => self.seconds * 1000.,
}
}
@ -129,7 +132,8 @@ impl ToComputedValue for Time {
type ComputedValue = ComputedTime;
fn to_computed_value(&self, _context: &Context) -> Self::ComputedValue {
let seconds = self.calc_clamping_mode
let seconds = self
.calc_clamping_mode
.map_or(self.seconds(), |mode| mode.clamp(self.seconds()));
ComputedTime::from_seconds(crate::values::normalize(seconds))
@ -158,7 +162,12 @@ impl ToCss for Time {
where
W: Write,
{
crate::values::serialize_specified_dimension(self.unitless_value(), self.unit(), self.calc_clamping_mode.is_some(), dest)
crate::values::serialize_specified_dimension(
self.unitless_value(),
self.unit(),
self.calc_clamping_mode.is_some(),
dest,
)
}
}

View file

@ -434,7 +434,7 @@ where
return Err(format!(
"ToShmem failed for HashSet: We only support empty sets \
(we don't expect custom properties in UA sheets, they're observable by content)",
))
));
}
Ok(ManuallyDrop::new(Self::default()))
}
@ -519,7 +519,7 @@ impl<T: ToShmem> ToShmem for ThinVec<T> {
fn to_shmem(&self, builder: &mut SharedMemoryBuilder) -> Result<Self> {
let len = self.len();
if len == 0 {
return Ok(ManuallyDrop::new(Self::new()))
return Ok(ManuallyDrop::new(Self::new()));
}
assert_eq!(mem::size_of::<Self>(), mem::size_of::<*const ()>());
@ -541,7 +541,11 @@ impl<T: ToShmem> ToShmem for ThinVec<T> {
assert!(item_align <= header_size);
let header_padding = 0;
let layout = Layout::from_size_align(header_size + header_padding + padded_size(item_size, item_align) * len, item_align).unwrap();
let layout = Layout::from_size_align(
header_size + header_padding + padded_size(item_size, item_align) * len,
item_align,
)
.unwrap();
let shmem_header_ptr = builder.alloc::<u8>(layout);
let shmem_data_ptr = unsafe { shmem_header_ptr.add(header_size + header_padding) };