style: Run rustfmt on servo/components/style and servo/ports/geckolib

This patch is generated by running `cargo +nightly fmt` under
`servo/components/style/` and `servo/ports/geckolib` against mozilla-central
https://hg.mozilla.org/mozilla-central/rev/b193f2e7a6a5d1f042c957ea4acd5c89bf210512

My nightly version is: 1.58.0-nightly (c9c4b5d72 2021-11-17)

Manually remove the redundant braces in author_styles.rs to fix a warning.

Differential Revision: https://phabricator.services.mozilla.com/D131556
This commit is contained in:
Ting-Yu Lin 2023-06-02 02:26:03 +02:00 committed by Oriol Brufau
parent 33ad82c3da
commit a0617bff0d
50 changed files with 486 additions and 340 deletions

View file

@ -6,8 +6,8 @@
use crate::properties::PropertyDeclarationBlock; use crate::properties::PropertyDeclarationBlock;
use crate::rule_tree::{CascadeLevel, StyleSource}; use crate::rule_tree::{CascadeLevel, StyleSource};
use crate::stylesheets::layer_rule::LayerOrder;
use crate::shared_lock::Locked; use crate::shared_lock::Locked;
use crate::stylesheets::layer_rule::LayerOrder;
use servo_arc::Arc; use servo_arc::Arc;
use smallvec::SmallVec; use smallvec::SmallVec;

View file

