From a0617bff0de3a4de70cc15123d0d6ffd6047f98f Mon Sep 17 00:00:00 2001 From: Ting-Yu Lin Date: Fri, 2 Jun 2023 02:26:03 +0200 Subject: [PATCH] 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 --- components/style/applicable_declarations.rs | 2 +- components/style/author_styles.rs | 13 +-- components/style/counter_style/mod.rs | 12 +-- components/style/custom_properties.rs | 13 +-- components/style/data.rs | 11 ++- components/style/error_reporting.rs | 2 +- components/style/gecko/media_features.rs | 48 +++++++-- components/style/gecko/media_queries.rs | 18 ++-- components/style/gecko/selector_parser.rs | 15 +-- components/style/gecko/wrapper.rs | 17 ++-- .../media_queries/media_feature_expression.rs | 16 +-- components/style/rule_collector.rs | 33 +++++-- components/style/selector_map.rs | 39 +++++--- components/style/selector_parser.rs | 3 +- components/style/shared_lock.rs | 10 +- components/style/style_adjuster.rs | 46 +++++++-- components/style/stylesheets/import_rule.rs | 3 +- components/style/stylesheets/loader.rs | 2 +- components/style/stylesheets/mod.rs | 4 +- components/style/stylesheets/rule_parser.rs | 23 ++--- .../style/stylesheets/rules_iterator.rs | 5 +- components/style/stylesheets/stylesheet.rs | 8 +- components/style/stylist.rs | 97 +++++++++---------- components/style/values/animated/transform.rs | 9 +- components/style/values/computed/color.rs | 2 +- components/style/values/computed/font.rs | 60 ++++++------ components/style/values/computed/image.rs | 1 - components/style/values/computed/length.rs | 6 +- components/style/values/computed/mod.rs | 2 +- components/style/values/computed/text.rs | 4 +- components/style/values/computed/transform.rs | 2 +- components/style/values/generics/counters.rs | 12 +-- components/style/values/generics/image.rs | 7 +- components/style/values/generics/mod.rs | 2 +- components/style/values/generics/transform.rs | 2 +- components/style/values/generics/ui.rs | 10 +- components/style/values/mod.rs | 4 +- components/style/values/resolved/color.rs | 4 +- components/style/values/resolved/counters.rs | 17 ++-- components/style/values/specified/box.rs | 10 +- components/style/values/specified/calc.rs | 36 ++++--- components/style/values/specified/color.rs | 10 +- components/style/values/specified/counters.rs | 50 +++++++--- components/style/values/specified/font.rs | 46 +++++---- components/style/values/specified/gecko.rs | 4 +- components/style/values/specified/image.rs | 39 ++++++-- components/style/values/specified/mod.rs | 6 +- components/style/values/specified/svg_path.rs | 18 ++-- components/style/values/specified/text.rs | 19 ++-- components/style/values/specified/ui.rs | 4 +- 50 files changed, 486 insertions(+), 340 deletions(-) diff --git a/components/style/applicable_declarations.rs b/components/style/applicable_declarations.rs index db0f7fce99f..7f2d3928d2d 100644 --- a/components/style/applicable_declarations.rs +++ b/components/style/applicable_declarations.rs @@ -6,8 +6,8 @@ use crate::properties::PropertyDeclarationBlock; use crate::rule_tree::{CascadeLevel, StyleSource}; -use crate::stylesheets::layer_rule::LayerOrder; use crate::shared_lock::Locked; +use crate::stylesheets::layer_rule::LayerOrder; use servo_arc::Arc; use smallvec::SmallVec; diff --git a/components/style/author_styles.rs b/components/style/author_styles.rs index dfd33711ed2..83bd0ad2854 100644 --- a/components/style/author_styles.rs +++ b/components/style/author_styles.rs @@ -10,10 +10,10 @@ use crate::dom::TElement; use crate::gecko_bindings::sugar::ownership::{HasBoxFFI, HasFFI, HasSimpleFFI}; use crate::invalidation::media_queries::ToMediaListKey; use crate::shared_lock::SharedRwLockReadGuard; -use crate::stylist::Stylist; use crate::stylesheet_set::AuthorStylesheetSet; use crate::stylesheets::StylesheetInDocument; use crate::stylist::CascadeData; +use crate::stylist::Stylist; use servo_arc::Arc; /// A set of author stylesheets and their computed representation, such as the @@ -32,9 +32,7 @@ where } lazy_static! { - static ref EMPTY_CASCADE_DATA: Arc = { - Arc::new_leaked(CascadeData::new()) - }; + static ref EMPTY_CASCADE_DATA: Arc = Arc::new_leaked(CascadeData::new()); } impl AuthorStyles @@ -55,11 +53,8 @@ where /// TODO(emilio): Need a host element and a snapshot map to do invalidation /// properly. #[inline] - pub fn flush( - &mut self, - stylist: &mut Stylist, - guard: &SharedRwLockReadGuard, - ) where + pub fn flush(&mut self, stylist: &mut Stylist, guard: &SharedRwLockReadGuard) + where E: TElement, S: ToMediaListKey, { diff --git a/components/style/counter_style/mod.rs b/components/style/counter_style/mod.rs index e470e53ae1f..daad5145e1c 100644 --- a/components/style/counter_style/mod.rs +++ b/components/style/counter_style/mod.rs @@ -55,12 +55,12 @@ pub fn parse_counter_style_name<'i, 't>( } fn is_valid_name_definition(ident: &CustomIdent) -> bool { - ident.0 != atom!("decimal") - && ident.0 != atom!("disc") - && ident.0 != atom!("circle") - && ident.0 != atom!("square") - && ident.0 != atom!("disclosure-closed") - && ident.0 != atom!("disclosure-open") + ident.0 != atom!("decimal") && + ident.0 != atom!("disc") && + ident.0 != atom!("circle") && + ident.0 != atom!("square") && + ident.0 != atom!("disclosure-closed") && + ident.0 != atom!("disclosure-open") } /// Parse the prelude of an @counter-style rule diff --git a/components/style/custom_properties.rs b/components/style/custom_properties.rs index 641a421bd5c..931bf32a00c 100644 --- a/components/style/custom_properties.rs +++ b/components/style/custom_properties.rs @@ -93,7 +93,9 @@ impl CssEnvironment { if !device.is_chrome_document() { 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)) } } @@ -682,10 +684,7 @@ impl<'a> CustomPropertiesBuilder<'a> { /// (meaning we should use the inherited value). /// /// It does cycle dependencies removal at the same time as substitution. -fn substitute_all( - custom_properties_map: &mut CustomPropertiesMap, - device: &Device, -) { +fn substitute_all(custom_properties_map: &mut CustomPropertiesMap, device: &Device) { // The cycle dependencies removal in this function is a variant // of Tarjan's algorithm. It is mostly based on the pseudo-code // listed in @@ -999,7 +998,9 @@ fn substitute_block<'i>( let first_token_type = input .next_including_whitespace_and_comments() .ok() - .map_or_else(TokenSerializationType::nothing, |t| t.serialization_type()); + .map_or_else(TokenSerializationType::nothing, |t| { + t.serialization_type() + }); input.reset(&after_comma); let mut position = (after_comma.position(), first_token_type); last_token_type = substitute_block( diff --git a/components/style/data.rs b/components/style/data.rs index f486b24dc58..758adf57a68 100644 --- a/components/style/data.rs +++ b/components/style/data.rs @@ -179,13 +179,20 @@ impl ElementStyles { pub fn uses_viewport_units(&self) -> bool { 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; } for pseudo_style in self.pseudos.as_array() { 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; } } diff --git a/components/style/error_reporting.rs b/components/style/error_reporting.rs index eebb0901309..752f68b5bdc 100644 --- a/components/style/error_reporting.rs +++ b/components/style/error_reporting.rs @@ -214,7 +214,7 @@ impl<'a> fmt::Display for ContextualParseError<'a> { ContextualParseError::UnsupportedValue(_value, ref err) => parse_error_to_str(err, f), ContextualParseError::NeverMatchingHostSelector(ref selector) => { write!(f, ":host selector is not featureless: {}", selector) - } + }, } } } diff --git a/components/style/gecko/media_features.rs b/components/style/gecko/media_features.rs index 40a34095d6f..d314500b88f 100644 --- a/components/style/gecko/media_features.rs +++ b/components/style/gecko/media_features.rs @@ -556,7 +556,8 @@ fn eval_moz_windows_non_native_menus( query_value: Option, _: Option, ) -> 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, 1 => true, _ => { @@ -873,18 +874,39 @@ pub static MEDIA_FEATURES: [MediaFeatureDescription; 58] = [ Evaluator::BoolInteger(eval_moz_overlay_scrollbars), ParsingRequirements::CHROME_AND_UA_ONLY, ), - - lnf_int_feature!(atom!("-moz-scrollbar-start-backward"), ScrollArrowStyle, get_scrollbar_start_backward), - 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-scrollbar-start-backward"), + ScrollArrowStyle, + get_scrollbar_start_backward + ), + 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-windows-default-theme"), WindowsDefaultTheme), 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-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-classic"), WindowsClassic), 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-maximize-button"), GTKCSDMaximizeButton), 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), 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" + ), ]; diff --git a/components/style/gecko/media_queries.rs b/components/style/gecko/media_queries.rs index 9c10c69609d..19ed6444f07 100644 --- a/components/style/gecko/media_queries.rs +++ b/components/style/gecko/media_queries.rs @@ -14,7 +14,7 @@ use crate::media_queries::MediaType; use crate::properties::ComputedValues; use crate::string_cache::Atom; 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::font::FONT_MEDIUM_PX; use crate::values::{CustomIdent, KeyframesName}; @@ -389,10 +389,12 @@ impl Device { } /// Computes a system color and returns it as an nscolor. - pub(crate) fn system_nscolor(&self, system_color: SystemColor, color_scheme: &ColorScheme) -> u32 { - unsafe { - bindings::Gecko_ComputeSystemColor(system_color, self.document(), color_scheme) - } + pub(crate) fn system_nscolor( + &self, + system_color: SystemColor, + color_scheme: &ColorScheme, + ) -> u32 { + unsafe { bindings::Gecko_ComputeSystemColor(system_color, self.document(), color_scheme) } } /// Returns the default background color. @@ -460,14 +462,16 @@ impl Device { /// Returns the gtk titlebar radius in CSS pixels. pub fn titlebar_radius(&self) -> f32 { 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. pub fn menu_radius(&self) -> f32 { unsafe { - bindings::Gecko_GetLookAndFeelInt(bindings::LookAndFeel_IntID::GtkMenuRadius as i32) as f32 + bindings::Gecko_GetLookAndFeelInt(bindings::LookAndFeel_IntID::GtkMenuRadius as i32) + as f32 } } diff --git a/components/style/gecko/selector_parser.rs b/components/style/gecko/selector_parser.rs index 47b2ce5e412..35c5a5c454d 100644 --- a/components/style/gecko/selector_parser.rs +++ b/components/style/gecko/selector_parser.rs @@ -139,7 +139,10 @@ impl NonTSPseudoClass { /// Returns whether the pseudo-class is enabled in content sheets. #[inline] 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"); } if let NonTSPseudoClass::MozLocaleDir(..) = *self { @@ -174,12 +177,10 @@ impl NonTSPseudoClass { /// Get the document state flag associated with a pseudo-class, if any. pub fn document_state_flag(&self) -> DocumentState { match *self { - NonTSPseudoClass::MozLocaleDir(ref dir) => { - match dir.as_horizontal_direction() { - Some(HorizontalDirection::Ltr) => DocumentState::LTR_LOCALE, - Some(HorizontalDirection::Rtl) => DocumentState::RTL_LOCALE, - None => DocumentState::empty(), - } + NonTSPseudoClass::MozLocaleDir(ref dir) => match dir.as_horizontal_direction() { + Some(HorizontalDirection::Ltr) => DocumentState::LTR_LOCALE, + Some(HorizontalDirection::Rtl) => DocumentState::RTL_LOCALE, + None => DocumentState::empty(), }, NonTSPseudoClass::MozWindowInactive => DocumentState::WINDOW_INACTIVE, NonTSPseudoClass::MozLWTheme => DocumentState::LWTHEME, diff --git a/components/style/gecko/wrapper.rs b/components/style/gecko/wrapper.rs index e9c67eac554..c41d2ff1e85 100644 --- a/components/style/gecko/wrapper.rs +++ b/components/style/gecko/wrapper.rs @@ -27,6 +27,7 @@ use crate::gecko_bindings::bindings; use crate::gecko_bindings::bindings::Gecko_ElementHasAnimations; use crate::gecko_bindings::bindings::Gecko_ElementHasCSSAnimations; 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_GetAnimationEffectCount; 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_UnsetDirtyStyleAttr; 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::structs; use crate::gecko_bindings::structs::nsChangeHint; @@ -1196,7 +1196,11 @@ impl<'le> TElement for GeckoElement<'le> { where 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; unsafe { let atom = if is_nodeinfo { @@ -1972,9 +1976,7 @@ impl<'le> ::selectors::Element for GeckoElement<'le> { NonTSPseudoClass::Active | NonTSPseudoClass::Hover | NonTSPseudoClass::MozAutofillPreview | - NonTSPseudoClass::Dir(..) => { - self.state().intersects(pseudo_class.state_flag()) - }, + NonTSPseudoClass::Dir(..) => self.state().intersects(pseudo_class.state_flag()), NonTSPseudoClass::AnyLink => self.is_link(), NonTSPseudoClass::Link => { self.is_link() && context.visited_handling().matches_unvisited() @@ -2033,7 +2035,10 @@ impl<'le> ::selectors::Element for GeckoElement<'le> { NonTSPseudoClass::MozWindowInactive => { let state_bit = pseudo_class.document_state_flag(); 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; } if context.extra_data.document_state.intersects(state_bit) { diff --git a/components/style/media_queries/media_feature_expression.rs b/components/style/media_queries/media_feature_expression.rs index 1658439da21..80827af401c 100644 --- a/components/style/media_queries/media_feature_expression.rs +++ b/components/style/media_queries/media_feature_expression.rs @@ -211,13 +211,15 @@ fn consume_operation_or_colon(input: &mut Parser) -> Result, () // // TODO(emilio): Maybe we should ignore comments as well? // https://github.com/w3c/csswg-drafts/issues/6248 - let parsed_equal = input.try_parse(|i| { - let t = i.next_including_whitespace().map_err(|_| ())?; - if !matches!(t, Token::Delim('=')) { - return Err(()) - } - Ok(()) - }).is_ok(); + let parsed_equal = input + .try_parse(|i| { + let t = i.next_including_whitespace().map_err(|_| ())?; + if !matches!(t, Token::Delim('=')) { + return Err(()); + } + Ok(()) + }) + .is_ok(); if !parsed_equal { return Ok(Some(operator)); diff --git a/components/style/rule_collector.rs b/components/style/rule_collector.rs index 65f55ea887a..021c0176416 100644 --- a/components/style/rule_collector.rs +++ b/components/style/rule_collector.rs @@ -147,8 +147,9 @@ where self.context.current_host = host.map(|e| e.opaque()); f(self); if start != self.rules.len() { - self.rules[start..] - .sort_unstable_by_key(|block| (block.layer_order, block.specificity, block.source_order())); + self.rules[start..].sort_unstable_by_key(|block| { + (block.layer_order, block.specificity, block.source_order()) + }); } self.context.current_host = old_host; self.in_sort_scope = false; @@ -214,7 +215,12 @@ where } #[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"); SelectorMap::get_matching_rules( self.element, @@ -228,7 +234,12 @@ where } #[inline] - fn collect_rules_in_map(&mut self, map: &SelectorMap, cascade_level: CascadeLevel, cascade_data: &CascadeData) { + fn collect_rules_in_map( + &mut self, + map: &SelectorMap, + cascade_level: CascadeLevel, + cascade_data: &CascadeData, + ) { debug_assert!(self.in_sort_scope, "Rules gotta be sorted"); map.get_all_matching_rules( self.element, @@ -390,10 +401,10 @@ where let outer_shadow = inner_shadow_host.containing_shadow(); let cascade_data = match outer_shadow { Some(shadow) => shadow.style_data(), - None => Some(self - .stylist - .cascade_data() - .borrow_for_origin(Origin::Author) + None => Some( + self.stylist + .cascade_data() + .borrow_for_origin(Origin::Author), ), }; @@ -406,7 +417,11 @@ where self.in_tree(containing_host, |collector| { for p in &parts { 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, + ); } } }); diff --git a/components/style/selector_map.rs b/components/style/selector_map.rs index a2b5d6bb6b6..ff7e93ae9c0 100644 --- a/components/style/selector_map.rs +++ b/components/style/selector_map.rs @@ -12,7 +12,7 @@ use crate::hash::map as hash_map; use crate::hash::{HashMap, HashSet}; use crate::rule_tree::CascadeLevel; use crate::selector_parser::SelectorImpl; -use crate::stylist::{Rule, CascadeData}; +use crate::stylist::{CascadeData, Rule}; use crate::{Atom, LocalName, Namespace, WeakAtom}; use fallible::FallibleVec; use hashglobe::FailedAllocationError; @@ -313,7 +313,8 @@ impl SelectorMap { context, 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 SelectorMap { &mut self.local_name_hash }; if name != lower_name { - hash - .try_entry(lower_name.clone())? + hash.try_entry(lower_name.clone())? .or_insert_with(SmallVec::new) .try_push($entry.clone())?; } - hash - .try_entry(name.clone())? - .or_insert_with(SmallVec::new) + hash.try_entry(name.clone())?.or_insert_with(SmallVec::new) }, Bucket::Namespace(url) => self .namespace_hash @@ -387,7 +385,11 @@ impl SelectorMap { let bucket = { 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 // selector map would be worth it. Consider a case like: @@ -619,11 +621,16 @@ fn specific_bucket_for<'a>( Component::Root => Bucket::Root, Component::ID(ref id) => Bucket::ID(id), Component::Class(ref class) => Bucket::Class(class), - Component::AttributeInNoNamespace { ref local_name, .. } if bucket_attributes => Bucket::Attribute { - name: local_name, - lower_name: local_name, + Component::AttributeInNoNamespace { ref local_name, .. } if bucket_attributes => { + Bucket::Attribute { + 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, 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 // match the slotted . - Component::Slotted(ref selector) => find_bucket(selector.iter(), disjoint_buckets, bucket_attributes), - Component::Host(Some(ref selector)) => find_bucket(selector.iter(), disjoint_buckets, bucket_attributes), + Component::Slotted(ref selector) => { + 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) => { if list.len() == 1 { find_bucket(list[0].iter(), disjoint_buckets, bucket_attributes) diff --git a/components/style/selector_parser.rs b/components/style/selector_parser.rs index 8e0e3412d4b..d28e333da04 100644 --- a/components/style/selector_parser.rs +++ b/components/style/selector_parser.rs @@ -76,8 +76,7 @@ impl<'a> SelectorParser<'a> { /// Whether we're parsing selectors in a stylesheet that has chrome /// privilege. pub fn chrome_rules_enabled(&self) -> bool { - self.url_data.chrome_rules_enabled() || - self.stylesheet_origin == Origin::User + self.url_data.chrome_rules_enabled() || self.stylesheet_origin == Origin::User } } diff --git a/components/style/shared_lock.rs b/components/style/shared_lock.rs index d524f0c6cdf..55708a9f7bb 100644 --- a/components/style/shared_lock.rs +++ b/components/style/shared_lock.rs @@ -97,7 +97,10 @@ impl SharedRwLock { #[cfg(feature = "gecko")] #[inline] 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. @@ -154,7 +157,10 @@ impl<'a> SharedRwLockReadGuard<'a> { #[inline] #[cfg(feature = "gecko")] 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()) } } diff --git a/components/style/style_adjuster.rs b/components/style/style_adjuster.rs index 31028f98571..d12864155dd 100644 --- a/components/style/style_adjuster.rs +++ b/components/style/style_adjuster.rs @@ -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. #[cfg(feature = "gecko")] fn adjust_for_marker_pseudo(&mut self) { + use crate::values::computed::counters::Content; use crate::values::computed::font::{FontFamily, FontSynthesis}; 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()) && 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 { return; } - if !self.style.flags.get().contains(ComputedValueFlags::HAS_AUTHOR_SPECIFIED_FONT_FAMILY) { - self.style.mutate_font().set_font_family(FontFamily::moz_bullet().clone()); + if !self + .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. // Then we can add it to the @font-face rule in html.css instead. // https://github.com/w3c/csswg-drafts/issues/6081 - if !self.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_FONT_SYNTHESIS) + { + self.style + .mutate_font() + .set_font_synthesis(FontSynthesis::none()); } } - if !self.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_LETTER_SPACING) + { + self.style + .mutate_inherited_text() + .set_letter_spacing(LetterSpacing::normal()); } - if !self.style.flags.get().contains(ComputedValueFlags::HAS_AUTHOR_SPECIFIED_WORD_SPACING) { - self.style.mutate_inherited_text().set_word_spacing(WordSpacing::normal()); + if !self + .style + .flags + .get() + .contains(ComputedValueFlags::HAS_AUTHOR_SPECIFIED_WORD_SPACING) + { + self.style + .mutate_inherited_text() + .set_word_spacing(WordSpacing::normal()); } } diff --git a/components/style/stylesheets/import_rule.rs b/components/style/stylesheets/import_rule.rs index 7352dea0b9e..ccf0bb11e51 100644 --- a/components/style/stylesheets/import_rule.rs +++ b/components/style/stylesheets/import_rule.rs @@ -10,8 +10,8 @@ use crate::media_queries::MediaList; use crate::shared_lock::{DeepCloneParams, DeepCloneWithLock}; use crate::shared_lock::{SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard}; use crate::str::CssStringWriter; -use crate::stylesheets::{CssRule, StylesheetInDocument}; use crate::stylesheets::layer_rule::LayerName; +use crate::stylesheets::{CssRule, StylesheetInDocument}; use crate::values::CssUrl; use cssparser::SourceLocation; use std::fmt::{self, Write}; @@ -131,7 +131,6 @@ pub struct ImportLayer { pub name: Option, } - impl ToCss for ImportLayer { fn to_css(&self, dest: &mut CssWriter) -> fmt::Result where diff --git a/components/style/stylesheets/loader.rs b/components/style/stylesheets/loader.rs index c145bafdc04..45f7d22a55c 100644 --- a/components/style/stylesheets/loader.rs +++ b/components/style/stylesheets/loader.rs @@ -8,7 +8,7 @@ use crate::media_queries::MediaList; use crate::parser::ParserContext; 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 cssparser::SourceLocation; use servo_arc::Arc; diff --git a/components/style/stylesheets/mod.rs b/components/style/stylesheets/mod.rs index 762bca6033f..f7098e0c151 100644 --- a/components/style/stylesheets/mod.rs +++ b/components/style/stylesheets/mod.rs @@ -509,11 +509,11 @@ impl DeepCloneWithLock for CssRule { CssRule::Layer(Arc::new( lock.wrap(rule.deep_clone_with_lock(lock, guard, params)), )) - } + }, CssRule::ScrollTimeline(ref arc) => { let rule = arc.read_with(guard); CssRule::ScrollTimeline(Arc::new(lock.wrap(rule.clone()))) - } + }, } } } diff --git a/components/style/stylesheets/rule_parser.rs b/components/style/stylesheets/rule_parser.rs index 995ee801e40..12ec7226bfc 100644 --- a/components/style/stylesheets/rule_parser.rs +++ b/components/style/stylesheets/rule_parser.rs @@ -289,7 +289,7 @@ impl<'a, 'i> AtRuleParser<'i> for TopLevelRuleParser<'a> { &mut self, prelude: AtRulePrelude, start: &ParserState, - ) -> Result { + ) -> Result { let rule = match prelude { AtRulePrelude::Import(url, media, layer) => { let loader = self @@ -613,15 +613,13 @@ impl<'a, 'b, 'i> AtRuleParser<'i> for NestedRuleParser<'a, 'b> { 0 | 1 => names.into_iter().next(), _ => return Err(input.new_error(BasicParseErrorKind::AtRuleBodyInvalid)), }; - Ok(CssRule::Layer(Arc::new(self.shared_lock.wrap( - LayerRule { - kind: LayerRuleKind::Block { - name, - rules: self.parse_nested_rules(input, CssRuleType::Layer), - }, - source_location: start.source_location(), + Ok(CssRule::Layer(Arc::new(self.shared_lock.wrap(LayerRule { + kind: LayerRuleKind::Block { + name, + rules: self.parse_nested_rules(input, CssRuleType::Layer), }, - )))) + source_location: start.source_location(), + })))) }, AtRulePrelude::Import(..) | AtRulePrelude::Namespace(..) => { // These rules don't have blocks. @@ -650,7 +648,7 @@ impl<'a, 'b, 'i> AtRuleParser<'i> for NestedRuleParser<'a, 'b> { &mut self, prelude: AtRulePrelude, start: &ParserState, - ) -> Result { + ) -> Result { Ok(match prelude { AtRulePrelude::Layer(names) => { if names.is_empty() { @@ -687,7 +685,10 @@ fn check_for_useless_selector( } if found_host && found_non_host { 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; } } diff --git a/components/style/stylesheets/rules_iterator.rs b/components/style/stylesheets/rules_iterator.rs index 32851dd2cca..0cbc7327441 100644 --- a/components/style/stylesheets/rules_iterator.rs +++ b/components/style/stylesheets/rules_iterator.rs @@ -111,7 +111,7 @@ where LayerRuleKind::Block { ref rules, .. } => Some(rules.read_with(guard).0.iter()), LayerRuleKind::Statement { .. } => None, } - } + }, } } } @@ -323,7 +323,8 @@ impl<'a, 'b> EffectiveRulesIterator<'a, 'b> { guard: &'a SharedRwLockReadGuard<'b>, rule: &'a CssRule, ) -> Self { - let children = RulesIterator::::children(rule, device, quirks_mode, guard, &mut false); + let children = + RulesIterator::::children(rule, device, quirks_mode, guard, &mut false); EffectiveRulesIterator::new(device, quirks_mode, guard, children.unwrap_or([].iter())) } } diff --git a/components/style/stylesheets/stylesheet.rs b/components/style/stylesheets/stylesheet.rs index 1b6b59bac78..e63d8187365 100644 --- a/components/style/stylesheets/stylesheet.rs +++ b/components/style/stylesheets/stylesheet.rs @@ -591,9 +591,11 @@ impl Clone for Stylesheet { // Make a deep clone of the media, using the new lock. let media = self.media.read_with(&guard).clone(); let media = Arc::new(lock.wrap(media)); - let contents = Arc::new(self - .contents - .deep_clone_with_lock(&lock, &guard, &DeepCloneParams)); + let contents = Arc::new(self.contents.deep_clone_with_lock( + &lock, + &guard, + &DeepCloneParams, + )); Stylesheet { contents, diff --git a/components/style/stylist.rs b/components/style/stylist.rs index 0663ea440d9..a5538aa1189 100644 --- a/components/style/stylist.rs +++ b/components/style/stylist.rs @@ -11,7 +11,9 @@ use crate::element_state::{DocumentState, ElementState}; #[cfg(feature = "gecko")] use crate::gecko_bindings::structs::{ServoStyleSetSizes, StyleRuleInclusion}; 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::media_queries::Device; 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::{DocumentStylesheetFlusher, SheetCollectionFlusher}; 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::{StyleRule, StylesheetInDocument, StylesheetContents}; #[cfg(feature = "gecko")] 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::{Atom, LocalName, Namespace, WeakAtom}; use fallible::FallibleVec; +use fxhash::FxHashMap; use hashglobe::FailedAllocationError; use malloc_size_of::MallocSizeOf; #[cfg(feature = "gecko")] @@ -48,11 +53,10 @@ use selectors::NthIndexCache; use servo_arc::{Arc, ArcBorrow}; use smallbitvec::SmallBitVec; use smallvec::SmallVec; +use std::hash::{Hash, Hasher}; use std::sync::Mutex; use std::{mem, ops}; -use std::hash::{Hash, Hasher}; use style_traits::viewport::ViewportConstraints; -use fxhash::FxHashMap; /// The type of the stylesheets that the stylist contains. #[cfg(feature = "servo")] @@ -93,7 +97,7 @@ struct CascadeDataCacheKey { unsafe impl Send for CascadeDataCacheKey {} unsafe impl Sync for CascadeDataCacheKey {} -trait CascadeDataCacheEntry : Sized { +trait CascadeDataCacheEntry: Sized { /// Returns a reference to the cascade data. fn cascade_data(&self) -> &CascadeData; /// Rebuilds the cascade data for the new stylesheet collection. The @@ -121,7 +125,9 @@ where Entry: CascadeDataCacheEntry, { fn new() -> Self { - Self { entries: Default::default() } + Self { + entries: Default::default(), + } } fn len(&self) -> usize { @@ -165,15 +171,9 @@ where match self.entries.entry(key) { HashMapEntry::Vacant(e) => { debug!("> Picking the slow path (not in the cache)"); - new_entry = Entry::rebuild( - device, - quirks_mode, - collection, - guard, - old_entry, - )?; + new_entry = Entry::rebuild(device, quirks_mode, collection, guard, old_entry)?; e.insert(new_entry.clone()); - } + }, HashMapEntry::Occupied(mut e) => { // Avoid reusing our old entry (this can happen if we get // 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"); - new_entry = Entry::rebuild( - device, - quirks_mode, - collection, - guard, - old_entry, - )?; + new_entry = Entry::rebuild(device, quirks_mode, collection, guard, old_entry)?; e.insert(new_entry.clone()); - } + }, } Ok(Some(new_entry)) @@ -272,7 +266,7 @@ impl CascadeDataCacheEntry for UserAgentCascadeData { _old: &Self, ) -> Result, FailedAllocationError> where - S: StylesheetInDocument + PartialEq + 'static + S: StylesheetInDocument + PartialEq + 'static, { // TODO: Maybe we should support incremental rebuilds, though they seem // uncommon and rebuild() doesn't deal with @@ -604,13 +598,8 @@ impl Stylist { where S: StylesheetInDocument + PartialEq + 'static, { - self.author_data_cache.lookup( - &self.device, - self.quirks_mode, - collection, - guard, - old_data, - ) + self.author_data_cache + .lookup(&self.device, self.quirks_mode, collection, guard, old_data) } /// Iterate over the extra data in origin order. @@ -2114,7 +2103,11 @@ impl CascadeData { } 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 { return; // Nothing to do } @@ -2131,7 +2124,10 @@ impl CascadeData { order: &mut LayerOrder, ) { 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 (first, remaining) = remaining_layers.split_at_mut(child_index + 1); let child = &mut first[child_index]; @@ -2323,7 +2319,10 @@ impl CascadeData { let keyframes_rule = keyframes_rule.read_with(guard); 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) => { e.insert(KeyframesAnimation::from_keyframes( &keyframes_rule.keyframes, @@ -2338,9 +2337,8 @@ impl CascadeData { // // TODO(emilio): This will need to be harder for // layers. - let needs_insert = - keyframes_rule.vendor_prefix.is_none() || - e.get().vendor_prefix.is_some(); + let needs_insert = keyframes_rule.vendor_prefix.is_none() || + e.get().vendor_prefix.is_some(); if needs_insert { e.insert(KeyframesAnimation::from_keyframes( &keyframes_rule.keyframes, @@ -2401,13 +2399,8 @@ impl CascadeData { } let mut effective = false; - let children = EffectiveRulesIterator::children( - rule, - device, - quirks_mode, - guard, - &mut effective, - ); + let children = + EffectiveRulesIterator::children(rule, device, quirks_mode, guard, &mut effective); if !effective { continue; @@ -2426,7 +2419,8 @@ impl CascadeData { let mut parent = layer.clone(); parent.0.pop(); - *data.layer_id + *data + .layer_id .get_mut(&parent) .expect("Parent layers should be registered before child layers") } else { @@ -2489,7 +2483,6 @@ impl CascadeData { &mut layer_names_to_pop, ); } - }, CssRule::Media(ref lock) => { if rebuild_kind.should_rebuild_invalidation() { @@ -2509,7 +2502,7 @@ impl CascadeData { &mut current_layer, &mut layer_names_to_pop, ); - } + }, LayerRuleKind::Statement { ref names } => { for name in &**names { let mut pushed = 0; @@ -2525,7 +2518,7 @@ impl CascadeData { current_layer.0.pop(); } } - } + }, } }, // 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_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 { debug!( @@ -2739,7 +2734,7 @@ impl CascadeDataCacheEntry for CascadeData { old: &Self, ) -> Result, FailedAllocationError> where - S: StylesheetInDocument + PartialEq + 'static + S: StylesheetInDocument + PartialEq + 'static, { debug_assert!(collection.dirty(), "We surely need to do something?"); // If we're doing a full rebuild anyways, don't bother cloning the data. diff --git a/components/style/values/animated/transform.rs b/components/style/values/animated/transform.rs index 598bf9b59a7..542b4c31023 100644 --- a/components/style/values/animated/transform.rs +++ b/components/style/values/animated/transform.rs @@ -1122,7 +1122,7 @@ impl Animate for ComputedTransformOperation { 1. } else { -1. / perspective_z - } + }, )) }; Ok(TransformOperation::Perspective(used_value)) @@ -1204,10 +1204,9 @@ impl ComputeSquaredDistance for ComputedTransformOperation { ( &TransformOperation::Perspective(ref fd), &TransformOperation::Perspective(ref td), - ) => { - fd.infinity_or(|l| l.px()) - .compute_squared_distance(&td.infinity_or(|l| l.px())) - }, + ) => fd + .infinity_or(|l| l.px()) + .compute_squared_distance(&td.infinity_or(|l| l.px())), (&TransformOperation::Perspective(ref p), &TransformOperation::Matrix3D(ref m)) | (&TransformOperation::Matrix3D(ref m), &TransformOperation::Perspective(ref p)) => { // FIXME(emilio): Is this right? Why interpolating this with diff --git a/components/style/values/computed/color.rs b/components/style/values/computed/color.rs index 36cd1db4a42..6b970181d85 100644 --- a/components/style/values/computed/color.rs +++ b/components/style/values/computed/color.rs @@ -6,7 +6,7 @@ use crate::values::animated::color::RGBA as AnimatedRGBA; 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 std::fmt; use style_traits::{CssWriter, ToCss}; diff --git a/components/style/values/computed/font.rs b/components/style/values/computed/font.rs index 18fbe8c6fd8..ab6755d0951 100644 --- a/components/style/values/computed/font.rs +++ b/components/style/values/computed/font.rs @@ -202,7 +202,6 @@ macro_rules! static_font_family { }; } - impl FontFamily { #[inline] /// 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`. #[cfg(feature = "gecko")] pub(crate) fn moz_bullet() -> &'static Self { - static_font_family!(MOZ_BULLET, SingleFontFamily::FamilyName(FamilyName { - name: atom!("-moz-bullet-font"), - syntax: FontFamilyNameSyntax::Identifiers, - })); + static_font_family!( + MOZ_BULLET, + SingleFontFamily::FamilyName(FamilyName { + name: atom!("-moz-bullet-font"), + syntax: FontFamilyNameSyntax::Identifiers, + }) + ); &*MOZ_BULLET } @@ -226,10 +228,12 @@ impl FontFamily { pub fn for_system_font(name: &str) -> Self { Self { families: FontFamilyList { - list: crate::ArcSlice::from_iter(std::iter::once(SingleFontFamily::FamilyName(FamilyName { - name: Atom::from(name), - syntax: FontFamilyNameSyntax::Identifiers, - }))), + list: crate::ArcSlice::from_iter(std::iter::once(SingleFontFamily::FamilyName( + FamilyName { + name: Atom::from(name), + syntax: FontFamilyNameSyntax::Identifiers, + }, + ))), fallback: GenericFontFamily::None, }, is_system_font: true, @@ -240,8 +244,11 @@ impl FontFamily { pub fn generic(generic: GenericFontFamily) -> &'static Self { macro_rules! generic_font_family { ($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); @@ -257,7 +264,7 @@ impl FontFamily { GenericFontFamily::None => { debug_assert!(false, "Bogus caller!"); &*SERIF - } + }, GenericFontFamily::Serif => &*SERIF, GenericFontFamily::SansSerif => &*SANS_SERIF, GenericFontFamily::Monospace => &*MONOSPACE, @@ -444,24 +451,21 @@ impl GenericFontFamily { /// families that the website might specify, since they're not configured by /// the user. See bug 789788 and bug 1730098. #[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 { - Self::None | - Self::Fantasy | - Self::Cursive | - Self::SystemUi | - Self::MozEmoji => false, + Self::None | Self::Fantasy | Self::Cursive | Self::SystemUi | Self::MozEmoji => false, - Self::Serif | - Self::SansSerif | - Self::Monospace => true, + Self::Serif | Self::SansSerif | Self::Monospace => true, } } } impl Parse for SingleFontFamily { /// Parse a font-family value. - fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result> { + fn parse<'i, 't>( + context: &ParserContext, + input: &mut Parser<'i, 't>, + ) -> Result> { if let Ok(value) = input.try_parse(|i| i.expect_string_cloned()) { return Ok(SingleFontFamily::FamilyName(FamilyName { name: Atom::from(&*value), @@ -603,13 +607,11 @@ impl FontFamilyList { /// font prioritization, then move it to the front of the list. Otherwise, /// prepend the default generic. #[cfg(feature = "gecko")] - pub (crate) fn prioritize_first_generic_or_prepend(&mut self, generic: GenericFontFamily) { - let index_of_first_generic = self.iter().position(|f| { - match *f { - SingleFontFamily::Generic(f) => f.valid_for_user_font_prioritization(), - _ => false, - } - }); + pub(crate) fn prioritize_first_generic_or_prepend(&mut self, generic: GenericFontFamily) { + let index_of_first_generic = self.iter().position(|f| match *f { + SingleFontFamily::Generic(f) => f.valid_for_user_font_prioritization(), + _ => false, + }); if let Some(0) = index_of_first_generic { return; // Already first diff --git a/components/style/values/computed/image.rs b/components/style/values/computed/image.rs index a0cb8f3fe45..980017b2822 100644 --- a/components/style/values/computed/image.rs +++ b/components/style/values/computed/image.rs @@ -84,7 +84,6 @@ impl ToComputedValue for specified::ImageSet { let mut selected_resolution = items[0].resolution.dppx(); for (i, item) in items.iter().enumerate() { - // 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) { continue; diff --git a/components/style/values/computed/length.rs b/components/style/values/computed/length.rs index f455da5f676..b8ff80587e6 100644 --- a/components/style/values/computed/length.rs +++ b/components/style/values/computed/length.rs @@ -37,7 +37,9 @@ impl ToComputedValue for specified::NoCalcLength { length.to_computed_value(context, FontBaseSize::CurrentStyle) }, 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()) }, specified::NoCalcLength::ServoCharacterWidth(length) => { @@ -191,7 +193,7 @@ impl Size { GenericSize::MaxContent | GenericSize::FitContent | GenericSize::MozAvailable | - GenericSize::FitContentFunction(_) => false + GenericSize::FitContentFunction(_) => false, } } } diff --git a/components/style/values/computed/mod.rs b/components/style/values/computed/mod.rs index 9d775b45cd4..ad7663804be 100644 --- a/components/style/values/computed/mod.rs +++ b/components/style/values/computed/mod.rs @@ -62,7 +62,7 @@ pub use self::font::{FontSize, FontSizeAdjust, FontStretch, FontSynthesis}; pub use self::font::{FontVariantAlternates, FontWeight}; pub use self::font::{FontVariantEastAsian, FontVariationSettings}; 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::{Length, LengthOrNumber, LengthPercentage, NonNegativeLengthOrNumber}; pub use self::length::{LengthOrAuto, LengthPercentageOrAuto, MaxSize, Size}; diff --git a/components/style/values/computed/text.rs b/components/style/values/computed/text.rs index 629626b06b3..0920156108f 100644 --- a/components/style/values/computed/text.rs +++ b/components/style/values/computed/text.rs @@ -18,7 +18,9 @@ use crate::Zero; use std::fmt::{self, Write}; 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::{TextDecorationLine, TextEmphasisPosition}; pub use crate::values::specified::{TextDecorationSkipInk, TextJustify, TextTransform}; diff --git a/components/style/values/computed/transform.rs b/components/style/values/computed/transform.rs index 5eafa0cd627..d70349ee0fe 100644 --- a/components/style/values/computed/transform.rs +++ b/components/style/values/computed/transform.rs @@ -520,7 +520,7 @@ impl ToAnimatedZero for TransformOperation { Ok(generic::TransformOperation::Rotate(Angle::zero())) }, generic::TransformOperation::Perspective(_) => Ok( - generic::TransformOperation::Perspective(generic::PerspectiveFunction::None) + generic::TransformOperation::Perspective(generic::PerspectiveFunction::None), ), generic::TransformOperation::AccumulateMatrix { .. } | generic::TransformOperation::InterpolateMatrix { .. } => { diff --git a/components/style/values/generics/counters.rs b/components/style/values/generics/counters.rs index e5656faea56..2d9948cef4a 100644 --- a/components/style/values/generics/counters.rs +++ b/components/style/values/generics/counters.rs @@ -11,8 +11,8 @@ use crate::values::generics::CounterStyle; #[cfg(any(feature = "gecko", feature = "servo-layout-2020"))] use crate::values::specified::Attr; use crate::values::CustomIdent; -use std::ops::Deref; use std::fmt::{self, Write}; +use std::ops::Deref; use style_traits::{CssWriter, ToCss}; /// A name / value pair for counters. @@ -238,15 +238,7 @@ impl Content { /// Items for the `content` property. #[derive( - Clone, - Debug, - Eq, - MallocSizeOf, - PartialEq, - ToComputedValue, - ToCss, - ToResolvedValue, - ToShmem, + Clone, Debug, Eq, MallocSizeOf, PartialEq, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(u8)] pub enum GenericContentItem { diff --git a/components/style/values/generics/image.rs b/components/style/values/generics/image.rs index 014ae46db02..fa53dd6ac8b 100644 --- a/components/style/values/generics/image.rs +++ b/components/style/values/generics/image.rs @@ -131,9 +131,7 @@ pub struct GenericImageSet { } /// An optional percent and a cross fade image. -#[derive( - Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToResolvedValue, ToShmem, -)] +#[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToResolvedValue, ToShmem)] #[repr(C)] pub struct GenericImageSetItem { /// ``. `` is converted to `Image::Url` at parse time. @@ -151,8 +149,7 @@ pub struct GenericImageSetItem { pub has_mime_type: bool, } -impl ToCss for GenericImageSetItem -{ +impl ToCss for GenericImageSetItem { fn to_css(&self, dest: &mut CssWriter) -> fmt::Result where W: fmt::Write, diff --git a/components/style/values/generics/mod.rs b/components/style/values/generics/mod.rs index c0cdf04b71d..b15d4f01887 100644 --- a/components/style/values/generics/mod.rs +++ b/components/style/values/generics/mod.rs @@ -106,7 +106,7 @@ impl CounterStyle { name == &atom!("square") || name == &atom!("disclosure-closed") || name == &atom!("disclosure-open") - } + }, _ => false, } } diff --git a/components/style/values/generics/transform.rs b/components/style/values/generics/transform.rs index 604872ba5dc..816dde92e4f 100644 --- a/components/style/values/generics/transform.rs +++ b/components/style/values/generics/transform.rs @@ -733,7 +733,7 @@ where dest.write_char(' ')?; z.to_css(dest)?; dest.write_char(' ')?; - } + }, } angle.to_css(dest) }, diff --git a/components/style/values/generics/ui.rs b/components/style/values/generics/ui.rs index ff6aefdc63e..4d9515199ad 100644 --- a/components/style/values/generics/ui.rs +++ b/components/style/values/generics/ui.rs @@ -56,15 +56,7 @@ impl ToCss for Cursor { } /// A generic value for item of `image cursors`. -#[derive( - Clone, - Debug, - MallocSizeOf, - PartialEq, - ToComputedValue, - ToResolvedValue, - ToShmem, -)] +#[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToResolvedValue, ToShmem)] #[repr(C)] pub struct GenericCursorImage { /// The url to parse images from. diff --git a/components/style/values/mod.rs b/components/style/values/mod.rs index b8e7f1f3b8b..626fc32ff18 100644 --- a/components/style/values/mod.rs +++ b/components/style/values/mod.rs @@ -547,9 +547,7 @@ impl Parse for TimelineOrKeyframesName { s, &["none"], )?)), - Token::QuotedString(ref s) => { - Ok(Self::QuotedString(Atom::from(s.as_ref()))) - }, + Token::QuotedString(ref s) => Ok(Self::QuotedString(Atom::from(s.as_ref()))), ref t => Err(location.new_unexpected_token_error(t.clone())), } } diff --git a/components/style/values/resolved/color.rs b/components/style/values/resolved/color.rs index dbf6375e5bf..ea912945c5a 100644 --- a/components/style/values/resolved/color.rs +++ b/components/style/values/resolved/color.rs @@ -40,6 +40,8 @@ impl ToResolvedValue for computed::CaretColor { #[inline] 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), + )) } } diff --git a/components/style/values/resolved/counters.rs b/components/style/values/resolved/counters.rs index cdaebcdea3e..e246dd567f9 100644 --- a/components/style/values/resolved/counters.rs +++ b/components/style/values/resolved/counters.rs @@ -31,19 +31,22 @@ impl ToResolvedValue for computed::Content { #[inline] fn to_resolved_value(self, context: &Context) -> Self { - let (is_pseudo, is_before_or_after, is_marker) = - match context.style.pseudo() { - Some(ref pseudo) => (true, pseudo.is_before_or_after(), pseudo.is_marker()), - None => (false, false, false) - }; + let (is_pseudo, is_before_or_after, is_marker) = match context.style.pseudo() { + Some(ref pseudo) => (true, pseudo.is_before_or_after(), pseudo.is_marker()), + None => (false, false, false), + }; match self { Self::Normal if is_before_or_after => Self::None, // For now, make `content: none` compute to `normal` for pseudos // other than ::before, ::after and ::marker, as we don't respect it. // https://github.com/w3c/csswg-drafts/issues/6124 // Ditto for non-pseudo elements if the pref is disabled. - Self::None if (is_pseudo && !is_before_or_after && !is_marker) || - (!is_pseudo && !allow_element_content_none()) => Self::Normal, + Self::None + if (is_pseudo && !is_before_or_after && !is_marker) || + (!is_pseudo && !allow_element_content_none()) => + { + Self::Normal + }, other => other, } } diff --git a/components/style/values/specified/box.rs b/components/style/values/specified/box.rs index 7d5543cf7fc..67e90c0a8a2 100644 --- a/components/style/values/specified/box.rs +++ b/components/style/values/specified/box.rs @@ -1954,7 +1954,10 @@ impl BreakBetween { /// See https://drafts.csswg.org/css-break/#page-break-properties. #[cfg(feature = "gecko")] #[inline] - pub(crate) fn parse_legacy<'i>(_: &ParserContext, input: &mut Parser<'i, '_>) -> Result> { + pub(crate) fn parse_legacy<'i>( + _: &ParserContext, + input: &mut Parser<'i, '_>, + ) -> Result> { let break_value = BreakBetween::parse(input)?; match break_value { BreakBetween::Always => Ok(BreakBetween::Page), @@ -2018,7 +2021,10 @@ impl BreakWithin { /// See https://drafts.csswg.org/css-break/#page-break-properties. #[cfg(feature = "gecko")] #[inline] - pub(crate) fn parse_legacy<'i>(_: &ParserContext, input: &mut Parser<'i, '_>) -> Result> { + pub(crate) fn parse_legacy<'i>( + _: &ParserContext, + input: &mut Parser<'i, '_>, + ) -> Result> { let break_value = BreakWithin::parse(input)?; match break_value { BreakWithin::Auto | BreakWithin::Avoid => Ok(break_value), diff --git a/components/style/values/specified/calc.rs b/components/style/values/specified/calc.rs index a043e4ea96e..d6997934554 100644 --- a/components/style/values/specified/calc.rs +++ b/components/style/values/specified/calc.rs @@ -380,43 +380,47 @@ impl CalcNode { Ok(Self::MinMax(arguments.into(), op)) }, - MathFunction::Sin | - MathFunction::Cos | - MathFunction::Tan => { + MathFunction::Sin | MathFunction::Cos | MathFunction::Tan => { let argument = Self::parse_argument(context, input, CalcUnit::Angle)?; let radians = match argument.to_number() { Ok(v) => v, Err(()) => match argument.to_angle() { Ok(angle) => angle.radians(), - Err(()) => return Err( - input.new_custom_error(StyleParseErrorKind::UnspecifiedError) - ), + Err(()) => { + return Err( + input.new_custom_error(StyleParseErrorKind::UnspecifiedError) + ) + }, }, }; let number = match function { MathFunction::Sin => radians.sin(), MathFunction::Cos => radians.cos(), MathFunction::Tan => radians.tan(), - _ => unsafe { debug_unreachable!("We just checked!"); }, + _ => unsafe { + debug_unreachable!("We just checked!"); + }, }; Ok(Self::Leaf(Leaf::Number(number))) }, - MathFunction::Asin | - MathFunction::Acos | - MathFunction::Atan => { + MathFunction::Asin | MathFunction::Acos | MathFunction::Atan => { let argument = Self::parse_argument(context, input, CalcUnit::Number)?; let number = match argument.to_number() { Ok(v) => v, - Err(()) => return Err( - input.new_custom_error(StyleParseErrorKind::UnspecifiedError) - ), + Err(()) => { + return Err( + input.new_custom_error(StyleParseErrorKind::UnspecifiedError) + ) + }, }; let radians = match function { MathFunction::Asin => number.asin(), MathFunction::Acos => number.acos(), 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)))) @@ -597,7 +601,9 @@ impl CalcNode { let function = match MathFunction::from_ident(&*name) { 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() { diff --git a/components/style/values/specified/color.rs b/components/style/values/specified/color.rs index c2f5df4bf32..3629b17058f 100644 --- a/components/style/values/specified/color.rs +++ b/components/style/values/specified/color.rs @@ -453,13 +453,12 @@ pub enum SystemColor { impl SystemColor { #[inline] fn compute(&self, cx: &Context) -> ComputedColor { - use crate::gecko_bindings::bindings; use crate::gecko::values::convert_nscolor_to_rgba; + use crate::gecko_bindings::bindings; // TODO: We should avoid cloning here most likely, though it's // cheap-ish. - let style_color_scheme = - cx.style().get_inherited_ui().clone_color_scheme(); + let style_color_scheme = cx.style().get_inherited_ui().clone_color_scheme(); let color = cx.device().system_nscolor(*self, &style_color_scheme); if color == bindings::NS_SAME_AS_FOREGROUND_COLOR { return ComputedColor::currentcolor(); @@ -932,7 +931,10 @@ impl ColorScheme { } impl Parse for ColorScheme { - fn parse<'i, 't>(_: &ParserContext, input: &mut Parser<'i, 't>) -> Result> { + fn parse<'i, 't>( + _: &ParserContext, + input: &mut Parser<'i, 't>, + ) -> Result> { let mut idents = vec![]; let mut bits = ColorSchemeFlags::empty(); diff --git a/components/style/values/specified/counters.rs b/components/style/values/specified/counters.rs index c9507ce8383..91fd7e77078 100644 --- a/components/style/values/specified/counters.rs +++ b/components/style/values/specified/counters.rs @@ -22,7 +22,11 @@ use selectors::parser::SelectorParseErrorKind; use style_traits::{KeywordsCollectFn, ParseError, SpecifiedValueInfo, StyleParseErrorKind}; #[derive(PartialEq)] -enum CounterType { Increment, Set, Reset, } +enum CounterType { + Increment, + Set, + Reset, +} impl CounterType { fn default_value(&self) -> i32 { @@ -41,7 +45,11 @@ impl Parse for CounterIncrement { context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result> { - 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, input: &mut Parser<'i, 't>, ) -> Result> { - 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 { let location = input.current_source_location(); let (name, is_reversed) = match input.next() { - Ok(&Token::Ident(ref ident)) => (CustomIdent::from_ident(location, ident, &["none"])?, false), - Ok(&Token::Function(ref name)) if counter_type == CounterType::Reset && name.eq_ignore_ascii_case("reversed") => { + Ok(&Token::Ident(ref ident)) => { + (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| { 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) => { let t = t.clone(); 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)) { - Ok(start) => + Ok(start) => { if start.value == i32::min_value() { // The spec says that values must be clamped to the valid range, // 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) } else { 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() { diff --git a/components/style/values/specified/font.rs b/components/style/values/specified/font.rs index e78fec45d02..d11a2411a5d 100644 --- a/components/style/values/specified/font.rs +++ b/components/style/values/specified/font.rs @@ -8,16 +8,18 @@ use crate::context::QuirksMode; use crate::parser::{Parse, ParserContext}; 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::{Angle as ComputedAngle, Percentage as ComputedPercentage}; 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::{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::specified::length::{FontBaseSize, PX_PER_PT}; 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::Atom; use cssparser::{Parser, Token}; @@ -406,7 +408,9 @@ impl ToComputedValue for FontStyle { /// /// https://drafts.csswg.org/css-fonts-4/#font-stretch-prop #[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)] pub enum FontStretch { Stretch(NonNegativePercentage), @@ -510,7 +514,9 @@ impl ToComputedValue for FontStretch { } 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, input: &mut Parser<'i, 't>, ) -> Result> { - 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 { #[cfg(feature = "gecko")] 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 -#[derive( - Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss, ToShmem, -)] +#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss, ToShmem)] #[allow(missing_docs)] pub enum FontSizeAdjust { Value(GenericFontSizeAdjust), @@ -804,7 +809,9 @@ impl Parse for FontSizeAdjust { } // Without a basis keyword, the number refers to the 'ex-height' metric. 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( - Clone, - Copy, - Debug, - MallocSizeOf, - PartialEq, - ToComputedValue, - ToResolvedValue, - ToShmem, + Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToResolvedValue, ToShmem, )] /// 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 @@ -2102,11 +2102,7 @@ impl ToCss for FontSynthesis { impl SpecifiedValueInfo for FontSynthesis { fn collect_completion_keywords(f: KeywordsCollectFn) { - f(&[ - "none", - "weight", - "style", - ]); + f(&["none", "weight", "style"]); if allow_font_synthesis_small_caps() { f(&["small-caps"]); } @@ -2319,7 +2315,9 @@ impl Parse for VariationValue { /// A metrics override value for a @font-face descriptor /// /// 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 { /// A non-negative `` of the computed font size Override(NonNegativePercentage), diff --git a/components/style/values/specified/gecko.rs b/components/style/values/specified/gecko.rs index 9b01cc2a6c4..e721add59cf 100644 --- a/components/style/values/specified/gecko.rs +++ b/components/style/values/specified/gecko.rs @@ -52,7 +52,9 @@ impl Parse for IntersectionObserverRootMargin { use crate::Zero; if input.is_exhausted() { // 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)?; Ok(IntersectionObserverRootMargin(rect)) diff --git a/components/style/values/specified/image.rs b/components/style/values/specified/image.rs index 095ce20f4c7..f027c69f03a 100644 --- a/components/style/values/specified/image.rs +++ b/components/style/values/specified/image.rs @@ -181,7 +181,13 @@ impl Parse for Image { context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result> { - 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, ) -> Result> { 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)); } @@ -374,7 +383,9 @@ impl ImageSet { } } 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 { selected_index: 0, @@ -386,9 +397,7 @@ impl ImageSet { impl ImageSetItem { fn parse_type<'i>(p: &mut Parser<'i, '_>) -> Result> { p.expect_function_matching("type")?; - p.parse_nested_block(|input| { - Ok(input.expect_string()?.as_ref().to_owned().into()) - }) + p.parse_nested_block(|input| Ok(input.expect_string()?.as_ref().to_owned().into())) } fn parse<'i, 't>( @@ -404,23 +413,33 @@ impl ImageSetItem { 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(); // Try to parse resolution after type(). 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 has_mime_type = mime_type.is_some(); 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, + }) } } diff --git a/components/style/values/specified/mod.rs b/components/style/values/specified/mod.rs index 8923a868a7c..7cb34ca9a23 100644 --- a/components/style/values/specified/mod.rs +++ b/components/style/values/specified/mod.rs @@ -55,7 +55,7 @@ pub use self::font::{FontVariantAlternates, FontWeight}; pub use self::font::{FontVariantEastAsian, FontVariationSettings}; pub use self::font::{MathDepth, MozScriptMinSize, MozScriptSizeMultiplier, XLang, XTextZoom}; 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::{FontRelativeLength, Length, LengthOrNumber, NonNegativeLengthOrNumber}; 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::outline::OutlineStyle; 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::{ 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::{SVGPaintOrder, SVGStrokeDashArray, SVGWidth}; pub use self::svg_path::SVGPathData; +pub use self::text::RubyPosition; pub use self::text::TextAlignLast; pub use self::text::TextUnderlinePosition; -pub use self::text::RubyPosition; pub use self::text::{InitialLetter, LetterSpacing, LineBreak, LineHeight, TextAlign}; pub use self::text::{OverflowWrap, TextEmphasisPosition, TextEmphasisStyle, WordBreak}; pub use self::text::{TextAlignKeyword, TextDecorationLine, TextOverflow, WordSpacing}; diff --git a/components/style/values/specified/svg_path.rs b/components/style/values/specified/svg_path.rs index a443a443326..b251ce900ce 100644 --- a/components/style/values/specified/svg_path.rs +++ b/components/style/values/specified/svg_path.rs @@ -85,7 +85,7 @@ impl SVGPathData { absolute: IsAbsolute::new(seg_type == PATHSEG_MOVETO_ABS), }); i = i + 2; - } + }, PATHSEG_LINETO_ABS | PATHSEG_LINETO_REL => { debug_assert!(i + 1 < path.len()); result.push(PathCommand::LineTo { @@ -93,7 +93,7 @@ impl SVGPathData { absolute: IsAbsolute::new(seg_type == PATHSEG_LINETO_ABS), }); i = i + 2; - } + }, PATHSEG_CURVETO_CUBIC_ABS | PATHSEG_CURVETO_CUBIC_REL => { debug_assert!(i + 5 < path.len()); result.push(PathCommand::CurveTo { @@ -103,7 +103,7 @@ impl SVGPathData { absolute: IsAbsolute::new(seg_type == PATHSEG_CURVETO_CUBIC_ABS), }); i = i + 6; - } + }, PATHSEG_CURVETO_QUADRATIC_ABS | PATHSEG_CURVETO_QUADRATIC_REL => { debug_assert!(i + 3 < path.len()); result.push(PathCommand::QuadBezierCurveTo { @@ -112,7 +112,7 @@ impl SVGPathData { absolute: IsAbsolute::new(seg_type == PATHSEG_CURVETO_QUADRATIC_ABS), }); i = i + 4; - } + }, PATHSEG_ARC_ABS | PATHSEG_ARC_REL => { debug_assert!(i + 6 < path.len()); result.push(PathCommand::EllipticalArc { @@ -125,7 +125,7 @@ impl SVGPathData { absolute: IsAbsolute::new(seg_type == PATHSEG_ARC_ABS), }); i = i + 7; - } + }, PATHSEG_LINETO_HORIZONTAL_ABS | PATHSEG_LINETO_HORIZONTAL_REL => { debug_assert!(i < path.len()); result.push(PathCommand::HorizontalLineTo { @@ -133,7 +133,7 @@ impl SVGPathData { absolute: IsAbsolute::new(seg_type == PATHSEG_LINETO_HORIZONTAL_ABS), }); i = i + 1; - } + }, PATHSEG_LINETO_VERTICAL_ABS | PATHSEG_LINETO_VERTICAL_REL => { debug_assert!(i < path.len()); result.push(PathCommand::VerticalLineTo { @@ -141,7 +141,7 @@ impl SVGPathData { absolute: IsAbsolute::new(seg_type == PATHSEG_LINETO_VERTICAL_ABS), }); i = i + 1; - } + }, PATHSEG_CURVETO_CUBIC_SMOOTH_ABS | PATHSEG_CURVETO_CUBIC_SMOOTH_REL => { debug_assert!(i + 3 < path.len()); result.push(PathCommand::SmoothCurveTo { @@ -150,7 +150,7 @@ impl SVGPathData { absolute: IsAbsolute::new(seg_type == PATHSEG_CURVETO_CUBIC_SMOOTH_ABS), }); i = i + 4; - } + }, PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS | PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL => { debug_assert!(i + 1 < path.len()); result.push(PathCommand::SmoothQuadBezierCurveTo { @@ -158,7 +158,7 @@ impl SVGPathData { absolute: IsAbsolute::new(seg_type == PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS), }); i = i + 2; - } + }, PATHSEG_UNKNOWN | _ => return Err(()), } } diff --git a/components/style/values/specified/text.rs b/components/style/values/specified/text.rs index ce652734060..893c5232c5e 100644 --- a/components/style/values/specified/text.rs +++ b/components/style/values/specified/text.rs @@ -1061,7 +1061,6 @@ impl Default for MozControlCharacterVisibility { } } - /// Values for the `line-break` property. #[repr(u8)] #[derive( @@ -1259,15 +1258,7 @@ impl ToCss for TextUnderlinePosition { /// Values for `ruby-position` property #[repr(u8)] #[derive( - Clone, - Copy, - Debug, - Eq, - MallocSizeOf, - PartialEq, - ToComputedValue, - ToResolvedValue, - ToShmem, + Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, ToComputedValue, ToResolvedValue, ToShmem, )] #[allow(missing_docs)] pub enum RubyPosition { @@ -1283,7 +1274,9 @@ impl Parse for RubyPosition { input: &mut Parser<'i, 't>, ) -> Result> { // 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() { return Ok(RubyPosition::AlternateOver); } @@ -1294,7 +1287,9 @@ impl Parse for RubyPosition { }; // Parse alternate after 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) { (true, true) => RubyPosition::AlternateOver, diff --git a/components/style/values/specified/ui.rs b/components/style/values/specified/ui.rs index 4594cbfcc77..07463efe66a 100644 --- a/components/style/values/specified/ui.rs +++ b/components/style/values/specified/ui.rs @@ -11,7 +11,9 @@ use crate::values::specified::image::Image; use crate::values::specified::Number; use cssparser::Parser; 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. pub type Cursor = generics::GenericCursor;