@ -10,10 +10,10 @@ use crate::dom::TElement;
use crate::gecko_bindings::sugar::ownership::{HasBoxFFI, HasFFI, HasSimpleFFI}; use crate::gecko_bindings::sugar::ownership::{HasBoxFFI, HasFFI, HasSimpleFFI};
use crate::invalidation::media_queries::ToMediaListKey; use crate::invalidation::media_queries::ToMediaListKey;
use crate::shared_lock::SharedRwLockReadGuard; use crate::shared_lock::SharedRwLockReadGuard;
use crate::stylist::Stylist;
use crate::stylesheet_set::AuthorStylesheetSet; use crate::stylesheet_set::AuthorStylesheetSet;
use crate::stylesheets::StylesheetInDocument; use crate::stylesheets::StylesheetInDocument;
use crate::stylist::CascadeData; use crate::stylist::CascadeData;
use crate::stylist::Stylist;
use servo_arc::Arc; use servo_arc::Arc;
/// A set of author stylesheets and their computed representation, such as the /// A set of author stylesheets and their computed representation, such as the
@ -32,9 +32,7 @@ where
} }
lazy_static! { lazy_static! {
static ref EMPTY_CASCADE_DATA: Arc<CascadeData> = { static ref EMPTY_CASCADE_DATA: Arc<CascadeData> = Arc::new_leaked(CascadeData::new());
Arc::new_leaked(CascadeData::new())
};
} }
impl<S> AuthorStyles<S> impl<S> AuthorStyles<S>
@ -55,11 +53,8 @@ where
/// TODO(emilio): Need a host element and a snapshot map to do invalidation /// TODO(emilio): Need a host element and a snapshot map to do invalidation
/// properly. /// properly.
#[inline] #[inline]
pub fn flush<E>( pub fn flush<E>(&mut self, stylist: &mut Stylist, guard: &SharedRwLockReadGuard)
&mut self, where
stylist: &mut Stylist,
guard: &SharedRwLockReadGuard,
) where
E: TElement, E: TElement,
S: ToMediaListKey, S: ToMediaListKey,
{ {

View file

@ -55,12 +55,12 @@ pub fn parse_counter_style_name<'i, 't>(
} }
fn is_valid_name_definition(ident: &CustomIdent) -> bool { fn is_valid_name_definition(ident: &CustomIdent) -> bool {
ident.0 != atom!("decimal") ident.0 != atom!("decimal") &&
&& ident.0 != atom!("disc") ident.0 != atom!("disc") &&
&& ident.0 != atom!("circle") ident.0 != atom!("circle") &&
&& ident.0 != atom!("square") ident.0 != atom!("square") &&
&& ident.0 != atom!("disclosure-closed") ident.0 != atom!("disclosure-closed") &&
&& ident.0 != atom!("disclosure-open") ident.0 != atom!("disclosure-open")
} }
/// Parse the prelude of an @counter-style rule /// Parse the prelude of an @counter-style rule

View file

@ -93,7 +93,9 @@ impl CssEnvironment {
if !device.is_chrome_document() { if !device.is_chrome_document() {
return None; return None;
} }
let var = CHROME_ENVIRONMENT_VARIABLES.iter().find(|var| var.name == *name)?; let var = CHROME_ENVIRONMENT_VARIABLES
.iter()
.find(|var| var.name == *name)?;
Some((var.evaluator)(device)) Some((var.evaluator)(device))
} }
} }
@ -682,10 +684,7 @@ impl<'a> CustomPropertiesBuilder<'a> {
/// (meaning we should use the inherited value). /// (meaning we should use the inherited value).
/// ///
/// It does cycle dependencies removal at the same time as substitution. /// It does cycle dependencies removal at the same time as substitution.
fn substitute_all( fn substitute_all(custom_properties_map: &mut CustomPropertiesMap, device: &Device) {
custom_properties_map: &mut CustomPropertiesMap,
device: &Device,
) {
// The cycle dependencies removal in this function is a variant // The cycle dependencies removal in this function is a variant
// of Tarjan's algorithm. It is mostly based on the pseudo-code // of Tarjan's algorithm. It is mostly based on the pseudo-code
// listed in // listed in
@ -999,7 +998,9 @@ fn substitute_block<'i>(
let first_token_type = input let first_token_type = input
.next_including_whitespace_and_comments() .next_including_whitespace_and_comments()
.ok() .ok()
.map_or_else(TokenSerializationType::nothing, |t| t.serialization_type()); .map_or_else(TokenSerializationType::nothing, |t| {
t.serialization_type()
});
input.reset(&after_comma); input.reset(&after_comma);
let mut position = (after_comma.position(), first_token_type); let mut position = (after_comma.position(), first_token_type);
last_token_type = substitute_block( last_token_type = substitute_block(

View file

@ -179,13 +179,20 @@ impl ElementStyles {
pub fn uses_viewport_units(&self) -> bool { pub fn uses_viewport_units(&self) -> bool {
use crate::computed_value_flags::ComputedValueFlags; use crate::computed_value_flags::ComputedValueFlags;
if self.primary().flags.intersects(ComputedValueFlags::USES_VIEWPORT_UNITS) { if self
.primary()
.flags
.intersects(ComputedValueFlags::USES_VIEWPORT_UNITS)
{
return true; return true;
} }
for pseudo_style in self.pseudos.as_array() { for pseudo_style in self.pseudos.as_array() {
if let Some(ref pseudo_style) = pseudo_style { if let Some(ref pseudo_style) = pseudo_style {
if pseudo_style.flags.intersects(ComputedValueFlags::USES_VIEWPORT_UNITS) { if pseudo_style
.flags
.intersects(ComputedValueFlags::USES_VIEWPORT_UNITS)
{
return true; return true;
} }
} }

View file

@ -214,7 +214,7 @@ impl<'a> fmt::Display for ContextualParseError<'a> {
ContextualParseError::UnsupportedValue(_value, ref err) => parse_error_to_str(err, f), ContextualParseError::UnsupportedValue(_value, ref err) => parse_error_to_str(err, f),
ContextualParseError::NeverMatchingHostSelector(ref selector) => { ContextualParseError::NeverMatchingHostSelector(ref selector) => {
write!(f, ":host selector is not featureless: {}", selector) write!(f, ":host selector is not featureless: {}", selector)
} },
} }
} }
} }

View file

@ -556,7 +556,8 @@ fn eval_moz_windows_non_native_menus(
query_value: Option<bool>, query_value: Option<bool>,
_: Option<RangeOrOperator>, _: Option<RangeOrOperator>,
) -> bool { ) -> bool {
let use_non_native_menus = match static_prefs::pref!("browser.display.windows.non_native_menus") { let use_non_native_menus = match static_prefs::pref!("browser.display.windows.non_native_menus")
{
0 => false, 0 => false,
1 => true, 1 => true,
_ => { _ => {
@ -873,18 +874,39 @@ pub static MEDIA_FEATURES: [MediaFeatureDescription; 58] = [
Evaluator::BoolInteger(eval_moz_overlay_scrollbars), Evaluator::BoolInteger(eval_moz_overlay_scrollbars),
ParsingRequirements::CHROME_AND_UA_ONLY, ParsingRequirements::CHROME_AND_UA_ONLY,
), ),
lnf_int_feature!(
lnf_int_feature!(atom!("-moz-scrollbar-start-backward"), ScrollArrowStyle, get_scrollbar_start_backward), atom!("-moz-scrollbar-start-backward"),
lnf_int_feature!(atom!("-moz-scrollbar-start-forward"), ScrollArrowStyle, get_scrollbar_start_forward), ScrollArrowStyle,
lnf_int_feature!(atom!("-moz-scrollbar-end-backward"), ScrollArrowStyle, get_scrollbar_end_backward), get_scrollbar_start_backward
lnf_int_feature!(atom!("-moz-scrollbar-end-forward"), ScrollArrowStyle, get_scrollbar_end_forward), ),
lnf_int_feature!(atom!("-moz-scrollbar-thumb-proportional"), ScrollSliderStyle), lnf_int_feature!(
atom!("-moz-scrollbar-start-forward"),
ScrollArrowStyle,
get_scrollbar_start_forward
),
lnf_int_feature!(
atom!("-moz-scrollbar-end-backward"),
ScrollArrowStyle,
get_scrollbar_end_backward
),
lnf_int_feature!(
atom!("-moz-scrollbar-end-forward"),
ScrollArrowStyle,
get_scrollbar_end_forward
),
lnf_int_feature!(
atom!("-moz-scrollbar-thumb-proportional"),
ScrollSliderStyle
),
lnf_int_feature!(atom!("-moz-menubar-drag"), MenuBarDrag), lnf_int_feature!(atom!("-moz-menubar-drag"), MenuBarDrag),
lnf_int_feature!(atom!("-moz-windows-default-theme"), WindowsDefaultTheme), lnf_int_feature!(atom!("-moz-windows-default-theme"), WindowsDefaultTheme),
lnf_int_feature!(atom!("-moz-mac-graphite-theme"), MacGraphiteTheme), lnf_int_feature!(atom!("-moz-mac-graphite-theme"), MacGraphiteTheme),
lnf_int_feature!(atom!("-moz-mac-big-sur-theme"), MacBigSurTheme), lnf_int_feature!(atom!("-moz-mac-big-sur-theme"), MacBigSurTheme),
lnf_int_feature!(atom!("-moz-mac-rtl"), MacRTL), lnf_int_feature!(atom!("-moz-mac-rtl"), MacRTL),
lnf_int_feature!(atom!("-moz-windows-accent-color-in-titlebar"), WindowsAccentColorInTitlebar), lnf_int_feature!(
atom!("-moz-windows-accent-color-in-titlebar"),
WindowsAccentColorInTitlebar
),
lnf_int_feature!(atom!("-moz-windows-compositor"), DWMCompositor), lnf_int_feature!(atom!("-moz-windows-compositor"), DWMCompositor),
lnf_int_feature!(atom!("-moz-windows-classic"), WindowsClassic), lnf_int_feature!(atom!("-moz-windows-classic"), WindowsClassic),
lnf_int_feature!(atom!("-moz-windows-glass"), WindowsGlass), lnf_int_feature!(atom!("-moz-windows-glass"), WindowsGlass),
@ -893,8 +915,14 @@ pub static MEDIA_FEATURES: [MediaFeatureDescription; 58] = [
lnf_int_feature!(atom!("-moz-gtk-csd-minimize-button"), GTKCSDMinimizeButton), lnf_int_feature!(atom!("-moz-gtk-csd-minimize-button"), GTKCSDMinimizeButton),
lnf_int_feature!(atom!("-moz-gtk-csd-maximize-button"), GTKCSDMaximizeButton), lnf_int_feature!(atom!("-moz-gtk-csd-maximize-button"), GTKCSDMaximizeButton),
lnf_int_feature!(atom!("-moz-gtk-csd-close-button"), GTKCSDCloseButton), lnf_int_feature!(atom!("-moz-gtk-csd-close-button"), GTKCSDCloseButton),
lnf_int_feature!(atom!("-moz-gtk-csd-reversed-placement"), GTKCSDReversedPlacement), lnf_int_feature!(
atom!("-moz-gtk-csd-reversed-placement"),
GTKCSDReversedPlacement
),
lnf_int_feature!(atom!("-moz-system-dark-theme"), SystemUsesDarkTheme), lnf_int_feature!(atom!("-moz-system-dark-theme"), SystemUsesDarkTheme),
bool_pref_feature!(atom!("-moz-proton"), "browser.proton.enabled"), bool_pref_feature!(atom!("-moz-proton"), "browser.proton.enabled"),
bool_pref_feature!(atom!("-moz-proton-places-tooltip"), "browser.proton.places-tooltip.enabled"), bool_pref_feature!(
atom!("-moz-proton-places-tooltip"),
"browser.proton.places-tooltip.enabled"
),
]; ];

View file

@ -14,7 +14,7 @@ use crate::media_queries::MediaType;
use crate::properties::ComputedValues; use crate::properties::ComputedValues;
use crate::string_cache::Atom; use crate::string_cache::Atom;
use crate::values::computed::font::GenericFontFamily; use crate::values::computed::font::GenericFontFamily;
use crate::values::computed::{Length, ColorScheme}; use crate::values::computed::{ColorScheme, Length};
use crate::values::specified::color::SystemColor; use crate::values::specified::color::SystemColor;
use crate::values::specified::font::FONT_MEDIUM_PX; use crate::values::specified::font::FONT_MEDIUM_PX;
use crate::values::{CustomIdent, KeyframesName}; use crate::values::{CustomIdent, KeyframesName};
@ -389,10 +389,12 @@ impl Device {
} }
/// Computes a system color and returns it as an nscolor. /// Computes a system color and returns it as an nscolor.
pub(crate) fn system_nscolor(&self, system_color: SystemColor, color_scheme: &ColorScheme) -> u32 { pub(crate) fn system_nscolor(
unsafe { &self,
bindings::Gecko_ComputeSystemColor(system_color, self.document(), color_scheme) system_color: SystemColor,
} color_scheme: &ColorScheme,
) -> u32 {
unsafe { bindings::Gecko_ComputeSystemColor(system_color, self.document(), color_scheme) }
} }
/// Returns the default background color. /// Returns the default background color.
@ -460,14 +462,16 @@ impl Device {
/// Returns the gtk titlebar radius in CSS pixels. /// Returns the gtk titlebar radius in CSS pixels.
pub fn titlebar_radius(&self) -> f32 { pub fn titlebar_radius(&self) -> f32 {
unsafe { unsafe {
bindings::Gecko_GetLookAndFeelInt(bindings::LookAndFeel_IntID::TitlebarRadius as i32) as f32 bindings::Gecko_GetLookAndFeelInt(bindings::LookAndFeel_IntID::TitlebarRadius as i32)
as f32
} }
} }
/// Returns the gtk menu radius in CSS pixels. /// Returns the gtk menu radius in CSS pixels.
pub fn menu_radius(&self) -> f32 { pub fn menu_radius(&self) -> f32 {
unsafe { unsafe {
bindings::Gecko_GetLookAndFeelInt(bindings::LookAndFeel_IntID::GtkMenuRadius as i32) as f32 bindings::Gecko_GetLookAndFeelInt(bindings::LookAndFeel_IntID::GtkMenuRadius as i32)
as f32
} }
} }

View file

@ -139,7 +139,10 @@ impl NonTSPseudoClass {
/// Returns whether the pseudo-class is enabled in content sheets. /// Returns whether the pseudo-class is enabled in content sheets.
#[inline] #[inline]
fn is_enabled_in_content(&self) -> bool { fn is_enabled_in_content(&self) -> bool {
if matches!(*self, Self::MozLWTheme | Self::MozLWThemeBrightText | Self::MozLWThemeDarkText) { if matches!(
*self,
Self::MozLWTheme | Self::MozLWThemeBrightText | Self::MozLWThemeDarkText
) {
return static_prefs::pref!("layout.css.moz-lwtheme.content.enabled"); return static_prefs::pref!("layout.css.moz-lwtheme.content.enabled");
} }
if let NonTSPseudoClass::MozLocaleDir(..) = *self { if let NonTSPseudoClass::MozLocaleDir(..) = *self {
@ -174,12 +177,10 @@ impl NonTSPseudoClass {
/// Get the document state flag associated with a pseudo-class, if any. /// Get the document state flag associated with a pseudo-class, if any.
pub fn document_state_flag(&self) -> DocumentState { pub fn document_state_flag(&self) -> DocumentState {
match *self { match *self {
NonTSPseudoClass::MozLocaleDir(ref dir) => { NonTSPseudoClass::MozLocaleDir(ref dir) => match dir.as_horizontal_direction() {
match dir.as_horizontal_direction() { Some(HorizontalDirection::Ltr) => DocumentState::LTR_LOCALE,
Some(HorizontalDirection::Ltr) => DocumentState::LTR_LOCALE, Some(HorizontalDirection::Rtl) => DocumentState::RTL_LOCALE,
Some(HorizontalDirection::Rtl) => DocumentState::RTL_LOCALE, None => DocumentState::empty(),
None => DocumentState::empty(),
}
}, },
NonTSPseudoClass::MozWindowInactive => DocumentState::WINDOW_INACTIVE, NonTSPseudoClass::MozWindowInactive => DocumentState::WINDOW_INACTIVE,
NonTSPseudoClass::MozLWTheme => DocumentState::LWTHEME, NonTSPseudoClass::MozLWTheme => DocumentState::LWTHEME,

View file

@ -27,6 +27,7 @@ use crate::gecko_bindings::bindings;
use crate::gecko_bindings::bindings::Gecko_ElementHasAnimations; use crate::gecko_bindings::bindings::Gecko_ElementHasAnimations;
use crate::gecko_bindings::bindings::Gecko_ElementHasCSSAnimations; use crate::gecko_bindings::bindings::Gecko_ElementHasCSSAnimations;
use crate::gecko_bindings::bindings::Gecko_ElementHasCSSTransitions; use crate::gecko_bindings::bindings::Gecko_ElementHasCSSTransitions;
use crate::gecko_bindings::bindings::Gecko_ElementState;
use crate::gecko_bindings::bindings::Gecko_GetActiveLinkAttrDeclarationBlock; use crate::gecko_bindings::bindings::Gecko_GetActiveLinkAttrDeclarationBlock;
use crate::gecko_bindings::bindings::Gecko_GetAnimationEffectCount; use crate::gecko_bindings::bindings::Gecko_GetAnimationEffectCount;
use crate::gecko_bindings::bindings::Gecko_GetAnimationRule; use crate::gecko_bindings::bindings::Gecko_GetAnimationRule;
@ -39,7 +40,6 @@ use crate::gecko_bindings::bindings::Gecko_IsSignificantChild;
use crate::gecko_bindings::bindings::Gecko_MatchLang; use crate::gecko_bindings::bindings::Gecko_MatchLang;
use crate::gecko_bindings::bindings::Gecko_UnsetDirtyStyleAttr; use crate::gecko_bindings::bindings::Gecko_UnsetDirtyStyleAttr;
use crate::gecko_bindings::bindings::Gecko_UpdateAnimations; use crate::gecko_bindings::bindings::Gecko_UpdateAnimations;
use crate::gecko_bindings::bindings::Gecko_ElementState;
use crate::gecko_bindings::bindings::{Gecko_SetNodeFlags, Gecko_UnsetNodeFlags}; use crate::gecko_bindings::bindings::{Gecko_SetNodeFlags, Gecko_UnsetNodeFlags};
use crate::gecko_bindings::structs; use crate::gecko_bindings::structs;
use crate::gecko_bindings::structs::nsChangeHint; use crate::gecko_bindings::structs::nsChangeHint;
@ -1196,7 +1196,11 @@ impl<'le> TElement for GeckoElement<'le> {
where where
F: FnMut(&AtomIdent), F: FnMut(&AtomIdent),
{ {
for attr in self.non_mapped_attrs().iter().chain(self.mapped_attrs().iter()) { for attr in self
.non_mapped_attrs()
.iter()
.chain(self.mapped_attrs().iter())
{
let is_nodeinfo = attr.mName.mBits & 1 != 0; let is_nodeinfo = attr.mName.mBits & 1 != 0;
unsafe { unsafe {
let atom = if is_nodeinfo { let atom = if is_nodeinfo {
@ -1972,9 +1976,7 @@ impl<'le> ::selectors::Element for GeckoElement<'le> {
NonTSPseudoClass::Active | NonTSPseudoClass::Active |
NonTSPseudoClass::Hover | NonTSPseudoClass::Hover |
NonTSPseudoClass::MozAutofillPreview | NonTSPseudoClass::MozAutofillPreview |
NonTSPseudoClass::Dir(..) => { NonTSPseudoClass::Dir(..) => self.state().intersects(pseudo_class.state_flag()),
self.state().intersects(pseudo_class.state_flag())
},
NonTSPseudoClass::AnyLink => self.is_link(), NonTSPseudoClass::AnyLink => self.is_link(),
NonTSPseudoClass::Link => { NonTSPseudoClass::Link => {
self.is_link() && context.visited_handling().matches_unvisited() self.is_link() && context.visited_handling().matches_unvisited()
@ -2033,7 +2035,10 @@ impl<'le> ::selectors::Element for GeckoElement<'le> {
NonTSPseudoClass::MozWindowInactive => { NonTSPseudoClass::MozWindowInactive => {
let state_bit = pseudo_class.document_state_flag(); let state_bit = pseudo_class.document_state_flag();
if state_bit.is_empty() { if state_bit.is_empty() {
debug_assert!(matches!(pseudo_class, NonTSPseudoClass::MozLocaleDir(..)), "Only moz-locale-dir should ever return an empty state"); debug_assert!(
matches!(pseudo_class, NonTSPseudoClass::MozLocaleDir(..)),
"Only moz-locale-dir should ever return an empty state"
);
return false; return false;
} }
if context.extra_data.document_state.intersects(state_bit) { if context.extra_data.document_state.intersects(state_bit) {

View file

@ -211,13 +211,15 @@ fn consume_operation_or_colon(input: &mut Parser) -> Result<Option<Operator>, ()
// //
// TODO(emilio): Maybe we should ignore comments as well? // TODO(emilio): Maybe we should ignore comments as well?
// https://github.com/w3c/csswg-drafts/issues/6248 // https://github.com/w3c/csswg-drafts/issues/6248
let parsed_equal = input.try_parse(|i| { let parsed_equal = input
let t = i.next_including_whitespace().map_err(|_| ())?; .try_parse(|i| {
if !matches!(t, Token::Delim('=')) { let t = i.next_including_whitespace().map_err(|_| ())?;
return Err(()) if !matches!(t, Token::Delim('=')) {
} return Err(());
Ok(()) }
}).is_ok(); Ok(())
})
.is_ok();
if !parsed_equal { if !parsed_equal {
return Ok(Some(operator)); return Ok(Some(operator));

View file

@ -147,8 +147,9 @@ where
self.context.current_host = host.map(|e| e.opaque()); self.context.current_host = host.map(|e| e.opaque());
f(self); f(self);
if start != self.rules.len() { if start != self.rules.len() {
self.rules[start..] self.rules[start..].sort_unstable_by_key(|block| {
.sort_unstable_by_key(|block| (block.layer_order, block.specificity, block.source_order())); (block.layer_order, block.specificity, block.source_order())
});
} }
self.context.current_host = old_host; self.context.current_host = old_host;
self.in_sort_scope = false; self.in_sort_scope = false;
@ -214,7 +215,12 @@ where
} }
#[inline] #[inline]
fn collect_rules_in_list(&mut self, part_rules: &[Rule], cascade_level: CascadeLevel, cascade_data: &CascadeData) { fn collect_rules_in_list(
&mut self,
part_rules: &[Rule],
cascade_level: CascadeLevel,
cascade_data: &CascadeData,
) {
debug_assert!(self.in_sort_scope, "Rules gotta be sorted"); debug_assert!(self.in_sort_scope, "Rules gotta be sorted");
SelectorMap::get_matching_rules( SelectorMap::get_matching_rules(
self.element, self.element,
@ -228,7 +234,12 @@ where
} }
#[inline] #[inline]
fn collect_rules_in_map(&mut self, map: &SelectorMap<Rule>, cascade_level: CascadeLevel, cascade_data: &CascadeData) { fn collect_rules_in_map(
&mut self,
map: &SelectorMap<Rule>,
cascade_level: CascadeLevel,
cascade_data: &CascadeData,
) {
debug_assert!(self.in_sort_scope, "Rules gotta be sorted"); debug_assert!(self.in_sort_scope, "Rules gotta be sorted");
map.get_all_matching_rules( map.get_all_matching_rules(
self.element, self.element,
@ -390,10 +401,10 @@ where
let outer_shadow = inner_shadow_host.containing_shadow(); let outer_shadow = inner_shadow_host.containing_shadow();
let cascade_data = match outer_shadow { let cascade_data = match outer_shadow {
Some(shadow) => shadow.style_data(), Some(shadow) => shadow.style_data(),
None => Some(self None => Some(
.stylist self.stylist
.cascade_data() .cascade_data()
.borrow_for_origin(Origin::Author) .borrow_for_origin(Origin::Author),
), ),
}; };
@ -406,7 +417,11 @@ where
self.in_tree(containing_host, |collector| { self.in_tree(containing_host, |collector| {
for p in &parts { for p in &parts {
if let Some(part_rules) = part_rules.get(&p.0) { if let Some(part_rules) = part_rules.get(&p.0) {
collector.collect_rules_in_list(part_rules, cascade_level, cascade_data); collector.collect_rules_in_list(
part_rules,
cascade_level,
cascade_data,
);
} }
} }
}); });

View file

@ -12,7 +12,7 @@ use crate::hash::map as hash_map;
use crate::hash::{HashMap, HashSet}; use crate::hash::{HashMap, HashSet};
use crate::rule_tree::CascadeLevel; use crate::rule_tree::CascadeLevel;
use crate::selector_parser::SelectorImpl; use crate::selector_parser::SelectorImpl;
use crate::stylist::{Rule, CascadeData}; use crate::stylist::{CascadeData, Rule};
use crate::{Atom, LocalName, Namespace, WeakAtom}; use crate::{Atom, LocalName, Namespace, WeakAtom};
use fallible::FallibleVec; use fallible::FallibleVec;
use hashglobe::FailedAllocationError; use hashglobe::FailedAllocationError;
@ -313,7 +313,8 @@ impl SelectorMap<Rule> {
context, context,
flags_setter, flags_setter,
) { ) {
matching_rules.push(rule.to_applicable_declaration_block(cascade_level, cascade_data)); matching_rules
.push(rule.to_applicable_declaration_block(cascade_level, cascade_data));
} }
} }
} }
@ -366,14 +367,11 @@ impl<T: SelectorMapEntry> SelectorMap<T> {
&mut self.local_name_hash &mut self.local_name_hash
}; };
if name != lower_name { if name != lower_name {
hash hash.try_entry(lower_name.clone())?
.try_entry(lower_name.clone())?
.or_insert_with(SmallVec::new) .or_insert_with(SmallVec::new)
.try_push($entry.clone())?; .try_push($entry.clone())?;
} }
hash hash.try_entry(name.clone())?.or_insert_with(SmallVec::new)
.try_entry(name.clone())?
.or_insert_with(SmallVec::new)
}, },
Bucket::Namespace(url) => self Bucket::Namespace(url) => self
.namespace_hash .namespace_hash
@ -387,7 +385,11 @@ impl<T: SelectorMapEntry> SelectorMap<T> {
let bucket = { let bucket = {
let mut disjoint_buckets = SmallVec::new(); let mut disjoint_buckets = SmallVec::new();
let bucket = find_bucket(entry.selector(), &mut disjoint_buckets, self.bucket_attributes); let bucket = find_bucket(
entry.selector(),
&mut disjoint_buckets,
self.bucket_attributes,
);
// See if inserting this selector in multiple entries in the // See if inserting this selector in multiple entries in the
// selector map would be worth it. Consider a case like: // selector map would be worth it. Consider a case like:
@ -619,11 +621,16 @@ fn specific_bucket_for<'a>(
Component::Root => Bucket::Root, Component::Root => Bucket::Root,
Component::ID(ref id) => Bucket::ID(id), Component::ID(ref id) => Bucket::ID(id),
Component::Class(ref class) => Bucket::Class(class), Component::Class(ref class) => Bucket::Class(class),
Component::AttributeInNoNamespace { ref local_name, .. } if bucket_attributes => Bucket::Attribute { Component::AttributeInNoNamespace { ref local_name, .. } if bucket_attributes => {
name: local_name, Bucket::Attribute {
lower_name: local_name, name: local_name,
lower_name: local_name,
}
}, },
Component::AttributeInNoNamespaceExists { ref local_name, ref local_name_lower } if bucket_attributes => Bucket::Attribute { Component::AttributeInNoNamespaceExists {
ref local_name,
ref local_name_lower,
} if bucket_attributes => Bucket::Attribute {
name: local_name, name: local_name,
lower_name: local_name_lower, lower_name: local_name_lower,
}, },
@ -656,8 +663,12 @@ fn specific_bucket_for<'a>(
// //
// So inserting `span` in the rule hash makes sense since we want to // So inserting `span` in the rule hash makes sense since we want to
// match the slotted <span>. // match the slotted <span>.
Component::Slotted(ref selector) => find_bucket(selector.iter(), disjoint_buckets, bucket_attributes), Component::Slotted(ref selector) => {
Component::Host(Some(ref selector)) => find_bucket(selector.iter(), disjoint_buckets, bucket_attributes), find_bucket(selector.iter(), disjoint_buckets, bucket_attributes)
},
Component::Host(Some(ref selector)) => {
find_bucket(selector.iter(), disjoint_buckets, bucket_attributes)
},
Component::Is(ref list) | Component::Where(ref list) => { Component::Is(ref list) | Component::Where(ref list) => {
if list.len() == 1 { if list.len() == 1 {
find_bucket(list[0].iter(), disjoint_buckets, bucket_attributes) find_bucket(list[0].iter(), disjoint_buckets, bucket_attributes)

View file

@ -76,8 +76,7 @@ impl<'a> SelectorParser<'a> {
/// Whether we're parsing selectors in a stylesheet that has chrome /// Whether we're parsing selectors in a stylesheet that has chrome
/// privilege. /// privilege.
pub fn chrome_rules_enabled(&self) -> bool { pub fn chrome_rules_enabled(&self) -> bool {
self.url_data.chrome_rules_enabled() || self.url_data.chrome_rules_enabled() || self.stylesheet_origin == Origin::User
self.stylesheet_origin == Origin::User
} }
} }

View file

@ -97,7 +97,10 @@ impl SharedRwLock {
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
#[inline] #[inline]
fn ptr(&self) -> *const SomethingZeroSizedButTyped { fn ptr(&self) -> *const SomethingZeroSizedButTyped {
self.cell.as_ref().map(|cell| cell.as_ptr() as *const _).unwrap_or(ptr::null()) self.cell
.as_ref()
.map(|cell| cell.as_ptr() as *const _)
.unwrap_or(ptr::null())
} }
/// Wrap the given data to make its access protected by this lock. /// Wrap the given data to make its access protected by this lock.
@ -154,7 +157,10 @@ impl<'a> SharedRwLockReadGuard<'a> {
#[inline] #[inline]
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
fn ptr(&self) -> *const SomethingZeroSizedButTyped { fn ptr(&self) -> *const SomethingZeroSizedButTyped {
self.0.as_ref().map(|r| &**r as *const _).unwrap_or(ptr::null()) self.0
.as_ref()
.map(|r| &**r as *const _)
.unwrap_or(ptr::null())
} }
} }

View file

@ -760,9 +760,9 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
/// the same font as its fallback ('list-style-type') in case it fails to load. /// the same font as its fallback ('list-style-type') in case it fails to load.
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
fn adjust_for_marker_pseudo(&mut self) { fn adjust_for_marker_pseudo(&mut self) {
use crate::values::computed::counters::Content;
use crate::values::computed::font::{FontFamily, FontSynthesis}; use crate::values::computed::font::{FontFamily, FontSynthesis};
use crate::values::computed::text::{LetterSpacing, WordSpacing}; use crate::values::computed::text::{LetterSpacing, WordSpacing};
use crate::values::computed::counters::{Content};
let is_legacy_marker = self.style.pseudo.map_or(false, |p| p.is_marker()) && let is_legacy_marker = self.style.pseudo.map_or(false, |p| p.is_marker()) &&
self.style.get_list().clone_list_style_type().is_bullet() && self.style.get_list().clone_list_style_type().is_bullet() &&
@ -770,21 +770,49 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
if !is_legacy_marker { if !is_legacy_marker {
return; return;
} }
if !self.style.flags.get().contains(ComputedValueFlags::HAS_AUTHOR_SPECIFIED_FONT_FAMILY) { if !self
self.style.mutate_font().set_font_family(FontFamily::moz_bullet().clone()); .style
.flags
.get()
.contains(ComputedValueFlags::HAS_AUTHOR_SPECIFIED_FONT_FAMILY)
{
self.style
.mutate_font()
.set_font_family(FontFamily::moz_bullet().clone());
// FIXME(mats): We can remove this if support for font-synthesis is added to @font-face rules. // FIXME(mats): We can remove this if support for font-synthesis is added to @font-face rules.
// Then we can add it to the @font-face rule in html.css instead. // Then we can add it to the @font-face rule in html.css instead.
// https://github.com/w3c/csswg-drafts/issues/6081 // https://github.com/w3c/csswg-drafts/issues/6081
if !self.style.flags.get().contains(ComputedValueFlags::HAS_AUTHOR_SPECIFIED_FONT_SYNTHESIS) { if !self
self.style.mutate_font().set_font_synthesis(FontSynthesis::none()); .style
.flags
.get()
.contains(ComputedValueFlags::HAS_AUTHOR_SPECIFIED_FONT_SYNTHESIS)
{
self.style
.mutate_font()
.set_font_synthesis(FontSynthesis::none());
} }
} }
if !self.style.flags.get().contains(ComputedValueFlags::HAS_AUTHOR_SPECIFIED_LETTER_SPACING) { if !self
self.style.mutate_inherited_text().set_letter_spacing(LetterSpacing::normal()); .style
.flags
.get()
.contains(ComputedValueFlags::HAS_AUTHOR_SPECIFIED_LETTER_SPACING)
{
self.style
.mutate_inherited_text()
.set_letter_spacing(LetterSpacing::normal());
} }
if !self.style.flags.get().contains(ComputedValueFlags::HAS_AUTHOR_SPECIFIED_WORD_SPACING) { if !self
self.style.mutate_inherited_text().set_word_spacing(WordSpacing::normal()); .style
.flags
.get()
.contains(ComputedValueFlags::HAS_AUTHOR_SPECIFIED_WORD_SPACING)
{
self.style
.mutate_inherited_text()
.set_word_spacing(WordSpacing::normal());
} }
} }

View file

@ -10,8 +10,8 @@ use crate::media_queries::MediaList;
use crate::shared_lock::{DeepCloneParams, DeepCloneWithLock}; use crate::shared_lock::{DeepCloneParams, DeepCloneWithLock};
use crate::shared_lock::{SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard}; use crate::shared_lock::{SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard};
use crate::str::CssStringWriter; use crate::str::CssStringWriter;
use crate::stylesheets::{CssRule, StylesheetInDocument};
use crate::stylesheets::layer_rule::LayerName; use crate::stylesheets::layer_rule::LayerName;
use crate::stylesheets::{CssRule, StylesheetInDocument};
use crate::values::CssUrl; use crate::values::CssUrl;
use cssparser::SourceLocation; use cssparser::SourceLocation;
use std::fmt::{self, Write}; use std::fmt::{self, Write};
@ -131,7 +131,6 @@ pub struct ImportLayer {
pub name: Option<LayerName>, pub name: Option<LayerName>,
} }
impl ToCss for ImportLayer { impl ToCss for ImportLayer {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where where

View file

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

View file

@ -509,11 +509,11 @@ impl DeepCloneWithLock for CssRule {
CssRule::Layer(Arc::new( CssRule::Layer(Arc::new(
lock.wrap(rule.deep_clone_with_lock(lock, guard, params)), lock.wrap(rule.deep_clone_with_lock(lock, guard, params)),
)) ))
} },
CssRule::ScrollTimeline(ref arc) => { CssRule::ScrollTimeline(ref arc) => {
let rule = arc.read_with(guard); let rule = arc.read_with(guard);
CssRule::ScrollTimeline(Arc::new(lock.wrap(rule.clone()))) CssRule::ScrollTimeline(Arc::new(lock.wrap(rule.clone())))
} },
} }
} }
} }

View file

@ -289,7 +289,7 @@ impl<'a, 'i> AtRuleParser<'i> for TopLevelRuleParser<'a> {
&mut self, &mut self,
prelude: AtRulePrelude, prelude: AtRulePrelude,
start: &ParserState, start: &ParserState,
) -> Result<Self::AtRule, ()> { ) -> Result<Self::AtRule, ()> {
let rule = match prelude { let rule = match prelude {
AtRulePrelude::Import(url, media, layer) => { AtRulePrelude::Import(url, media, layer) => {
let loader = self let loader = self
@ -613,15 +613,13 @@ impl<'a, 'b, 'i> AtRuleParser<'i> for NestedRuleParser<'a, 'b> {
0 | 1 => names.into_iter().next(), 0 | 1 => names.into_iter().next(),
_ => return Err(input.new_error(BasicParseErrorKind::AtRuleBodyInvalid)), _ => return Err(input.new_error(BasicParseErrorKind::AtRuleBodyInvalid)),
}; };
Ok(CssRule::Layer(Arc::new(self.shared_lock.wrap( Ok(CssRule::Layer(Arc::new(self.shared_lock.wrap(LayerRule {
LayerRule { kind: LayerRuleKind::Block {
kind: LayerRuleKind::Block { name,
name, rules: self.parse_nested_rules(input, CssRuleType::Layer),
rules: self.parse_nested_rules(input, CssRuleType::Layer),
},
source_location: start.source_location(),
}, },
)))) source_location: start.source_location(),
}))))
}, },
AtRulePrelude::Import(..) | AtRulePrelude::Namespace(..) => { AtRulePrelude::Import(..) | AtRulePrelude::Namespace(..) => {
// These rules don't have blocks. // These rules don't have blocks.
@ -650,7 +648,7 @@ impl<'a, 'b, 'i> AtRuleParser<'i> for NestedRuleParser<'a, 'b> {
&mut self, &mut self,
prelude: AtRulePrelude, prelude: AtRulePrelude,
start: &ParserState, start: &ParserState,
) -> Result<Self::AtRule, ()> { ) -> Result<Self::AtRule, ()> {
Ok(match prelude { Ok(match prelude {
AtRulePrelude::Layer(names) => { AtRulePrelude::Layer(names) => {
if names.is_empty() { if names.is_empty() {
@ -687,7 +685,10 @@ fn check_for_useless_selector(
} }
if found_host && found_non_host { if found_host && found_non_host {
let location = input.current_source_location(); let location = input.current_source_location();
context.log_css_error(location, ContextualParseError::NeverMatchingHostSelector(selector.to_css_string())); context.log_css_error(
location,
ContextualParseError::NeverMatchingHostSelector(selector.to_css_string()),
);
continue 'selector_loop; continue 'selector_loop;
} }
} }

View file

@ -111,7 +111,7 @@ where
LayerRuleKind::Block { ref rules, .. } => Some(rules.read_with(guard).0.iter()), LayerRuleKind::Block { ref rules, .. } => Some(rules.read_with(guard).0.iter()),
LayerRuleKind::Statement { .. } => None, LayerRuleKind::Statement { .. } => None,
} }
} },
} }
} }
} }
@ -323,7 +323,8 @@ impl<'a, 'b> EffectiveRulesIterator<'a, 'b> {
guard: &'a SharedRwLockReadGuard<'b>, guard: &'a SharedRwLockReadGuard<'b>,
rule: &'a CssRule, rule: &'a CssRule,
) -> Self { ) -> Self {
let children = RulesIterator::<AllRules>::children(rule, device, quirks_mode, guard, &mut false); let children =
RulesIterator::<AllRules>::children(rule, device, quirks_mode, guard, &mut false);
EffectiveRulesIterator::new(device, quirks_mode, guard, children.unwrap_or([].iter())) EffectiveRulesIterator::new(device, quirks_mode, guard, children.unwrap_or([].iter()))
} }
} }

View file

@ -591,9 +591,11 @@ impl Clone for Stylesheet {
// Make a deep clone of the media, using the new lock. // Make a deep clone of the media, using the new lock.
let media = self.media.read_with(&guard).clone(); let media = self.media.read_with(&guard).clone();
let media = Arc::new(lock.wrap(media)); let media = Arc::new(lock.wrap(media));
let contents = Arc::new(self let contents = Arc::new(self.contents.deep_clone_with_lock(
.contents &lock,
.deep_clone_with_lock(&lock, &guard, &DeepCloneParams)); &guard,
&DeepCloneParams,
));
Stylesheet { Stylesheet {
contents, contents,

View file

@ -11,7 +11,9 @@ use crate::element_state::{DocumentState, ElementState};
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
use crate::gecko_bindings::structs::{ServoStyleSetSizes, StyleRuleInclusion}; use crate::gecko_bindings::structs::{ServoStyleSetSizes, StyleRuleInclusion};
use crate::invalidation::element::invalidation_map::InvalidationMap; use crate::invalidation::element::invalidation_map::InvalidationMap;
use crate::invalidation::media_queries::{EffectiveMediaQueryResults, MediaListKey, ToMediaListKey}; use crate::invalidation::media_queries::{
EffectiveMediaQueryResults, MediaListKey, ToMediaListKey,
};
use crate::invalidation::stylesheets::RuleChangeKind; use crate::invalidation::stylesheets::RuleChangeKind;
use crate::media_queries::Device; use crate::media_queries::Device;
use crate::properties::{self, CascadeMode, ComputedValues}; use crate::properties::{self, CascadeMode, ComputedValues};
@ -25,15 +27,18 @@ use crate::shared_lock::{Locked, SharedRwLockReadGuard, StylesheetGuards};
use crate::stylesheet_set::{DataValidity, DocumentStylesheetSet, SheetRebuildKind}; use crate::stylesheet_set::{DataValidity, DocumentStylesheetSet, SheetRebuildKind};
use crate::stylesheet_set::{DocumentStylesheetFlusher, SheetCollectionFlusher}; use crate::stylesheet_set::{DocumentStylesheetFlusher, SheetCollectionFlusher};
use crate::stylesheets::keyframes_rule::KeyframesAnimation; use crate::stylesheets::keyframes_rule::KeyframesAnimation;
use crate::stylesheets::layer_rule::{LayerName, LayerId, LayerOrder}; use crate::stylesheets::layer_rule::{LayerId, LayerName, LayerOrder};
use crate::stylesheets::viewport_rule::{self, MaybeNew, ViewportRule}; use crate::stylesheets::viewport_rule::{self, MaybeNew, ViewportRule};
use crate::stylesheets::{StyleRule, StylesheetInDocument, StylesheetContents};
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
use crate::stylesheets::{CounterStyleRule, FontFaceRule, FontFeatureValuesRule, PageRule}; use crate::stylesheets::{CounterStyleRule, FontFaceRule, FontFeatureValuesRule, PageRule};
use crate::stylesheets::{CssRule, Origin, OriginSet, PerOrigin, PerOriginIter, EffectiveRulesIterator}; use crate::stylesheets::{
CssRule, EffectiveRulesIterator, Origin, OriginSet, PerOrigin, PerOriginIter,
};
use crate::stylesheets::{StyleRule, StylesheetContents, StylesheetInDocument};
use crate::thread_state::{self, ThreadState}; use crate::thread_state::{self, ThreadState};
use crate::{Atom, LocalName, Namespace, WeakAtom}; use crate::{Atom, LocalName, Namespace, WeakAtom};
use fallible::FallibleVec; use fallible::FallibleVec;
use fxhash::FxHashMap;
use hashglobe::FailedAllocationError; use hashglobe::FailedAllocationError;
use malloc_size_of::MallocSizeOf; use malloc_size_of::MallocSizeOf;
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
@ -48,11 +53,10 @@ use selectors::NthIndexCache;
use servo_arc::{Arc, ArcBorrow}; use servo_arc::{Arc, ArcBorrow};
use smallbitvec::SmallBitVec; use smallbitvec::SmallBitVec;
use smallvec::SmallVec; use smallvec::SmallVec;
use std::hash::{Hash, Hasher};
use std::sync::Mutex; use std::sync::Mutex;
use std::{mem, ops}; use std::{mem, ops};
use std::hash::{Hash, Hasher};
use style_traits::viewport::ViewportConstraints; use style_traits::viewport::ViewportConstraints;
use fxhash::FxHashMap;
/// The type of the stylesheets that the stylist contains. /// The type of the stylesheets that the stylist contains.
#[cfg(feature = "servo")] #[cfg(feature = "servo")]
@ -93,7 +97,7 @@ struct CascadeDataCacheKey {
unsafe impl Send for CascadeDataCacheKey {} unsafe impl Send for CascadeDataCacheKey {}
unsafe impl Sync for CascadeDataCacheKey {} unsafe impl Sync for CascadeDataCacheKey {}
trait CascadeDataCacheEntry : Sized { trait CascadeDataCacheEntry: Sized {
/// Returns a reference to the cascade data. /// Returns a reference to the cascade data.
fn cascade_data(&self) -> &CascadeData; fn cascade_data(&self) -> &CascadeData;
/// Rebuilds the cascade data for the new stylesheet collection. The /// Rebuilds the cascade data for the new stylesheet collection. The
@ -121,7 +125,9 @@ where
Entry: CascadeDataCacheEntry, Entry: CascadeDataCacheEntry,
{ {
fn new() -> Self { fn new() -> Self {
Self { entries: Default::default() } Self {
entries: Default::default(),
}
} }
fn len(&self) -> usize { fn len(&self) -> usize {
@ -165,15 +171,9 @@ where
match self.entries.entry(key) { match self.entries.entry(key) {
HashMapEntry::Vacant(e) => { HashMapEntry::Vacant(e) => {
debug!("> Picking the slow path (not in the cache)"); debug!("> Picking the slow path (not in the cache)");
new_entry = Entry::rebuild( new_entry = Entry::rebuild(device, quirks_mode, collection, guard, old_entry)?;
device,
quirks_mode,
collection,
guard,
old_entry,
)?;
e.insert(new_entry.clone()); e.insert(new_entry.clone());
} },
HashMapEntry::Occupied(mut e) => { HashMapEntry::Occupied(mut e) => {
// Avoid reusing our old entry (this can happen if we get // Avoid reusing our old entry (this can happen if we get
// invalidated due to CSSOM mutations and our old stylesheet // invalidated due to CSSOM mutations and our old stylesheet
@ -192,15 +192,9 @@ where
} }
debug!("> Picking the slow path due to same entry as old"); debug!("> Picking the slow path due to same entry as old");
new_entry = Entry::rebuild( new_entry = Entry::rebuild(device, quirks_mode, collection, guard, old_entry)?;
device,
quirks_mode,
collection,
guard,
old_entry,
)?;
e.insert(new_entry.clone()); e.insert(new_entry.clone());
} },
} }
Ok(Some(new_entry)) Ok(Some(new_entry))
@ -272,7 +266,7 @@ impl CascadeDataCacheEntry for UserAgentCascadeData {
_old: &Self, _old: &Self,
) -> Result<Arc<Self>, FailedAllocationError> ) -> Result<Arc<Self>, FailedAllocationError>
where where
S: StylesheetInDocument + PartialEq + 'static S: StylesheetInDocument + PartialEq + 'static,
{ {
// TODO: Maybe we should support incremental rebuilds, though they seem // TODO: Maybe we should support incremental rebuilds, though they seem
// uncommon and rebuild() doesn't deal with // uncommon and rebuild() doesn't deal with
@ -604,13 +598,8 @@ impl Stylist {
where where
S: StylesheetInDocument + PartialEq + 'static, S: StylesheetInDocument + PartialEq + 'static,
{ {
self.author_data_cache.lookup( self.author_data_cache
&self.device, .lookup(&self.device, self.quirks_mode, collection, guard, old_data)
self.quirks_mode,
collection,
guard,
old_data,
)
} }
/// Iterate over the extra data in origin order. /// Iterate over the extra data in origin order.
@ -2114,7 +2103,11 @@ impl CascadeData {
} }
fn compute_layer_order(&mut self) { fn compute_layer_order(&mut self) {
debug_assert_ne!(self.layers.len(), 0, "There should be at least the root layer!"); debug_assert_ne!(
self.layers.len(),
0,
"There should be at least the root layer!"
);
if self.layers.len() == 1 { if self.layers.len() == 1 {
return; // Nothing to do return; // Nothing to do
} }
@ -2131,7 +2124,10 @@ impl CascadeData {
order: &mut LayerOrder, order: &mut LayerOrder,
) { ) {
for child in parent.children.iter() { for child in parent.children.iter() {
debug_assert!(parent.id < *child, "Children are always registered after parents"); debug_assert!(
parent.id < *child,
"Children are always registered after parents"
);
let child_index = (child.0 - parent.id.0 - 1) as usize; let child_index = (child.0 - parent.id.0 - 1) as usize;
let (first, remaining) = remaining_layers.split_at_mut(child_index + 1); let (first, remaining) = remaining_layers.split_at_mut(child_index + 1);
let child = &mut first[child_index]; let child = &mut first[child_index];
@ -2323,7 +2319,10 @@ impl CascadeData {
let keyframes_rule = keyframes_rule.read_with(guard); let keyframes_rule = keyframes_rule.read_with(guard);
debug!("Found valid keyframes rule: {:?}", *keyframes_rule); debug!("Found valid keyframes rule: {:?}", *keyframes_rule);
match self.animations.try_entry(keyframes_rule.name.as_atom().clone())? { match self
.animations
.try_entry(keyframes_rule.name.as_atom().clone())?
{
Entry::Vacant(e) => { Entry::Vacant(e) => {
e.insert(KeyframesAnimation::from_keyframes( e.insert(KeyframesAnimation::from_keyframes(
&keyframes_rule.keyframes, &keyframes_rule.keyframes,
@ -2338,9 +2337,8 @@ impl CascadeData {
// //
// TODO(emilio): This will need to be harder for // TODO(emilio): This will need to be harder for
// layers. // layers.
let needs_insert = let needs_insert = keyframes_rule.vendor_prefix.is_none() ||
keyframes_rule.vendor_prefix.is_none() || e.get().vendor_prefix.is_some();
e.get().vendor_prefix.is_some();
if needs_insert { if needs_insert {
e.insert(KeyframesAnimation::from_keyframes( e.insert(KeyframesAnimation::from_keyframes(
&keyframes_rule.keyframes, &keyframes_rule.keyframes,
@ -2401,13 +2399,8 @@ impl CascadeData {
} }
let mut effective = false; let mut effective = false;
let children = EffectiveRulesIterator::children( let children =
rule, EffectiveRulesIterator::children(rule, device, quirks_mode, guard, &mut effective);
device,
quirks_mode,
guard,
&mut effective,
);
if !effective { if !effective {
continue; continue;
@ -2426,7 +2419,8 @@ impl CascadeData {
let mut parent = layer.clone(); let mut parent = layer.clone();
parent.0.pop(); parent.0.pop();
*data.layer_id *data
.layer_id
.get_mut(&parent) .get_mut(&parent)
.expect("Parent layers should be registered before child layers") .expect("Parent layers should be registered before child layers")
} else { } else {
@ -2489,7 +2483,6 @@ impl CascadeData {
&mut layer_names_to_pop, &mut layer_names_to_pop,
); );
} }
}, },
CssRule::Media(ref lock) => { CssRule::Media(ref lock) => {
if rebuild_kind.should_rebuild_invalidation() { if rebuild_kind.should_rebuild_invalidation() {
@ -2509,7 +2502,7 @@ impl CascadeData {
&mut current_layer, &mut current_layer,
&mut layer_names_to_pop, &mut layer_names_to_pop,
); );
} },
LayerRuleKind::Statement { ref names } => { LayerRuleKind::Statement { ref names } => {
for name in &**names { for name in &**names {
let mut pushed = 0; let mut pushed = 0;
@ -2525,7 +2518,7 @@ impl CascadeData {
current_layer.0.pop(); current_layer.0.pop();
} }
} }
} },
} }
}, },
// We don't care about any other rule. // We don't care about any other rule.
@ -2609,7 +2602,9 @@ impl CascadeData {
let effective_now = stylesheet.is_effective_for_device(device, guard); let effective_now = stylesheet.is_effective_for_device(device, guard);
let effective_then = self.effective_media_query_results.was_effective(stylesheet.contents()); let effective_then = self
.effective_media_query_results
.was_effective(stylesheet.contents());
if effective_now != effective_then { if effective_now != effective_then {
debug!( debug!(
@ -2739,7 +2734,7 @@ impl CascadeDataCacheEntry for CascadeData {
old: &Self, old: &Self,
) -> Result<Arc<Self>, FailedAllocationError> ) -> Result<Arc<Self>, FailedAllocationError>
where where
S: StylesheetInDocument + PartialEq + 'static S: StylesheetInDocument + PartialEq + 'static,
{ {
debug_assert!(collection.dirty(), "We surely need to do something?"); debug_assert!(collection.dirty(), "We surely need to do something?");
// If we're doing a full rebuild anyways, don't bother cloning the data. // If we're doing a full rebuild anyways, don't bother cloning the data.

View file

@ -1122,7 +1122,7 @@ impl Animate for ComputedTransformOperation {
1. 1.
} else { } else {
-1. / perspective_z -1. / perspective_z
} },
)) ))
}; };
Ok(TransformOperation::Perspective(used_value)) Ok(TransformOperation::Perspective(used_value))
@ -1204,10 +1204,9 @@ impl ComputeSquaredDistance for ComputedTransformOperation {
( (
&TransformOperation::Perspective(ref fd), &TransformOperation::Perspective(ref fd),
&TransformOperation::Perspective(ref td), &TransformOperation::Perspective(ref td),
) => { ) => fd
fd.infinity_or(|l| l.px()) .infinity_or(|l| l.px())
.compute_squared_distance(&td.infinity_or(|l| l.px())) .compute_squared_distance(&td.infinity_or(|l| l.px())),
},
(&TransformOperation::Perspective(ref p), &TransformOperation::Matrix3D(ref m)) | (&TransformOperation::Perspective(ref p), &TransformOperation::Matrix3D(ref m)) |
(&TransformOperation::Matrix3D(ref m), &TransformOperation::Perspective(ref p)) => { (&TransformOperation::Matrix3D(ref m), &TransformOperation::Perspective(ref p)) => {
// FIXME(emilio): Is this right? Why interpolating this with // FIXME(emilio): Is this right? Why interpolating this with

View file

@ -6,7 +6,7 @@
use crate::values::animated::color::RGBA as AnimatedRGBA; use crate::values::animated::color::RGBA as AnimatedRGBA;
use crate::values::animated::ToAnimatedValue; use crate::values::animated::ToAnimatedValue;
use crate::values::generics::color::{GenericColor, GenericColorOrAuto, GenericCaretColor}; use crate::values::generics::color::{GenericCaretColor, GenericColor, GenericColorOrAuto};
use cssparser::{Color as CSSParserColor, RGBA}; use cssparser::{Color as CSSParserColor, RGBA};
use std::fmt; use std::fmt;
use style_traits::{CssWriter, ToCss}; use style_traits::{CssWriter, ToCss};

View file

@ -202,7 +202,6 @@ macro_rules! static_font_family {
}; };
} }
impl FontFamily { impl FontFamily {
#[inline] #[inline]
/// Get default font family as `serif` which is a generic font-family /// Get default font family as `serif` which is a generic font-family
@ -213,10 +212,13 @@ impl FontFamily {
/// Returns the font family for `-moz-bullet-font`. /// Returns the font family for `-moz-bullet-font`.
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
pub(crate) fn moz_bullet() -> &'static Self { pub(crate) fn moz_bullet() -> &'static Self {
static_font_family!(MOZ_BULLET, SingleFontFamily::FamilyName(FamilyName { static_font_family!(
name: atom!("-moz-bullet-font"), MOZ_BULLET,
syntax: FontFamilyNameSyntax::Identifiers, SingleFontFamily::FamilyName(FamilyName {
})); name: atom!("-moz-bullet-font"),
syntax: FontFamilyNameSyntax::Identifiers,
})
);
&*MOZ_BULLET &*MOZ_BULLET
} }
@ -226,10 +228,12 @@ impl FontFamily {
pub fn for_system_font(name: &str) -> Self { pub fn for_system_font(name: &str) -> Self {
Self { Self {
families: FontFamilyList { families: FontFamilyList {
list: crate::ArcSlice::from_iter(std::iter::once(SingleFontFamily::FamilyName(FamilyName { list: crate::ArcSlice::from_iter(std::iter::once(SingleFontFamily::FamilyName(
name: Atom::from(name), FamilyName {
syntax: FontFamilyNameSyntax::Identifiers, name: Atom::from(name),
}))), syntax: FontFamilyNameSyntax::Identifiers,
},
))),
fallback: GenericFontFamily::None, fallback: GenericFontFamily::None,
}, },
is_system_font: true, is_system_font: true,
@ -240,8 +244,11 @@ impl FontFamily {
pub fn generic(generic: GenericFontFamily) -> &'static Self { pub fn generic(generic: GenericFontFamily) -> &'static Self {
macro_rules! generic_font_family { macro_rules! generic_font_family {
($ident:ident, $family:ident) => { ($ident:ident, $family:ident) => {
static_font_family!($ident, SingleFontFamily::Generic(GenericFontFamily::$family)) static_font_family!(
} $ident,
SingleFontFamily::Generic(GenericFontFamily::$family)
)
};
} }
generic_font_family!(SERIF, Serif); generic_font_family!(SERIF, Serif);
@ -257,7 +264,7 @@ impl FontFamily {
GenericFontFamily::None => { GenericFontFamily::None => {
debug_assert!(false, "Bogus caller!"); debug_assert!(false, "Bogus caller!");
&*SERIF &*SERIF
} },
GenericFontFamily::Serif => &*SERIF, GenericFontFamily::Serif => &*SERIF,
GenericFontFamily::SansSerif => &*SANS_SERIF, GenericFontFamily::SansSerif => &*SANS_SERIF,
GenericFontFamily::Monospace => &*MONOSPACE, GenericFontFamily::Monospace => &*MONOSPACE,
@ -444,24 +451,21 @@ impl GenericFontFamily {
/// families that the website might specify, since they're not configured by /// families that the website might specify, since they're not configured by
/// the user. See bug 789788 and bug 1730098. /// the user. See bug 789788 and bug 1730098.
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
pub (crate) fn valid_for_user_font_prioritization(self) -> bool { pub(crate) fn valid_for_user_font_prioritization(self) -> bool {
match self { match self {
Self::None | Self::None | Self::Fantasy | Self::Cursive | Self::SystemUi | Self::MozEmoji => false,
Self::Fantasy |
Self::Cursive |
Self::SystemUi |
Self::MozEmoji => false,
Self::Serif | Self::Serif | Self::SansSerif | Self::Monospace => true,
Self::SansSerif |
Self::Monospace => true,
} }
} }
} }
impl Parse for SingleFontFamily { impl Parse for SingleFontFamily {
/// Parse a font-family value. /// Parse a font-family value.
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
if let Ok(value) = input.try_parse(|i| i.expect_string_cloned()) { if let Ok(value) = input.try_parse(|i| i.expect_string_cloned()) {
return Ok(SingleFontFamily::FamilyName(FamilyName { return Ok(SingleFontFamily::FamilyName(FamilyName {
name: Atom::from(&*value), name: Atom::from(&*value),
@ -603,13 +607,11 @@ impl FontFamilyList {
/// font prioritization, then move it to the front of the list. Otherwise, /// font prioritization, then move it to the front of the list. Otherwise,
/// prepend the default generic. /// prepend the default generic.
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
pub (crate) fn prioritize_first_generic_or_prepend(&mut self, generic: GenericFontFamily) { pub(crate) fn prioritize_first_generic_or_prepend(&mut self, generic: GenericFontFamily) {
let index_of_first_generic = self.iter().position(|f| { let index_of_first_generic = self.iter().position(|f| match *f {
match *f { SingleFontFamily::Generic(f) => f.valid_for_user_font_prioritization(),
SingleFontFamily::Generic(f) => f.valid_for_user_font_prioritization(), _ => false,
_ => false, });
}
});
if let Some(0) = index_of_first_generic { if let Some(0) = index_of_first_generic {
return; // Already first return; // Already first

View file

@ -84,7 +84,6 @@ impl ToComputedValue for specified::ImageSet {
let mut selected_resolution = items[0].resolution.dppx(); let mut selected_resolution = items[0].resolution.dppx();
for (i, item) in items.iter().enumerate() { for (i, item) in items.iter().enumerate() {
// If the MIME type is not supported, we discard the ImageSetItem // If the MIME type is not supported, we discard the ImageSetItem
if item.has_mime_type && !context.device().is_supported_mime_type(&item.mime_type) { if item.has_mime_type && !context.device().is_supported_mime_type(&item.mime_type) {
continue; continue;

View file

@ -37,7 +37,9 @@ impl ToComputedValue for specified::NoCalcLength {
length.to_computed_value(context, FontBaseSize::CurrentStyle) length.to_computed_value(context, FontBaseSize::CurrentStyle)
}, },
specified::NoCalcLength::ViewportPercentage(length) => { specified::NoCalcLength::ViewportPercentage(length) => {
context.builder.add_flags(ComputedValueFlags::USES_VIEWPORT_UNITS); context
.builder
.add_flags(ComputedValueFlags::USES_VIEWPORT_UNITS);
length.to_computed_value(context.viewport_size_for_viewport_unit_resolution()) length.to_computed_value(context.viewport_size_for_viewport_unit_resolution())
}, },
specified::NoCalcLength::ServoCharacterWidth(length) => { specified::NoCalcLength::ServoCharacterWidth(length) => {
@ -191,7 +193,7 @@ impl Size {
GenericSize::MaxContent | GenericSize::MaxContent |
GenericSize::FitContent | GenericSize::FitContent |
GenericSize::MozAvailable | GenericSize::MozAvailable |
GenericSize::FitContentFunction(_) => false GenericSize::FitContentFunction(_) => false,
} }
} }
} }

View file

@ -62,7 +62,7 @@ pub use self::font::{FontSize, FontSizeAdjust, FontStretch, FontSynthesis};
pub use self::font::{FontVariantAlternates, FontWeight}; pub use self::font::{FontVariantAlternates, FontWeight};
pub use self::font::{FontVariantEastAsian, FontVariationSettings}; pub use self::font::{FontVariantEastAsian, FontVariationSettings};
pub use self::font::{MathDepth, MozScriptMinSize, MozScriptSizeMultiplier, XLang, XTextZoom}; pub use self::font::{MathDepth, MozScriptMinSize, MozScriptSizeMultiplier, XLang, XTextZoom};
pub use self::image::{Gradient, Image, LineDirection, MozImageRect, ImageRendering}; pub use self::image::{Gradient, Image, ImageRendering, LineDirection, MozImageRect};
pub use self::length::{CSSPixelLength, NonNegativeLength}; pub use self::length::{CSSPixelLength, NonNegativeLength};
pub use self::length::{Length, LengthOrNumber, LengthPercentage, NonNegativeLengthOrNumber}; pub use self::length::{Length, LengthOrNumber, LengthPercentage, NonNegativeLengthOrNumber};
pub use self::length::{LengthOrAuto, LengthPercentageOrAuto, MaxSize, Size}; pub use self::length::{LengthOrAuto, LengthPercentageOrAuto, MaxSize, Size};

View file

@ -18,7 +18,9 @@ use crate::Zero;
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use style_traits::{CssWriter, ToCss}; use style_traits::{CssWriter, ToCss};
pub use crate::values::specified::text::{TextAlignLast, TextUnderlinePosition, MozControlCharacterVisibility}; pub use crate::values::specified::text::{
MozControlCharacterVisibility, TextAlignLast, TextUnderlinePosition,
};
pub use crate::values::specified::{LineBreak, OverflowWrap, RubyPosition, WordBreak}; pub use crate::values::specified::{LineBreak, OverflowWrap, RubyPosition, WordBreak};
pub use crate::values::specified::{TextDecorationLine, TextEmphasisPosition}; pub use crate::values::specified::{TextDecorationLine, TextEmphasisPosition};
pub use crate::values::specified::{TextDecorationSkipInk, TextJustify, TextTransform}; pub use crate::values::specified::{TextDecorationSkipInk, TextJustify, TextTransform};

View file

@ -520,7 +520,7 @@ impl ToAnimatedZero for TransformOperation {
Ok(generic::TransformOperation::Rotate(Angle::zero())) Ok(generic::TransformOperation::Rotate(Angle::zero()))
}, },
generic::TransformOperation::Perspective(_) => Ok( generic::TransformOperation::Perspective(_) => Ok(
generic::TransformOperation::Perspective(generic::PerspectiveFunction::None) generic::TransformOperation::Perspective(generic::PerspectiveFunction::None),
), ),
generic::TransformOperation::AccumulateMatrix { .. } | generic::TransformOperation::AccumulateMatrix { .. } |
generic::TransformOperation::InterpolateMatrix { .. } => { generic::TransformOperation::InterpolateMatrix { .. } => {

View file

@ -11,8 +11,8 @@ use crate::values::generics::CounterStyle;
#[cfg(any(feature = "gecko", feature = "servo-layout-2020"))] #[cfg(any(feature = "gecko", feature = "servo-layout-2020"))]
use crate::values::specified::Attr; use crate::values::specified::Attr;
use crate::values::CustomIdent; use crate::values::CustomIdent;
use std::ops::Deref;
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use std::ops::Deref;
use style_traits::{CssWriter, ToCss}; use style_traits::{CssWriter, ToCss};
/// A name / value pair for counters. /// A name / value pair for counters.
@ -238,15 +238,7 @@ impl<Image> Content<Image> {
/// Items for the `content` property. /// Items for the `content` property.
#[derive( #[derive(
Clone, Clone, Debug, Eq, MallocSizeOf, PartialEq, ToComputedValue, ToCss, ToResolvedValue, ToShmem,
Debug,
Eq,
MallocSizeOf,
PartialEq,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)] )]
#[repr(u8)] #[repr(u8)]
pub enum GenericContentItem<I> { pub enum GenericContentItem<I> {

View file

@ -131,9 +131,7 @@ pub struct GenericImageSet<Image, Resolution> {
} }
/// An optional percent and a cross fade image. /// An optional percent and a cross fade image.
#[derive( #[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToResolvedValue, ToShmem)]
Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToResolvedValue, ToShmem,
)]
#[repr(C)] #[repr(C)]
pub struct GenericImageSetItem<Image, Resolution> { pub struct GenericImageSetItem<Image, Resolution> {
/// `<image>`. `<string>` is converted to `Image::Url` at parse time. /// `<image>`. `<string>` is converted to `Image::Url` at parse time.
@ -151,8 +149,7 @@ pub struct GenericImageSetItem<Image, Resolution> {
pub has_mime_type: bool, pub has_mime_type: bool,
} }
impl<I: style_traits::ToCss, R: style_traits::ToCss> ToCss for GenericImageSetItem<I, R> impl<I: style_traits::ToCss, R: style_traits::ToCss> ToCss for GenericImageSetItem<I, R> {
{
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where where
W: fmt::Write, W: fmt::Write,

View file

@ -106,7 +106,7 @@ impl CounterStyle {
name == &atom!("square") || name == &atom!("square") ||
name == &atom!("disclosure-closed") || name == &atom!("disclosure-closed") ||
name == &atom!("disclosure-open") name == &atom!("disclosure-open")
} },
_ => false, _ => false,
} }
} }

View file

@ -733,7 +733,7 @@ where
dest.write_char(' ')?; dest.write_char(' ')?;
z.to_css(dest)?; z.to_css(dest)?;
dest.write_char(' ')?; dest.write_char(' ')?;
} },
} }
angle.to_css(dest) angle.to_css(dest)
}, },

View file

@ -56,15 +56,7 @@ impl<Image: ToCss> ToCss for Cursor<Image> {
} }
/// A generic value for item of `image cursors`. /// A generic value for item of `image cursors`.
#[derive( #[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToResolvedValue, ToShmem)]
Clone,
Debug,
MallocSizeOf,
PartialEq,
ToComputedValue,
ToResolvedValue,
ToShmem,
)]
#[repr(C)] #[repr(C)]
pub struct GenericCursorImage<Image, Number> { pub struct GenericCursorImage<Image, Number> {
/// The url to parse images from. /// The url to parse images from.

View file

@ -547,9 +547,7 @@ impl Parse for TimelineOrKeyframesName {
s, s,
&["none"], &["none"],
)?)), )?)),
Token::QuotedString(ref s) => { Token::QuotedString(ref s) => Ok(Self::QuotedString(Atom::from(s.as_ref()))),
Ok(Self::QuotedString(Atom::from(s.as_ref())))
},
ref t => Err(location.new_unexpected_token_error(t.clone())), ref t => Err(location.new_unexpected_token_error(t.clone())),
} }
} }

View file

@ -40,6 +40,8 @@ impl ToResolvedValue for computed::CaretColor {
#[inline] #[inline]
fn from_resolved_value(resolved: Self::ResolvedValue) -> Self { fn from_resolved_value(resolved: Self::ResolvedValue) -> Self {
generics::CaretColor(generics::ColorOrAuto::Color(computed::Color::from_resolved_value(resolved))) generics::CaretColor(generics::ColorOrAuto::Color(
computed::Color::from_resolved_value(resolved),
))
} }
} }

View file

@ -31,19 +31,22 @@ impl ToResolvedValue for computed::Content {
#[inline] #[inline]
fn to_resolved_value(self, context: &Context) -> Self { fn to_resolved_value(self, context: &Context) -> Self {
let (is_pseudo, is_before_or_after, is_marker) = let (is_pseudo, is_before_or_after, is_marker) = match context.style.pseudo() {
match context.style.pseudo() { Some(ref pseudo) => (true, pseudo.is_before_or_after(), pseudo.is_marker()),
Some(ref pseudo) => (true, pseudo.is_before_or_after(), pseudo.is_marker()), None => (false, false, false),
None => (false, false, false) };
};
match self { match self {
Self::Normal if is_before_or_after => Self::None, Self::Normal if is_before_or_after => Self::None,
// For now, make `content: none` compute to `normal` for pseudos // For now, make `content: none` compute to `normal` for pseudos
// other than ::before, ::after and ::marker, as we don't respect it. // other than ::before, ::after and ::marker, as we don't respect it.
// https://github.com/w3c/csswg-drafts/issues/6124 // https://github.com/w3c/csswg-drafts/issues/6124
// Ditto for non-pseudo elements if the pref is disabled. // Ditto for non-pseudo elements if the pref is disabled.
Self::None if (is_pseudo && !is_before_or_after && !is_marker) || Self::None
(!is_pseudo && !allow_element_content_none()) => Self::Normal, if (is_pseudo && !is_before_or_after && !is_marker) ||
(!is_pseudo && !allow_element_content_none()) =>
{
Self::Normal
},
other => other, other => other,
} }
} }

View file

@ -1954,7 +1954,10 @@ impl BreakBetween {
/// See https://drafts.csswg.org/css-break/#page-break-properties. /// See https://drafts.csswg.org/css-break/#page-break-properties.
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
#[inline] #[inline]
pub(crate) fn parse_legacy<'i>(_: &ParserContext, input: &mut Parser<'i, '_>) -> Result<Self, ParseError<'i>> { pub(crate) fn parse_legacy<'i>(
_: &ParserContext,
input: &mut Parser<'i, '_>,
) -> Result<Self, ParseError<'i>> {
let break_value = BreakBetween::parse(input)?; let break_value = BreakBetween::parse(input)?;
match break_value { match break_value {
BreakBetween::Always => Ok(BreakBetween::Page), BreakBetween::Always => Ok(BreakBetween::Page),
@ -2018,7 +2021,10 @@ impl BreakWithin {
/// See https://drafts.csswg.org/css-break/#page-break-properties. /// See https://drafts.csswg.org/css-break/#page-break-properties.
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
#[inline] #[inline]
pub(crate) fn parse_legacy<'i>(_: &ParserContext, input: &mut Parser<'i, '_>) -> Result<Self, ParseError<'i>> { pub(crate) fn parse_legacy<'i>(
_: &ParserContext,
input: &mut Parser<'i, '_>,
) -> Result<Self, ParseError<'i>> {
let break_value = BreakWithin::parse(input)?; let break_value = BreakWithin::parse(input)?;
match break_value { match break_value {
BreakWithin::Auto | BreakWithin::Avoid => Ok(break_value), BreakWithin::Auto | BreakWithin::Avoid => Ok(break_value),

View file

@ -380,43 +380,47 @@ impl CalcNode {
Ok(Self::MinMax(arguments.into(), op)) Ok(Self::MinMax(arguments.into(), op))
}, },
MathFunction::Sin | MathFunction::Sin | MathFunction::Cos | MathFunction::Tan => {
MathFunction::Cos |
MathFunction::Tan => {
let argument = Self::parse_argument(context, input, CalcUnit::Angle)?; let argument = Self::parse_argument(context, input, CalcUnit::Angle)?;
let radians = match argument.to_number() { let radians = match argument.to_number() {
Ok(v) => v, Ok(v) => v,
Err(()) => match argument.to_angle() { Err(()) => match argument.to_angle() {
Ok(angle) => angle.radians(), Ok(angle) => angle.radians(),
Err(()) => return Err( Err(()) => {
input.new_custom_error(StyleParseErrorKind::UnspecifiedError) return Err(
), input.new_custom_error(StyleParseErrorKind::UnspecifiedError)
)
},
}, },
}; };
let number = match function { let number = match function {
MathFunction::Sin => radians.sin(), MathFunction::Sin => radians.sin(),
MathFunction::Cos => radians.cos(), MathFunction::Cos => radians.cos(),
MathFunction::Tan => radians.tan(), MathFunction::Tan => radians.tan(),
_ => unsafe { debug_unreachable!("We just checked!"); }, _ => unsafe {
debug_unreachable!("We just checked!");
},
}; };
Ok(Self::Leaf(Leaf::Number(number))) Ok(Self::Leaf(Leaf::Number(number)))
}, },
MathFunction::Asin | MathFunction::Asin | MathFunction::Acos | MathFunction::Atan => {
MathFunction::Acos |
MathFunction::Atan => {
let argument = Self::parse_argument(context, input, CalcUnit::Number)?; let argument = Self::parse_argument(context, input, CalcUnit::Number)?;
let number = match argument.to_number() { let number = match argument.to_number() {
Ok(v) => v, Ok(v) => v,
Err(()) => return Err( Err(()) => {
input.new_custom_error(StyleParseErrorKind::UnspecifiedError) return Err(
), input.new_custom_error(StyleParseErrorKind::UnspecifiedError)
)
},
}; };
let radians = match function { let radians = match function {
MathFunction::Asin => number.asin(), MathFunction::Asin => number.asin(),
MathFunction::Acos => number.acos(), MathFunction::Acos => number.acos(),
MathFunction::Atan => number.atan(), MathFunction::Atan => number.atan(),
_ => unsafe { debug_unreachable!("We just checked!"); }, _ => unsafe {
debug_unreachable!("We just checked!");
},
}; };
Ok(Self::Leaf(Leaf::Angle(Angle::from_radians(radians)))) Ok(Self::Leaf(Leaf::Angle(Angle::from_radians(radians))))
@ -597,7 +601,9 @@ impl CalcNode {
let function = match MathFunction::from_ident(&*name) { let function = match MathFunction::from_ident(&*name) {
Ok(f) => f, Ok(f) => f,
Err(()) => return Err(location.new_unexpected_token_error(Token::Function(name.clone()))), Err(()) => {
return Err(location.new_unexpected_token_error(Token::Function(name.clone())))
},
}; };
if matches!(function, Sin | Cos | Tan | Asin | Acos | Atan) && !trig_enabled() { if matches!(function, Sin | Cos | Tan | Asin | Acos | Atan) && !trig_enabled() {

View file

@ -453,13 +453,12 @@ pub enum SystemColor {
impl SystemColor { impl SystemColor {
#[inline] #[inline]
fn compute(&self, cx: &Context) -> ComputedColor { fn compute(&self, cx: &Context) -> ComputedColor {
use crate::gecko_bindings::bindings;
use crate::gecko::values::convert_nscolor_to_rgba; use crate::gecko::values::convert_nscolor_to_rgba;
use crate::gecko_bindings::bindings;
// TODO: We should avoid cloning here most likely, though it's // TODO: We should avoid cloning here most likely, though it's
// cheap-ish. // cheap-ish.
let style_color_scheme = let style_color_scheme = cx.style().get_inherited_ui().clone_color_scheme();
cx.style().get_inherited_ui().clone_color_scheme();
let color = cx.device().system_nscolor(*self, &style_color_scheme); let color = cx.device().system_nscolor(*self, &style_color_scheme);
if color == bindings::NS_SAME_AS_FOREGROUND_COLOR { if color == bindings::NS_SAME_AS_FOREGROUND_COLOR {
return ComputedColor::currentcolor(); return ComputedColor::currentcolor();
@ -932,7 +931,10 @@ impl ColorScheme {
} }
impl Parse for ColorScheme { impl Parse for ColorScheme {
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 mut idents = vec![]; let mut idents = vec![];
let mut bits = ColorSchemeFlags::empty(); let mut bits = ColorSchemeFlags::empty();

View file

@ -22,7 +22,11 @@ use selectors::parser::SelectorParseErrorKind;
use style_traits::{KeywordsCollectFn, ParseError, SpecifiedValueInfo, StyleParseErrorKind}; use style_traits::{KeywordsCollectFn, ParseError, SpecifiedValueInfo, StyleParseErrorKind};
#[derive(PartialEq)] #[derive(PartialEq)]
enum CounterType { Increment, Set, Reset, } enum CounterType {
Increment,
Set,
Reset,
}
impl CounterType { impl CounterType {
fn default_value(&self) -> i32 { fn default_value(&self) -> i32 {
@ -41,7 +45,11 @@ impl Parse for CounterIncrement {
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
Ok(Self::new(parse_counters(context, input, CounterType::Increment)?)) Ok(Self::new(parse_counters(
context,
input,
CounterType::Increment,
)?))
} }
} }
@ -65,7 +73,11 @@ impl Parse for CounterReset {
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
Ok(Self::new(parse_counters(context, input, CounterType::Reset)?)) Ok(Self::new(parse_counters(
context,
input,
CounterType::Reset,
)?))
} }
} }
@ -85,13 +97,20 @@ fn parse_counters<'i, 't>(
loop { loop {
let location = input.current_source_location(); let location = input.current_source_location();
let (name, is_reversed) = match input.next() { let (name, is_reversed) = match input.next() {
Ok(&Token::Ident(ref ident)) => (CustomIdent::from_ident(location, ident, &["none"])?, false), Ok(&Token::Ident(ref ident)) => {
Ok(&Token::Function(ref name)) if counter_type == CounterType::Reset && name.eq_ignore_ascii_case("reversed") => { (CustomIdent::from_ident(location, ident, &["none"])?, false)
},
Ok(&Token::Function(ref name))
if counter_type == CounterType::Reset && name.eq_ignore_ascii_case("reversed") =>
{
input.parse_nested_block(|input| { input.parse_nested_block(|input| {
let location = input.current_source_location(); let location = input.current_source_location();
Ok((CustomIdent::from_ident(location, input.expect_ident()?, &["none"])?, true)) Ok((
CustomIdent::from_ident(location, input.expect_ident()?, &["none"])?,
true,
))
})? })?
} },
Ok(t) => { Ok(t) => {
let t = t.clone(); let t = t.clone();
return Err(location.new_unexpected_token_error(t)); return Err(location.new_unexpected_token_error(t));
@ -100,7 +119,7 @@ fn parse_counters<'i, 't>(
}; };
let value = match input.try_parse(|input| Integer::parse(context, input)) { let value = match input.try_parse(|input| Integer::parse(context, input)) {
Ok(start) => Ok(start) => {
if start.value == i32::min_value() { if start.value == i32::min_value() {
// The spec says that values must be clamped to the valid range, // The spec says that values must be clamped to the valid range,
// and we reserve i32::min_value() as an internal magic value. // and we reserve i32::min_value() as an internal magic value.
@ -108,10 +127,19 @@ fn parse_counters<'i, 't>(
Integer::new(i32::min_value() + 1) Integer::new(i32::min_value() + 1)
} else { } else {
start start
}, }
_ => Integer::new(if is_reversed { i32::min_value() } else { counter_type.default_value() }), },
_ => Integer::new(if is_reversed {
i32::min_value()
} else {
counter_type.default_value()
}),
}; };
counters.push(CounterPair { name, value, is_reversed }); counters.push(CounterPair {
name,
value,
is_reversed,
});
} }
if !counters.is_empty() { if !counters.is_empty() {

View file

@ -8,16 +8,18 @@
use crate::context::QuirksMode; use crate::context::QuirksMode;
use crate::parser::{Parse, ParserContext}; use crate::parser::{Parse, ParserContext};
use crate::values::computed::font::{FamilyName, FontFamilyList, FontStyleAngle, SingleFontFamily}; use crate::values::computed::font::{FamilyName, FontFamilyList, FontStyleAngle, SingleFontFamily};
use crate::values::computed::FontSizeAdjust as ComputedFontSizeAdjust;
use crate::values::computed::{font as computed, Length, NonNegativeLength}; use crate::values::computed::{font as computed, Length, NonNegativeLength};
use crate::values::computed::{Angle as ComputedAngle, Percentage as ComputedPercentage}; use crate::values::computed::{Angle as ComputedAngle, Percentage as ComputedPercentage};
use crate::values::computed::{CSSPixelLength, Context, ToComputedValue}; use crate::values::computed::{CSSPixelLength, Context, ToComputedValue};
use crate::values::computed::FontSizeAdjust as ComputedFontSizeAdjust;
use crate::values::generics::font::VariationValue; use crate::values::generics::font::VariationValue;
use crate::values::generics::font::{self as generics, FeatureTagValue, FontSettings, FontTag, GenericFontSizeAdjust}; use crate::values::generics::font::{
self as generics, FeatureTagValue, FontSettings, FontTag, GenericFontSizeAdjust,
};
use crate::values::generics::NonNegative; use crate::values::generics::NonNegative;
use crate::values::specified::length::{FontBaseSize, PX_PER_PT}; use crate::values::specified::length::{FontBaseSize, PX_PER_PT};
use crate::values::specified::{AllowQuirks, Angle, Integer, LengthPercentage}; use crate::values::specified::{AllowQuirks, Angle, Integer, LengthPercentage};
use crate::values::specified::{NoCalcLength, NonNegativeNumber, Number, NonNegativePercentage}; use crate::values::specified::{NoCalcLength, NonNegativeNumber, NonNegativePercentage, Number};
use crate::values::CustomIdent; use crate::values::CustomIdent;
use crate::Atom; use crate::Atom;
use cssparser::{Parser, Token}; use cssparser::{Parser, Token};
@ -406,7 +408,9 @@ impl ToComputedValue for FontStyle {
/// ///
/// https://drafts.csswg.org/css-fonts-4/#font-stretch-prop /// https://drafts.csswg.org/css-fonts-4/#font-stretch-prop
#[allow(missing_docs)] #[allow(missing_docs)]
#[derive(Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem)] #[derive(
Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem,
)]
#[repr(u8)] #[repr(u8)]
pub enum FontStretch { pub enum FontStretch {
Stretch(NonNegativePercentage), Stretch(NonNegativePercentage),
@ -510,7 +514,9 @@ impl ToComputedValue for FontStretch {
} }
fn from_computed_value(computed: &Self::ComputedValue) -> Self { fn from_computed_value(computed: &Self::ComputedValue) -> Self {
FontStretch::Stretch(NonNegativePercentage::from_computed_value(&NonNegative((computed.0).0))) FontStretch::Stretch(NonNegativePercentage::from_computed_value(&NonNegative(
(computed.0).0,
)))
} }
} }
@ -723,7 +729,8 @@ impl Parse for FontFamily {
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<FontFamily, ParseError<'i>> { ) -> Result<FontFamily, ParseError<'i>> {
let values = input.parse_comma_separated(|input| SingleFontFamily::parse(context, input))?; let values =
input.parse_comma_separated(|input| SingleFontFamily::parse(context, input))?;
Ok(FontFamily::Values(FontFamilyList { Ok(FontFamily::Values(FontFamilyList {
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
list: crate::ArcSlice::from_iter(values.into_iter()), list: crate::ArcSlice::from_iter(values.into_iter()),
@ -755,9 +762,7 @@ impl Parse for FamilyName {
} }
/// Preserve the readability of text when font fallback occurs /// Preserve the readability of text when font fallback occurs
#[derive( #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss, ToShmem)]
Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss, ToShmem,
)]
#[allow(missing_docs)] #[allow(missing_docs)]
pub enum FontSizeAdjust { pub enum FontSizeAdjust {
Value(GenericFontSizeAdjust<NonNegativeNumber>), Value(GenericFontSizeAdjust<NonNegativeNumber>),
@ -804,7 +809,9 @@ impl Parse for FontSizeAdjust {
} }
// Without a basis keyword, the number refers to the 'ex-height' metric. // Without a basis keyword, the number refers to the 'ex-height' metric.
let value = NonNegativeNumber::parse(context, input)?; let value = NonNegativeNumber::parse(context, input)?;
Ok(FontSizeAdjust::Value(GenericFontSizeAdjust::ExHeight(value))) Ok(FontSizeAdjust::Value(GenericFontSizeAdjust::ExHeight(
value,
)))
} }
} }
@ -1985,14 +1992,7 @@ impl Parse for FontFeatureSettings {
} }
#[derive( #[derive(
Clone, Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToResolvedValue, ToShmem,
Copy,
Debug,
MallocSizeOf,
PartialEq,
ToComputedValue,
ToResolvedValue,
ToShmem,
)] )]
/// Whether user agents are allowed to synthesize bold or oblique font faces /// Whether user agents are allowed to synthesize bold or oblique font faces
/// when a font family lacks those faces, or a small-caps variant when this is /// when a font family lacks those faces, or a small-caps variant when this is
@ -2102,11 +2102,7 @@ impl ToCss for FontSynthesis {
impl SpecifiedValueInfo for FontSynthesis { impl SpecifiedValueInfo for FontSynthesis {
fn collect_completion_keywords(f: KeywordsCollectFn) { fn collect_completion_keywords(f: KeywordsCollectFn) {
f(&[ f(&["none", "weight", "style"]);
"none",
"weight",
"style",
]);
if allow_font_synthesis_small_caps() { if allow_font_synthesis_small_caps() {
f(&["small-caps"]); f(&["small-caps"]);
} }
@ -2319,7 +2315,9 @@ impl Parse for VariationValue<Number> {
/// A metrics override value for a @font-face descriptor /// A metrics override value for a @font-face descriptor
/// ///
/// https://drafts.csswg.org/css-fonts/#font-metrics-override-desc /// https://drafts.csswg.org/css-fonts/#font-metrics-override-desc
#[derive(Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem)] #[derive(
Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem,
)]
pub enum MetricsOverride { pub enum MetricsOverride {
/// A non-negative `<percentage>` of the computed font size /// A non-negative `<percentage>` of the computed font size
Override(NonNegativePercentage), Override(NonNegativePercentage),

View file

@ -52,7 +52,9 @@ impl Parse for IntersectionObserverRootMargin {
use crate::Zero; use crate::Zero;
if input.is_exhausted() { if input.is_exhausted() {
// If there are zero elements in tokens, set tokens to ["0px"]. // If there are zero elements in tokens, set tokens to ["0px"].
return Ok(IntersectionObserverRootMargin(Rect::all(LengthPercentage::zero()))); return Ok(IntersectionObserverRootMargin(Rect::all(
LengthPercentage::zero(),
)));
} }
let rect = Rect::parse_with(context, input, parse_pixel_or_percent)?; let rect = Rect::parse_with(context, input, parse_pixel_or_percent)?;
Ok(IntersectionObserverRootMargin(rect)) Ok(IntersectionObserverRootMargin(rect))

View file

@ -181,7 +181,13 @@ impl Parse for Image {
context: &ParserContext, context: &ParserContext,
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<Image, ParseError<'i>> { ) -> Result<Image, ParseError<'i>> {
Image::parse_with_cors_mode(context, input, CorsMode::None, /* allow_none = */ true, /* only_url = */ false) Image::parse_with_cors_mode(
context,
input,
CorsMode::None,
/* allow_none = */ true,
/* only_url = */ false,
)
} }
} }
@ -334,7 +340,10 @@ impl CrossFadeImage {
cors_mode: CorsMode, cors_mode: CorsMode,
) -> Result<Self, ParseError<'i>> { ) -> Result<Self, ParseError<'i>> {
if let Ok(image) = input.try_parse(|input| { if let Ok(image) = input.try_parse(|input| {
Image::parse_with_cors_mode(context, input, cors_mode, /* allow_none = */ false, /* only_url = */ false) Image::parse_with_cors_mode(
context, input, cors_mode, /* allow_none = */ false,
/* only_url = */ false,
)
}) { }) {
return Ok(Self::Image(image)); return Ok(Self::Image(image));
} }
@ -374,7 +383,9 @@ impl ImageSet {
} }
} }
let items = input.parse_nested_block(|input| { let items = input.parse_nested_block(|input| {
input.parse_comma_separated(|input| ImageSetItem::parse(context, input, cors_mode, only_url)) input.parse_comma_separated(|input| {
ImageSetItem::parse(context, input, cors_mode, only_url)
})
})?; })?;
Ok(Self { Ok(Self {
selected_index: 0, selected_index: 0,
@ -386,9 +397,7 @@ impl ImageSet {
impl ImageSetItem { impl ImageSetItem {
fn parse_type<'i>(p: &mut Parser<'i, '_>) -> Result<crate::OwnedStr, ParseError<'i>> { fn parse_type<'i>(p: &mut Parser<'i, '_>) -> Result<crate::OwnedStr, ParseError<'i>> {
p.expect_function_matching("type")?; p.expect_function_matching("type")?;
p.parse_nested_block(|input| { p.parse_nested_block(|input| Ok(input.expect_string()?.as_ref().to_owned().into()))
Ok(input.expect_string()?.as_ref().to_owned().into())
})
} }
fn parse<'i, 't>( fn parse<'i, 't>(
@ -404,23 +413,33 @@ impl ImageSetItem {
cors_mode, cors_mode,
)), )),
Err(..) => Image::parse_with_cors_mode( Err(..) => Image::parse_with_cors_mode(
context, input, cors_mode, /* allow_none = */ false, /* only_url = */ only_url context, input, cors_mode, /* allow_none = */ false,
/* only_url = */ only_url,
)?, )?,
}; };
let mut resolution = input.try_parse(|input| Resolution::parse(context, input)).ok(); let mut resolution = input
.try_parse(|input| Resolution::parse(context, input))
.ok();
let mime_type = input.try_parse(Self::parse_type).ok(); let mime_type = input.try_parse(Self::parse_type).ok();
// Try to parse resolution after type(). // Try to parse resolution after type().
if mime_type.is_some() && resolution.is_none() { if mime_type.is_some() && resolution.is_none() {
resolution = input.try_parse(|input| Resolution::parse(context, input)).ok(); resolution = input
.try_parse(|input| Resolution::parse(context, input))
.ok();
} }
let resolution = resolution.unwrap_or(Resolution::X(1.0)); let resolution = resolution.unwrap_or(Resolution::X(1.0));
let has_mime_type = mime_type.is_some(); let has_mime_type = mime_type.is_some();
let mime_type = mime_type.unwrap_or_default(); let mime_type = mime_type.unwrap_or_default();
Ok(Self { image, resolution, has_mime_type, mime_type }) Ok(Self {
image,
resolution,
has_mime_type,
mime_type,
})
} }
} }

View file

@ -55,7 +55,7 @@ pub use self::font::{FontVariantAlternates, FontWeight};
pub use self::font::{FontVariantEastAsian, FontVariationSettings}; pub use self::font::{FontVariantEastAsian, FontVariationSettings};
pub use self::font::{MathDepth, MozScriptMinSize, MozScriptSizeMultiplier, XLang, XTextZoom}; pub use self::font::{MathDepth, MozScriptMinSize, MozScriptSizeMultiplier, XLang, XTextZoom};
pub use self::image::{EndingShape as GradientEndingShape, Gradient}; pub use self::image::{EndingShape as GradientEndingShape, Gradient};
pub use self::image::{Image, MozImageRect, ImageRendering}; pub use self::image::{Image, ImageRendering, MozImageRect};
pub use self::length::{AbsoluteLength, CalcLengthPercentage, CharacterWidth}; pub use self::length::{AbsoluteLength, CalcLengthPercentage, CharacterWidth};
pub use self::length::{FontRelativeLength, Length, LengthOrNumber, NonNegativeLengthOrNumber}; pub use self::length::{FontRelativeLength, Length, LengthOrNumber, NonNegativeLengthOrNumber};
pub use self::length::{LengthOrAuto, LengthPercentage, LengthPercentageOrAuto}; pub use self::length::{LengthOrAuto, LengthPercentage, LengthPercentageOrAuto};
@ -70,7 +70,7 @@ pub use self::list::Quotes;
pub use self::motion::{OffsetPath, OffsetRotate}; pub use self::motion::{OffsetPath, OffsetRotate};
pub use self::outline::OutlineStyle; pub use self::outline::OutlineStyle;
pub use self::page::{Orientation, PageSize, PaperSize}; pub use self::page::{Orientation, PageSize, PaperSize};
pub use self::percentage::{Percentage, NonNegativePercentage}; pub use self::percentage::{NonNegativePercentage, Percentage};
pub use self::position::AspectRatio; pub use self::position::AspectRatio;
pub use self::position::{ pub use self::position::{
GridAutoFlow, GridTemplateAreas, MasonryAutoFlow, Position, PositionOrAuto, GridAutoFlow, GridTemplateAreas, MasonryAutoFlow, Position, PositionOrAuto,
@ -83,9 +83,9 @@ pub use self::svg::{DProperty, MozContextProperties};
pub use self::svg::{SVGLength, SVGOpacity, SVGPaint}; pub use self::svg::{SVGLength, SVGOpacity, SVGPaint};
pub use self::svg::{SVGPaintOrder, SVGStrokeDashArray, SVGWidth}; pub use self::svg::{SVGPaintOrder, SVGStrokeDashArray, SVGWidth};
pub use self::svg_path::SVGPathData; pub use self::svg_path::SVGPathData;
pub use self::text::RubyPosition;
pub use self::text::TextAlignLast; pub use self::text::TextAlignLast;
pub use self::text::TextUnderlinePosition; pub use self::text::TextUnderlinePosition;
pub use self::text::RubyPosition;
pub use self::text::{InitialLetter, LetterSpacing, LineBreak, LineHeight, TextAlign}; pub use self::text::{InitialLetter, LetterSpacing, LineBreak, LineHeight, TextAlign};
pub use self::text::{OverflowWrap, TextEmphasisPosition, TextEmphasisStyle, WordBreak}; pub use self::text::{OverflowWrap, TextEmphasisPosition, TextEmphasisStyle, WordBreak};
pub use self::text::{TextAlignKeyword, TextDecorationLine, TextOverflow, WordSpacing}; pub use self::text::{TextAlignKeyword, TextDecorationLine, TextOverflow, WordSpacing};

View file

@ -85,7 +85,7 @@ impl SVGPathData {
absolute: IsAbsolute::new(seg_type == PATHSEG_MOVETO_ABS), absolute: IsAbsolute::new(seg_type == PATHSEG_MOVETO_ABS),
}); });
i = i + 2; i = i + 2;
} },
PATHSEG_LINETO_ABS | PATHSEG_LINETO_REL => { PATHSEG_LINETO_ABS | PATHSEG_LINETO_REL => {
debug_assert!(i + 1 < path.len()); debug_assert!(i + 1 < path.len());
result.push(PathCommand::LineTo { result.push(PathCommand::LineTo {
@ -93,7 +93,7 @@ impl SVGPathData {
absolute: IsAbsolute::new(seg_type == PATHSEG_LINETO_ABS), absolute: IsAbsolute::new(seg_type == PATHSEG_LINETO_ABS),
}); });
i = i + 2; i = i + 2;
} },
PATHSEG_CURVETO_CUBIC_ABS | PATHSEG_CURVETO_CUBIC_REL => { PATHSEG_CURVETO_CUBIC_ABS | PATHSEG_CURVETO_CUBIC_REL => {
debug_assert!(i + 5 < path.len()); debug_assert!(i + 5 < path.len());
result.push(PathCommand::CurveTo { result.push(PathCommand::CurveTo {
@ -103,7 +103,7 @@ impl SVGPathData {
absolute: IsAbsolute::new(seg_type == PATHSEG_CURVETO_CUBIC_ABS), absolute: IsAbsolute::new(seg_type == PATHSEG_CURVETO_CUBIC_ABS),
}); });
i = i + 6; i = i + 6;
} },
PATHSEG_CURVETO_QUADRATIC_ABS | PATHSEG_CURVETO_QUADRATIC_REL => { PATHSEG_CURVETO_QUADRATIC_ABS | PATHSEG_CURVETO_QUADRATIC_REL => {
debug_assert!(i + 3 < path.len()); debug_assert!(i + 3 < path.len());
result.push(PathCommand::QuadBezierCurveTo { result.push(PathCommand::QuadBezierCurveTo {
@ -112,7 +112,7 @@ impl SVGPathData {
absolute: IsAbsolute::new(seg_type == PATHSEG_CURVETO_QUADRATIC_ABS), absolute: IsAbsolute::new(seg_type == PATHSEG_CURVETO_QUADRATIC_ABS),
}); });
i = i + 4; i = i + 4;
} },
PATHSEG_ARC_ABS | PATHSEG_ARC_REL => { PATHSEG_ARC_ABS | PATHSEG_ARC_REL => {
debug_assert!(i + 6 < path.len()); debug_assert!(i + 6 < path.len());
result.push(PathCommand::EllipticalArc { result.push(PathCommand::EllipticalArc {
@ -125,7 +125,7 @@ impl SVGPathData {
absolute: IsAbsolute::new(seg_type == PATHSEG_ARC_ABS), absolute: IsAbsolute::new(seg_type == PATHSEG_ARC_ABS),
}); });
i = i + 7; i = i + 7;
} },
PATHSEG_LINETO_HORIZONTAL_ABS | PATHSEG_LINETO_HORIZONTAL_REL => { PATHSEG_LINETO_HORIZONTAL_ABS | PATHSEG_LINETO_HORIZONTAL_REL => {
debug_assert!(i < path.len()); debug_assert!(i < path.len());
result.push(PathCommand::HorizontalLineTo { result.push(PathCommand::HorizontalLineTo {
@ -133,7 +133,7 @@ impl SVGPathData {
absolute: IsAbsolute::new(seg_type == PATHSEG_LINETO_HORIZONTAL_ABS), absolute: IsAbsolute::new(seg_type == PATHSEG_LINETO_HORIZONTAL_ABS),
}); });
i = i + 1; i = i + 1;
} },
PATHSEG_LINETO_VERTICAL_ABS | PATHSEG_LINETO_VERTICAL_REL => { PATHSEG_LINETO_VERTICAL_ABS | PATHSEG_LINETO_VERTICAL_REL => {
debug_assert!(i < path.len()); debug_assert!(i < path.len());
result.push(PathCommand::VerticalLineTo { result.push(PathCommand::VerticalLineTo {
@ -141,7 +141,7 @@ impl SVGPathData {
absolute: IsAbsolute::new(seg_type == PATHSEG_LINETO_VERTICAL_ABS), absolute: IsAbsolute::new(seg_type == PATHSEG_LINETO_VERTICAL_ABS),
}); });
i = i + 1; i = i + 1;
} },
PATHSEG_CURVETO_CUBIC_SMOOTH_ABS | PATHSEG_CURVETO_CUBIC_SMOOTH_REL => { PATHSEG_CURVETO_CUBIC_SMOOTH_ABS | PATHSEG_CURVETO_CUBIC_SMOOTH_REL => {
debug_assert!(i + 3 < path.len()); debug_assert!(i + 3 < path.len());
result.push(PathCommand::SmoothCurveTo { result.push(PathCommand::SmoothCurveTo {
@ -150,7 +150,7 @@ impl SVGPathData {
absolute: IsAbsolute::new(seg_type == PATHSEG_CURVETO_CUBIC_SMOOTH_ABS), absolute: IsAbsolute::new(seg_type == PATHSEG_CURVETO_CUBIC_SMOOTH_ABS),
}); });
i = i + 4; i = i + 4;
} },
PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS | PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL => { PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS | PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL => {
debug_assert!(i + 1 < path.len()); debug_assert!(i + 1 < path.len());
result.push(PathCommand::SmoothQuadBezierCurveTo { result.push(PathCommand::SmoothQuadBezierCurveTo {
@ -158,7 +158,7 @@ impl SVGPathData {
absolute: IsAbsolute::new(seg_type == PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS), absolute: IsAbsolute::new(seg_type == PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS),
}); });
i = i + 2; i = i + 2;
} },
PATHSEG_UNKNOWN | _ => return Err(()), PATHSEG_UNKNOWN | _ => return Err(()),
} }
} }

View file

@ -1061,7 +1061,6 @@ impl Default for MozControlCharacterVisibility {
} }
} }
/// Values for the `line-break` property. /// Values for the `line-break` property.
#[repr(u8)] #[repr(u8)]
#[derive( #[derive(
@ -1259,15 +1258,7 @@ impl ToCss for TextUnderlinePosition {
/// Values for `ruby-position` property /// Values for `ruby-position` property
#[repr(u8)] #[repr(u8)]
#[derive( #[derive(
Clone, Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, ToComputedValue, ToResolvedValue, ToShmem,
Copy,
Debug,
Eq,
MallocSizeOf,
PartialEq,
ToComputedValue,
ToResolvedValue,
ToShmem,
)] )]
#[allow(missing_docs)] #[allow(missing_docs)]
pub enum RubyPosition { pub enum RubyPosition {
@ -1283,7 +1274,9 @@ impl Parse for RubyPosition {
input: &mut Parser<'i, 't>, input: &mut Parser<'i, 't>,
) -> Result<RubyPosition, ParseError<'i>> { ) -> Result<RubyPosition, ParseError<'i>> {
// Parse alternate before // Parse alternate before
let alternate = input.try_parse(|i| i.expect_ident_matching("alternate")).is_ok(); let alternate = input
.try_parse(|i| i.expect_ident_matching("alternate"))
.is_ok();
if alternate && input.is_exhausted() { if alternate && input.is_exhausted() {
return Ok(RubyPosition::AlternateOver); return Ok(RubyPosition::AlternateOver);
} }
@ -1294,7 +1287,9 @@ impl Parse for RubyPosition {
}; };
// Parse alternate after // Parse alternate after
let alternate = alternate || let alternate = alternate ||
input.try_parse(|i| i.expect_ident_matching("alternate")).is_ok(); input
.try_parse(|i| i.expect_ident_matching("alternate"))
.is_ok();
Ok(match (over, alternate) { Ok(match (over, alternate) {
(true, true) => RubyPosition::AlternateOver, (true, true) => RubyPosition::AlternateOver,

View file

@ -11,7 +11,9 @@ use crate::values::specified::image::Image;
use crate::values::specified::Number; use crate::values::specified::Number;
use cssparser::Parser; use cssparser::Parser;
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use style_traits::{CssWriter, KeywordsCollectFn, ParseError, SpecifiedValueInfo, StyleParseErrorKind, ToCss}; use style_traits::{
CssWriter, KeywordsCollectFn, ParseError, SpecifiedValueInfo, StyleParseErrorKind, ToCss,
};
/// A specified value for the `cursor` property. /// A specified value for the `cursor` property.
pub type Cursor = generics::GenericCursor<CursorImage>; pub type Cursor = generics::GenericCursor<CursorImage>;