style: Rustfmt recent changes.

This commit is contained in:
Emilio Cobos Álvarez 2020-02-10 16:50:57 +01:00
parent 1754c832d8
commit 071ce6f345
No known key found for this signature in database
GPG key ID: E1152D0994E4BF8A
22 changed files with 210 additions and 163 deletions

View file

@ -12,7 +12,9 @@ use crate::properties::{CSSWideKeyword, CustomDeclaration, CustomDeclarationValu
use crate::selector_map::{PrecomputedHashMap, PrecomputedHashSet, PrecomputedHasher}; use crate::selector_map::{PrecomputedHashMap, PrecomputedHashSet, PrecomputedHasher};
use crate::stylesheets::{Origin, PerOrigin}; use crate::stylesheets::{Origin, PerOrigin};
use crate::Atom; use crate::Atom;
use cssparser::{CowRcStr, Delimiter, Parser, ParserInput, SourcePosition, Token, TokenSerializationType}; use cssparser::{
CowRcStr, Delimiter, Parser, ParserInput, SourcePosition, Token, TokenSerializationType,
};
use indexmap::IndexMap; use indexmap::IndexMap;
use selectors::parser::SelectorParseErrorKind; use selectors::parser::SelectorParseErrorKind;
use servo_arc::Arc; use servo_arc::Arc;
@ -525,10 +527,7 @@ pub struct CustomPropertiesBuilder<'a> {
impl<'a> CustomPropertiesBuilder<'a> { impl<'a> CustomPropertiesBuilder<'a> {
/// Create a new builder, inheriting from a given custom properties map. /// Create a new builder, inheriting from a given custom properties map.
pub fn new( pub fn new(inherited: Option<&'a Arc<CustomPropertiesMap>>, device: &'a Device) -> Self {
inherited: Option<&'a Arc<CustomPropertiesMap>>,
device: &'a Device,
) -> Self {
Self { Self {
seen: PrecomputedHashSet::default(), seen: PrecomputedHashSet::default(),
reverted: Default::default(), reverted: Default::default(),
@ -576,8 +575,7 @@ impl<'a> CustomPropertiesBuilder<'a> {
// environment variable here, perform substitution here instead // environment variable here, perform substitution here instead
// of forcing a full traversal in `substitute_all` afterwards. // of forcing a full traversal in `substitute_all` afterwards.
let value = if !has_references && unparsed_value.references_environment { let value = if !has_references && unparsed_value.references_environment {
let result = let result = substitute_references_in_value(unparsed_value, &map, &self.device);
substitute_references_in_value(unparsed_value, &map, &self.device);
match result { match result {
Ok(new_value) => Arc::new(new_value), Ok(new_value) => Arc::new(new_value),
Err(..) => { Err(..) => {

View file

@ -138,7 +138,8 @@ impl Device {
/// Set the font size of the root element (for rem) /// Set the font size of the root element (for rem)
pub fn set_root_font_size(&self, size: Au) { pub fn set_root_font_size(&self, size: Au) {
self.root_font_size.store(size.0 as isize, Ordering::Relaxed) self.root_font_size
.store(size.0 as isize, Ordering::Relaxed)
} }
/// Sets the body text color for the "inherit color from body" quirk. /// Sets the body text color for the "inherit color from body" quirk.

View file

@ -706,7 +706,10 @@ pub trait MatchMethods: TElement {
let new_primary_style = data.styles.primary.as_ref().unwrap(); let new_primary_style = data.styles.primary.as_ref().unwrap();
let mut cascade_requirement = ChildCascadeRequirement::CanSkipCascade; let mut cascade_requirement = ChildCascadeRequirement::CanSkipCascade;
if new_primary_style.flags.contains(ComputedValueFlags::IS_ROOT_ELEMENT_STYLE) { if new_primary_style
.flags
.contains(ComputedValueFlags::IS_ROOT_ELEMENT_STYLE)
{
let device = context.shared.stylist.device(); let device = context.shared.stylist.device();
let new_font_size = new_primary_style.get_font().clone_font_size(); let new_font_size = new_primary_style.get_font().clone_font_size();

View file

@ -1767,12 +1767,19 @@ impl Drop for StrongRuleNode {
crash_str.push(b'\n'); crash_str.push(b'\n');
} }
children.each(|child| { children.each(|child| {
(*child.ptr()).source.as_ref().unwrap().dump_unchecked(&mut crash_str); (*child.ptr())
.source
.as_ref()
.unwrap()
.dump_unchecked(&mut crash_str);
crash_str.push(b'\n'); crash_str.push(b'\n');
}); });
} }
panic!("Children left in the rule tree on drop: {}", String::from_utf8_lossy(&crash_str).trim()); panic!(
"Children left in the rule tree on drop: {}",
String::from_utf8_lossy(&crash_str).trim()
);
} }
} }

View file

@ -16,7 +16,7 @@ use crate::values::KeyframesName;
use app_units::Au; use app_units::Au;
use cssparser::RGBA; use cssparser::RGBA;
use euclid::default::Size2D as UntypedSize2D; use euclid::default::Size2D as UntypedSize2D;
use euclid::{Scale, Size2D, SideOffsets2D}; use euclid::{Scale, SideOffsets2D, Size2D};
use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering}; use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering};
use style_traits::viewport::ViewportConstraints; use style_traits::viewport::ViewportConstraints;
use style_traits::{CSSPixel, DevicePixel}; use style_traits::{CSSPixel, DevicePixel};

View file

@ -173,7 +173,7 @@ impl ValidationData {
E: TElement, E: TElement,
{ {
if !element.has_part_attr() { if !element.has_part_attr() {
return &[] return &[];
} }
self.part_list.get_or_insert_with(|| { self.part_list.get_or_insert_with(|| {
let mut list = SmallVec::<[Atom; 5]>::new(); let mut list = SmallVec::<[Atom; 5]>::new();

View file

@ -204,7 +204,10 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
self.style.pseudo.map_or(false, |p| p.is_marker()) && self.style.pseudo.map_or(false, |p| p.is_marker()) &&
self.style.get_parent_list().clone_list_style_position() == self.style.get_parent_list().clone_list_style_position() ==
ListStylePosition::Outside && ListStylePosition::Outside &&
!layout_parent_style.get_box().clone_display().is_inline_flow() !layout_parent_style
.get_box()
.clone_display()
.is_inline_flow()
); );
if !blockify { if !blockify {
@ -241,7 +244,8 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
} }
if self.style.is_root_element { if self.style.is_root_element {
self.style.add_flags(ComputedValueFlags::IS_ROOT_ELEMENT_STYLE); self.style
.add_flags(ComputedValueFlags::IS_ROOT_ELEMENT_STYLE);
} }
#[cfg(feature = "servo-layout-2013")] #[cfg(feature = "servo-layout-2013")]
@ -285,8 +289,10 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> {
let writing_mode = self.style.get_inherited_box().clone_writing_mode(); let writing_mode = self.style.get_inherited_box().clone_writing_mode();
let text_combine_upright = self.style.get_inherited_text().clone_text_combine_upright(); let text_combine_upright = self.style.get_inherited_text().clone_text_combine_upright();
if matches!(writing_mode, WritingMode::VerticalRl | WritingMode::VerticalLr) && if matches!(
text_combine_upright == TextCombineUpright::All writing_mode,
WritingMode::VerticalRl | WritingMode::VerticalLr
) && text_combine_upright == TextCombineUpright::All
{ {
self.style.add_flags(ComputedValueFlags::IS_TEXT_COMBINED); self.style.add_flags(ComputedValueFlags::IS_TEXT_COMBINED);
self.style self.style

View file

@ -30,6 +30,10 @@ impl Animate for LengthPercentage {
// Gets clamped as needed after the animation if needed, so no need to // Gets clamped as needed after the animation if needed, so no need to
// specify any particular AllowedNumericType. // specify any particular AllowedNumericType.
Ok(LengthPercentage::new_calc(length, percentage, AllowedNumericType::All)) Ok(LengthPercentage::new_calc(
length,
percentage,
AllowedNumericType::All,
))
} }
} }

View file

@ -9,7 +9,9 @@
use crate::values::computed::{Context, ToComputedValue}; use crate::values::computed::{Context, ToComputedValue};
use crate::values::specified; use crate::values::specified;
pub use super::specified::{AlignContent, AlignItems, ContentDistribution, JustifyContent, SelfAlignment}; pub use super::specified::{
AlignContent, AlignItems, ContentDistribution, JustifyContent, SelfAlignment,
};
pub use super::specified::{AlignSelf, JustifySelf}; pub use super::specified::{AlignSelf, JustifySelf};
/// The computed value for the `justify-items` property. /// The computed value for the `justify-items` property.

View file

@ -21,9 +21,9 @@ use std::ops::{Add, AddAssign, Div, Mul, Neg, Sub};
use style_traits::{CSSPixel, CssWriter, ToCss}; use style_traits::{CSSPixel, CssWriter, ToCss};
pub use super::image::Image; pub use super::image::Image;
pub use super::length_percentage::{LengthPercentage, NonNegativeLengthPercentage};
pub use crate::values::specified::url::UrlOrNone; pub use crate::values::specified::url::UrlOrNone;
pub use crate::values::specified::{Angle, BorderStyle, Time}; pub use crate::values::specified::{Angle, BorderStyle, Time};
pub use super::length_percentage::{LengthPercentage, NonNegativeLengthPercentage};
impl ToComputedValue for specified::NoCalcLength { impl ToComputedValue for specified::NoCalcLength {
type ComputedValue = Length; type ComputedValue = Length;
@ -57,7 +57,9 @@ impl ToComputedValue for specified::Length {
fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
match *self { match *self {
specified::Length::NoCalc(l) => l.to_computed_value(context), specified::Length::NoCalc(l) => l.to_computed_value(context),
specified::Length::Calc(ref calc) => calc.to_computed_value(context).to_length().unwrap(), specified::Length::Calc(ref calc) => {
calc.to_computed_value(context).to_length().unwrap()
},
} }
} }

View file

@ -33,13 +33,13 @@ use crate::values::{specified, CSSFloat};
use crate::Zero; use crate::Zero;
use app_units::Au; use app_units::Au;
use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
use serde::{Serialize, Deserialize}; use serde::{Deserialize, Serialize};
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use style_traits::values::specified::AllowedNumericType; use style_traits::values::specified::AllowedNumericType;
use style_traits::{CssWriter, ToCss}; use style_traits::{CssWriter, ToCss};
#[doc(hidden)] #[doc(hidden)]
#[derive(Copy, Clone)] #[derive(Clone, Copy)]
#[repr(C)] #[repr(C)]
pub struct LengthVariant { pub struct LengthVariant {
tag: u32, tag: u32,
@ -47,7 +47,7 @@ pub struct LengthVariant {
} }
#[doc(hidden)] #[doc(hidden)]
#[derive(Copy, Clone)] #[derive(Clone, Copy)]
#[repr(C)] #[repr(C)]
pub struct PercentageVariant { pub struct PercentageVariant {
tag: u32, tag: u32,
@ -57,7 +57,7 @@ pub struct PercentageVariant {
// NOTE(emilio): cbindgen only understands the #[cfg] on the top level // NOTE(emilio): cbindgen only understands the #[cfg] on the top level
// definition. // definition.
#[doc(hidden)] #[doc(hidden)]
#[derive(Copy, Clone)] #[derive(Clone, Copy)]
#[repr(C)] #[repr(C)]
#[cfg(target_pointer_width = "32")] #[cfg(target_pointer_width = "32")]
pub struct CalcVariant { pub struct CalcVariant {
@ -66,7 +66,7 @@ pub struct CalcVariant {
} }
#[doc(hidden)] #[doc(hidden)]
#[derive(Copy, Clone)] #[derive(Clone, Copy)]
#[repr(C)] #[repr(C)]
#[cfg(target_pointer_width = "64")] #[cfg(target_pointer_width = "64")]
pub struct CalcVariant { pub struct CalcVariant {
@ -78,7 +78,7 @@ unsafe impl Send for CalcVariant {}
unsafe impl Sync for CalcVariant {} unsafe impl Sync for CalcVariant {}
#[doc(hidden)] #[doc(hidden)]
#[derive(Copy, Clone)] #[derive(Clone, Copy)]
#[repr(C)] #[repr(C)]
pub struct TagVariant { pub struct TagVariant {
tag: u32, tag: u32,
@ -123,7 +123,7 @@ impl LengthPercentageUnion {
pub const TAG_MASK: u32 = 0b11; pub const TAG_MASK: u32 = 0b11;
} }
#[derive(Copy, Clone, Debug, PartialEq)] #[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u32)] #[repr(u32)]
enum Tag { enum Tag {
Calc = LengthPercentageUnion::TAG_CALC, Calc = LengthPercentageUnion::TAG_CALC,
@ -171,7 +171,7 @@ enum Unpacked<'a> {
/// An unpacked `<length-percentage>` that owns the `calc()` variant, for /// An unpacked `<length-percentage>` that owns the `calc()` variant, for
/// serialization purposes. /// serialization purposes.
#[derive(Deserialize, Serialize, PartialEq)] #[derive(Deserialize, PartialEq, Serialize)]
enum Serializable { enum Serializable {
Calc(CalcLengthPercentage), Calc(CalcLengthPercentage),
Length(Length), Length(Length),
@ -192,7 +192,7 @@ impl LengthPercentage {
length: LengthVariant { length: LengthVariant {
tag: LengthPercentageUnion::TAG_LENGTH, tag: LengthPercentageUnion::TAG_LENGTH,
length, length,
} },
}); });
debug_assert_eq!(length.tag(), Tag::Length); debug_assert_eq!(length.tag(), Tag::Length);
length length
@ -205,7 +205,7 @@ impl LengthPercentage {
percentage: PercentageVariant { percentage: PercentageVariant {
tag: LengthPercentageUnion::TAG_PERCENTAGE, tag: LengthPercentageUnion::TAG_PERCENTAGE,
percentage, percentage,
} },
}); });
debug_assert_eq!(percent.tag(), Tag::Percentage); debug_assert_eq!(percent.tag(), Tag::Percentage);
percent percent
@ -223,7 +223,7 @@ impl LengthPercentage {
None => return Self::new_length(Length::new(clamping_mode.clamp(length.px()))), None => return Self::new_length(Length::new(clamping_mode.clamp(length.px()))),
}; };
if length.is_zero() { if length.is_zero() {
return Self::new_percent(Percentage(clamping_mode.clamp(percentage.0))) return Self::new_percent(Percentage(clamping_mode.clamp(percentage.0)));
} }
Self::new_calc_unchecked(Box::new(CalcLengthPercentage { Self::new_calc_unchecked(Box::new(CalcLengthPercentage {
length, length,
@ -241,7 +241,7 @@ impl LengthPercentage {
#[cfg(target_pointer_width = "32")] #[cfg(target_pointer_width = "32")]
tag: LengthPercentageUnion::TAG_CALC, tag: LengthPercentageUnion::TAG_CALC,
ptr, ptr,
} },
}); });
debug_assert_eq!(calc.tag(), Tag::Calc); debug_assert_eq!(calc.tag(), Tag::Calc);
calc calc
@ -293,7 +293,11 @@ impl LengthPercentage {
Unpacked::Length(l) => l.px() == 0.0, Unpacked::Length(l) => l.px() == 0.0,
Unpacked::Percentage(p) => p.0 == 0.0, Unpacked::Percentage(p) => p.0 == 0.0,
Unpacked::Calc(ref c) => { Unpacked::Calc(ref c) => {
debug_assert_ne!(c.length.px(), 0.0, "Should've been simplified to a percentage"); debug_assert_ne!(
c.length.px(),
0.0,
"Should've been simplified to a percentage"
);
false false
}, },
} }
@ -374,7 +378,7 @@ impl LengthPercentage {
Unpacked::Percentage(..) | Unpacked::Calc(..) => { Unpacked::Percentage(..) | Unpacked::Calc(..) => {
debug_assert!(self.has_percentage()); debug_assert!(self.has_percentage());
return None; return None;
} },
} }
} }
@ -387,7 +391,7 @@ impl LengthPercentage {
Unpacked::Calc(ref c) => { Unpacked::Calc(ref c) => {
debug_assert!(!c.length.is_zero()); debug_assert!(!c.length.is_zero());
None None
} },
} }
} }
@ -400,7 +404,7 @@ impl LengthPercentage {
Unpacked::Calc(ref c) => { Unpacked::Calc(ref c) => {
debug_assert!(self.has_percentage()); debug_assert!(self.has_percentage());
Some(c.percentage) Some(c.percentage)
} },
} }
} }
@ -419,7 +423,8 @@ impl LengthPercentage {
/// Convert the computed value into used value. /// Convert the computed value into used value.
#[inline] #[inline]
pub fn maybe_to_used_value(&self, container_len: Option<Length>) -> Option<Au> { pub fn maybe_to_used_value(&self, container_len: Option<Length>) -> Option<Au> {
self.maybe_percentage_relative_to(container_len).map(Au::from) self.maybe_percentage_relative_to(container_len)
.map(Au::from)
} }
/// If there are special rules for computing percentages in a value (e.g. /// If there are special rules for computing percentages in a value (e.g.
@ -470,7 +475,7 @@ impl Clone for LengthPercentage {
match self.unpack() { match self.unpack() {
Unpacked::Length(l) => Self::new_length(l), Unpacked::Length(l) => Self::new_length(l),
Unpacked::Percentage(p) => Self::new_percent(p), Unpacked::Percentage(p) => Self::new_percent(p),
Unpacked::Calc(c) => Self::new_calc_unchecked(Box::new(c.clone())) Unpacked::Calc(c) => Self::new_calc_unchecked(Box::new(c.clone())),
} }
} }
} }
@ -483,12 +488,8 @@ impl ToComputedValue for specified::LengthPercentage {
specified::LengthPercentage::Length(ref value) => { specified::LengthPercentage::Length(ref value) => {
LengthPercentage::new_length(value.to_computed_value(context)) LengthPercentage::new_length(value.to_computed_value(context))
}, },
specified::LengthPercentage::Percentage(value) => { specified::LengthPercentage::Percentage(value) => LengthPercentage::new_percent(value),
LengthPercentage::new_percent(value) specified::LengthPercentage::Calc(ref calc) => (**calc).to_computed_value(context),
},
specified::LengthPercentage::Calc(ref calc) => {
(**calc).to_computed_value(context)
},
} }
} }
@ -496,15 +497,15 @@ impl ToComputedValue for specified::LengthPercentage {
match computed.unpack() { match computed.unpack() {
Unpacked::Length(ref l) => { Unpacked::Length(ref l) => {
specified::LengthPercentage::Length(ToComputedValue::from_computed_value(l)) specified::LengthPercentage::Length(ToComputedValue::from_computed_value(l))
} },
Unpacked::Percentage(p) => { Unpacked::Percentage(p) => specified::LengthPercentage::Percentage(p),
specified::LengthPercentage::Percentage(p)
}
Unpacked::Calc(c) => { Unpacked::Calc(c) => {
// We simplify before constructing the LengthPercentage if // We simplify before constructing the LengthPercentage if
// needed, so this is always fine. // needed, so this is always fine.
specified::LengthPercentage::Calc(Box::new(specified::CalcLengthPercentage::from_computed_value(c))) specified::LengthPercentage::Calc(Box::new(
} specified::CalcLengthPercentage::from_computed_value(c),
))
},
} }
} }
} }
@ -517,7 +518,8 @@ impl ComputeSquaredDistance for LengthPercentage {
// ensures that the distance between length-only and percentage-only // ensures that the distance between length-only and percentage-only
// lengths makes sense. // lengths makes sense.
let basis = Length::new(100.); let basis = Length::new(100.);
self.resolve(basis).compute_squared_distance(&other.resolve(basis)) self.resolve(basis)
.compute_squared_distance(&other.resolve(basis))
} }
} }
@ -555,14 +557,14 @@ impl<'de> Deserialize<'de> for LengthPercentage {
where where
D: serde::Deserializer<'de>, D: serde::Deserializer<'de>,
{ {
Ok(Self::from_serializable(Serializable::deserialize(deserializer)?)) Ok(Self::from_serializable(Serializable::deserialize(
deserializer,
)?))
} }
} }
/// The representation of a calc() function with mixed lengths and percentages. /// The representation of a calc() function with mixed lengths and percentages.
#[derive( #[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize, ToAnimatedZero, ToResolvedValue)]
Clone, Debug, Deserialize, MallocSizeOf, Serialize, ToAnimatedZero, ToResolvedValue,
)]
#[repr(C)] #[repr(C)]
pub struct CalcLengthPercentage { pub struct CalcLengthPercentage {
length: Length, length: Length,
@ -596,7 +598,11 @@ impl CalcLengthPercentage {
/// Returns the clamped non-negative values. /// Returns the clamped non-negative values.
#[inline] #[inline]
fn clamp_to_non_negative(&self) -> LengthPercentage { fn clamp_to_non_negative(&self) -> LengthPercentage {
LengthPercentage::new_calc(self.length, Some(self.percentage), AllowedNumericType::NonNegative) LengthPercentage::new_calc(
self.length,
Some(self.percentage),
AllowedNumericType::NonNegative,
)
} }
} }
@ -629,8 +635,8 @@ impl specified::CalcLengthPercentage {
where where
F: Fn(Length) -> Length, F: Fn(Length) -> Length,
{ {
use crate::values::specified::length::{FontRelativeLength, ViewportPercentageLength};
use std::f32; use std::f32;
use crate::values::specified::length::{ViewportPercentageLength, FontRelativeLength};
let mut length = 0.; let mut length = 0.;
@ -764,4 +770,3 @@ impl NonNegativeLengthPercentage {
Some(std::cmp::max(resolved, Au(0))) Some(std::cmp::max(resolved, Au(0)))
} }
} }

View file

@ -501,11 +501,9 @@ impl ToComputedValue for specified::AngleOrPercentage {
#[inline] #[inline]
fn from_computed_value(computed: &AngleOrPercentage) -> Self { fn from_computed_value(computed: &AngleOrPercentage) -> Self {
match *computed { match *computed {
AngleOrPercentage::Percentage(percentage) => { AngleOrPercentage::Percentage(percentage) => specified::AngleOrPercentage::Percentage(
specified::AngleOrPercentage::Percentage(ToComputedValue::from_computed_value( ToComputedValue::from_computed_value(&percentage),
&percentage, ),
))
},
AngleOrPercentage::Angle(angle) => { AngleOrPercentage::Angle(angle) => {
specified::AngleOrPercentage::Angle(ToComputedValue::from_computed_value(&angle)) specified::AngleOrPercentage::Angle(ToComputedValue::from_computed_value(&angle))
}, },

View file

@ -145,15 +145,7 @@ fn is_decimal(counter_type: &CounterStyleType) -> bool {
/// ///
/// https://drafts.csswg.org/css-content/#propdef-content /// https://drafts.csswg.org/css-content/#propdef-content
#[derive( #[derive(
Clone, Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss, ToShmem,
Debug,
Eq,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
ToShmem,
)] )]
#[repr(u8)] #[repr(u8)]
pub enum GenericContent<ImageUrl> { pub enum GenericContent<ImageUrl> {

View file

@ -23,8 +23,10 @@ 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_before_or_after = let is_before_or_after = context
context.style.pseudo().map_or(false, |p| p.is_before_or_after()); .style
.pseudo()
.map_or(false, |p| p.is_before_or_after());
match self { match self {
Self::Normal if is_before_or_after => Self::None, Self::Normal if is_before_or_after => Self::None,
@ -43,4 +45,3 @@ impl ToResolvedValue for computed::Content {
resolved resolved
} }
} }

View file

@ -228,9 +228,7 @@ impl Angle {
let function = CalcNode::math_function(name, location)?; let function = CalcNode::math_function(name, location)?;
CalcNode::parse_angle(context, input, function) CalcNode::parse_angle(context, input, function)
}, },
Token::Number { value, .. } if value == 0. && allow_unitless_zero => { Token::Number { value, .. } if value == 0. && allow_unitless_zero => Ok(Angle::zero()),
Ok(Angle::zero())
},
ref t => { ref t => {
let t = t.clone(); let t = t.clone();
Err(input.new_unexpected_token_error(t)) Err(input.new_unexpected_token_error(t))

View file

@ -267,8 +267,7 @@ impl Display {
/// Whether this is `display: inline` (or `inline list-item`). /// Whether this is `display: inline` (or `inline list-item`).
#[inline] #[inline]
pub fn is_inline_flow(&self) -> bool { pub fn is_inline_flow(&self) -> bool {
self.outside() == DisplayOutside::Inline && self.outside() == DisplayOutside::Inline && self.inside() == DisplayInside::Flow
self.inside() == DisplayInside::Flow
} }
/// Returns whether this `display` value is some kind of list-item. /// Returns whether this `display` value is some kind of list-item.

View file

@ -20,7 +20,7 @@ use style_traits::values::specified::AllowedNumericType;
use style_traits::{CssWriter, ParseError, SpecifiedValueInfo, StyleParseErrorKind, ToCss}; use style_traits::{CssWriter, ParseError, SpecifiedValueInfo, StyleParseErrorKind, ToCss};
/// The name of the mathematical function that we're parsing. /// The name of the mathematical function that we're parsing.
#[derive(Debug, Copy, Clone)] #[derive(Clone, Copy, Debug)]
pub enum MathFunction { pub enum MathFunction {
/// `calc()`: https://drafts.csswg.org/css-values-4/#funcdef-calc /// `calc()`: https://drafts.csswg.org/css-values-4/#funcdef-calc
Calc, Calc,
@ -36,7 +36,7 @@ pub enum MathFunction {
/// sum. /// sum.
/// ///
/// See https://drafts.csswg.org/css-values-4/#sort-a-calculations-children /// See https://drafts.csswg.org/css-values-4/#sort-a-calculations-children
#[derive(Debug, Copy, Clone, Eq, Ord, PartialEq, PartialOrd)] #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
enum SortKey { enum SortKey {
Number, Number,
Percentage, Percentage,
@ -55,7 +55,7 @@ enum SortKey {
} }
/// Whether we're a `min` or `max` function. /// Whether we're a `min` or `max` function.
#[derive(Copy, Clone, Debug, PartialEq)] #[derive(Clone, Copy, Debug, PartialEq)]
pub enum MinMaxOp { pub enum MinMaxOp {
/// `min()` /// `min()`
Min, Min,
@ -216,7 +216,11 @@ macro_rules! impl_generic_to_type {
} }
$from_float(sum) $from_float(sum)
}, },
Self::Clamp { ref min, ref center, ref max } => { Self::Clamp {
ref min,
ref center,
ref max,
} => {
let min = min.$to_self()?; let min = min.$to_self()?;
let center = center.$to_self()?; let center = center.$to_self()?;
let max = max.$to_self()?; let max = max.$to_self()?;
@ -265,7 +269,7 @@ macro_rules! impl_generic_to_type {
Self::Percentage(..) | Self::Percentage(..) |
Self::Number(..) => return Err(()), Self::Number(..) => return Err(()),
}) })
}} }};
} }
impl PartialOrd for CalcNode { impl PartialOrd for CalcNode {
@ -327,7 +331,11 @@ impl CalcNode {
} }
}, },
// Multiplication is distributive across these. // Multiplication is distributive across these.
Self::Clamp { ref mut min, ref mut center, ref mut max } => { Self::Clamp {
ref mut min,
ref mut center,
ref mut max,
} => {
min.mul_by(scalar); min.mul_by(scalar);
center.mul_by(scalar); center.mul_by(scalar);
max.mul_by(scalar); max.mul_by(scalar);
@ -345,27 +353,21 @@ impl CalcNode {
Self::Percentage(..) => SortKey::Percentage, Self::Percentage(..) => SortKey::Percentage,
Self::Time(..) => SortKey::Sec, Self::Time(..) => SortKey::Sec,
Self::Angle(..) => SortKey::Deg, Self::Angle(..) => SortKey::Deg,
Self::Length(ref l) => { Self::Length(ref l) => match *l {
match *l {
NoCalcLength::Absolute(..) => SortKey::Px, NoCalcLength::Absolute(..) => SortKey::Px,
NoCalcLength::FontRelative(ref relative) => { NoCalcLength::FontRelative(ref relative) => match *relative {
match *relative {
FontRelativeLength::Ch(..) => SortKey::Ch, FontRelativeLength::Ch(..) => SortKey::Ch,
FontRelativeLength::Em(..) => SortKey::Em, FontRelativeLength::Em(..) => SortKey::Em,
FontRelativeLength::Ex(..) => SortKey::Ex, FontRelativeLength::Ex(..) => SortKey::Ex,
FontRelativeLength::Rem(..) => SortKey::Rem, FontRelativeLength::Rem(..) => SortKey::Rem,
}
}, },
NoCalcLength::ViewportPercentage(ref vp) => { NoCalcLength::ViewportPercentage(ref vp) => match *vp {
match *vp {
ViewportPercentageLength::Vh(..) => SortKey::Vh, ViewportPercentageLength::Vh(..) => SortKey::Vh,
ViewportPercentageLength::Vw(..) => SortKey::Vw, ViewportPercentageLength::Vw(..) => SortKey::Vw,
ViewportPercentageLength::Vmax(..) => SortKey::Vmax, ViewportPercentageLength::Vmax(..) => SortKey::Vmax,
ViewportPercentageLength::Vmin(..) => SortKey::Vmin, ViewportPercentageLength::Vmin(..) => SortKey::Vmin,
}
}, },
NoCalcLength::ServoCharacterWidth(..) => unreachable!(), NoCalcLength::ServoCharacterWidth(..) => unreachable!(),
}
}, },
Self::Sum(..) | Self::MinMax(..) | Self::Clamp { .. } => SortKey::Other, Self::Sum(..) | Self::MinMax(..) | Self::Clamp { .. } => SortKey::Other,
} }
@ -375,22 +377,28 @@ impl CalcNode {
/// ///
/// Only handles leaf nodes, it's the caller's responsibility to simplify /// Only handles leaf nodes, it's the caller's responsibility to simplify
/// them before calling this if needed. /// them before calling this if needed.
fn try_sum_in_place(&mut self, other: &Self) -> Result<(), ()> { use fn try_sum_in_place(&mut self, other: &Self) -> Result<(), ()> {
self::CalcNode::*; use self::CalcNode::*;
match (self, other) { (&mut Number(ref mut one), &Number(ref other)) | match (self, other) {
(&mut Percentage(ref mut one), &Percentage(ref other)) => { *one += (&mut Number(ref mut one), &Number(ref other)) |
*other; } (&mut Angle(ref mut one), &Angle(ref other)) => { *one (&mut Percentage(ref mut one), &Percentage(ref other)) => {
= specified::Angle::from_calc(one.degrees() + *one += *other;
other.degrees()); } (&mut Time(ref mut one), &Time(ref },
other)) => { *one = (&mut Angle(ref mut one), &Angle(ref other)) => {
specified::Time::from_calc(one.seconds() + *one = specified::Angle::from_calc(one.degrees() + other.degrees());
other.seconds()); } (&mut Length(ref mut one), },
&Length(ref other)) => { *one = (&mut Time(ref mut one), &Time(ref other)) => {
one.try_sum(other)?; } _ => return Err(()), *one = specified::Time::from_calc(one.seconds() + other.seconds());
},
(&mut Length(ref mut one), &Length(ref other)) => {
*one = one.try_sum(other)?;
},
_ => return Err(()),
} }
Ok(()) } Ok(())
}
/// Simplifies and sorts the calculation. This is only needed if it's going /// Simplifies and sorts the calculation. This is only needed if it's going
/// to be preserved after parsing (so, for `<length-percentage>`). Otherwise /// to be preserved after parsing (so, for `<length-percentage>`). Otherwise
@ -401,10 +409,14 @@ impl CalcNode {
($slot:expr) => {{ ($slot:expr) => {{
let result = mem::replace($slot, Self::Number(0.)); let result = mem::replace($slot, Self::Number(0.));
mem::replace(self, result); mem::replace(self, result);
}} }};
} }
match *self { match *self {
Self::Clamp { ref mut min, ref mut center, ref mut max } => { Self::Clamp {
ref mut min,
ref mut center,
ref mut max,
} => {
min.simplify_and_sort_children(); min.simplify_and_sort_children();
center.simplify_and_sort_children(); center.simplify_and_sort_children();
max.simplify_and_sort_children(); max.simplify_and_sort_children();
@ -518,10 +530,7 @@ impl CalcNode {
} }
} }
debug_assert!( debug_assert!(children.len() >= 2, "Should still have multiple kids!");
children.len() >= 2,
"Should still have multiple kids!"
);
// Sort by spec order. // Sort by spec order.
children.sort_unstable_by_key(|c| c.calc_node_sort_key()); children.sort_unstable_by_key(|c| c.calc_node_sort_key());
@ -542,11 +551,8 @@ impl CalcNode {
if let NoCalcLength::Absolute(ref mut absolute_length) = *len { if let NoCalcLength::Absolute(ref mut absolute_length) = *len {
*absolute_length = AbsoluteLength::Px(absolute_length.to_px()); *absolute_length = AbsoluteLength::Px(absolute_length.to_px());
} }
} },
Self::Percentage(..) | Self::Percentage(..) | Self::Angle(..) | Self::Time(..) | Self::Number(..) => {
Self::Angle(..) |
Self::Time(..) |
Self::Number(..) => {
// These are leaves already, nothing to do. // These are leaves already, nothing to do.
}, },
} }
@ -604,11 +610,9 @@ impl CalcNode {
(&Token::Percentage { unit_value, .. }, CalcUnit::Percentage) => { (&Token::Percentage { unit_value, .. }, CalcUnit::Percentage) => {
Ok(CalcNode::Percentage(unit_value)) Ok(CalcNode::Percentage(unit_value))
}, },
(&Token::ParenthesisBlock, _) => { (&Token::ParenthesisBlock, _) => input.parse_nested_block(|input| {
input.parse_nested_block(|input| {
CalcNode::parse_argument(context, input, expected_unit) CalcNode::parse_argument(context, input, expected_unit)
}) }),
},
(&Token::Function(ref name), _) => { (&Token::Function(ref name), _) => {
let function = CalcNode::math_function(name, location)?; let function = CalcNode::math_function(name, location)?;
CalcNode::parse(context, input, function, expected_unit) CalcNode::parse(context, input, function, expected_unit)
@ -644,16 +648,17 @@ impl CalcNode {
max: Box::new(max), max: Box::new(max),
}) })
}, },
MathFunction::Min | MathFunction::Min | MathFunction::Max => {
MathFunction::Max => {
// TODO(emilio): The common case for parse_comma_separated // TODO(emilio): The common case for parse_comma_separated
// is just one element, but for min / max is two, really... // is just one element, but for min / max is two, really...
// //
// Consider adding an API to cssparser to specify the // Consider adding an API to cssparser to specify the
// initial vector capacity? // initial vector capacity?
let arguments = input.parse_comma_separated(|input| { let arguments = input
.parse_comma_separated(|input| {
Self::parse_argument(context, input, expected_unit) Self::parse_argument(context, input, expected_unit)
})?.into_boxed_slice(); })?
.into_boxed_slice();
let op = match function { let op = match function {
MathFunction::Min => MinMaxOp::Min, MathFunction::Min => MinMaxOp::Min,
@ -662,7 +667,7 @@ impl CalcNode {
}; };
Ok(Self::MinMax(arguments, op)) Ok(Self::MinMax(arguments, op))
} },
} }
}) })
} }
@ -751,7 +756,9 @@ impl CalcNode {
let number = match rhs.to_number() { let number = match rhs.to_number() {
Ok(n) if n != 0. => n, Ok(n) if n != 0. => n,
_ => { _ => {
return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)); return Err(
input.new_custom_error(StyleParseErrorKind::UnspecifiedError)
);
}, },
}; };
node.mul_by(1. / number); node.mul_by(1. / number);
@ -838,10 +845,9 @@ impl CalcNode {
child.add_length_or_percentage_to(ret, factor)?; child.add_length_or_percentage_to(ret, factor)?;
} }
}, },
CalcNode::MinMax(..) | CalcNode::MinMax(..) | CalcNode::Clamp { .. } => {
CalcNode::Clamp { .. } => {
// FIXME(emilio): Implement min/max/clamp for length-percentage. // FIXME(emilio): Implement min/max/clamp for length-percentage.
return Err(()) return Err(());
}, },
CalcNode::Angle(..) | CalcNode::Time(..) | CalcNode::Number(..) => return Err(()), CalcNode::Angle(..) | CalcNode::Time(..) | CalcNode::Number(..) => return Err(()),
} }

View file

@ -111,7 +111,9 @@ impl FontRelativeLength {
// See https://github.com/rust-lang/rust/issues/68867. rustc isn't // See https://github.com/rust-lang/rust/issues/68867. rustc isn't
// able to figure it own on its own so we help. // able to figure it own on its own so we help.
_ => unsafe { _ => unsafe {
match *self { Em(..) | Ex(..) | Ch(..) | Rem(..) => {} } match *self {
Em(..) | Ex(..) | Ch(..) | Rem(..) => {},
}
debug_unreachable!("Forgot to handle unit in try_sum()") debug_unreachable!("Forgot to handle unit in try_sum()")
}, },
}) })
@ -283,7 +285,9 @@ impl ViewportPercentageLength {
// See https://github.com/rust-lang/rust/issues/68867. rustc isn't // See https://github.com/rust-lang/rust/issues/68867. rustc isn't
// able to figure it own on its own so we help. // able to figure it own on its own so we help.
_ => unsafe { _ => unsafe {
match *self { Vw(..) | Vh(..) | Vmin(..) | Vmax(..) => {} } match *self {
Vw(..) | Vh(..) | Vmin(..) | Vmax(..) => {},
}
debug_unreachable!("Forgot to handle unit in try_sum()") debug_unreachable!("Forgot to handle unit in try_sum()")
}, },
}) })
@ -527,14 +531,21 @@ impl NoCalcLength {
Ok(match (self, other) { Ok(match (self, other) {
(&Absolute(ref one), &Absolute(ref other)) => Absolute(*one + *other), (&Absolute(ref one), &Absolute(ref other)) => Absolute(*one + *other),
(&FontRelative(ref one), &FontRelative(ref other)) => FontRelative(one.try_sum(other)?), (&FontRelative(ref one), &FontRelative(ref other)) => FontRelative(one.try_sum(other)?),
(&ViewportPercentage(ref one), &ViewportPercentage(ref other)) => ViewportPercentage(one.try_sum(other)?), (&ViewportPercentage(ref one), &ViewportPercentage(ref other)) => {
ViewportPercentage(one.try_sum(other)?)
},
(&ServoCharacterWidth(ref one), &ServoCharacterWidth(ref other)) => { (&ServoCharacterWidth(ref one), &ServoCharacterWidth(ref other)) => {
ServoCharacterWidth(CharacterWidth(one.0 + other.0)) ServoCharacterWidth(CharacterWidth(one.0 + other.0))
}, },
// See https://github.com/rust-lang/rust/issues/68867. rustc isn't // See https://github.com/rust-lang/rust/issues/68867. rustc isn't
// able to figure it own on its own so we help. // able to figure it own on its own so we help.
_ => unsafe { _ => unsafe {
match *self { Absolute(..) | FontRelative(..) | ViewportPercentage(..) | ServoCharacterWidth(..) => {} } match *self {
Absolute(..) |
FontRelative(..) |
ViewportPercentage(..) |
ServoCharacterWidth(..) => {},
}
debug_unreachable!("Forgot to handle unit in try_sum()") debug_unreachable!("Forgot to handle unit in try_sum()")
}, },
}) })
@ -569,12 +580,21 @@ impl PartialOrd for NoCalcLength {
match (self, other) { match (self, other) {
(&Absolute(ref one), &Absolute(ref other)) => one.to_px().partial_cmp(&other.to_px()), (&Absolute(ref one), &Absolute(ref other)) => one.to_px().partial_cmp(&other.to_px()),
(&FontRelative(ref one), &FontRelative(ref other)) => one.partial_cmp(other), (&FontRelative(ref one), &FontRelative(ref other)) => one.partial_cmp(other),
(&ViewportPercentage(ref one), &ViewportPercentage(ref other)) => one.partial_cmp(other), (&ViewportPercentage(ref one), &ViewportPercentage(ref other)) => {
(&ServoCharacterWidth(ref one), &ServoCharacterWidth(ref other)) => one.0.partial_cmp(&other.0), one.partial_cmp(other)
},
(&ServoCharacterWidth(ref one), &ServoCharacterWidth(ref other)) => {
one.0.partial_cmp(&other.0)
},
// See https://github.com/rust-lang/rust/issues/68867. rustc isn't // See https://github.com/rust-lang/rust/issues/68867. rustc isn't
// able to figure it own on its own so we help. // able to figure it own on its own so we help.
_ => unsafe { _ => unsafe {
match *self { Absolute(..) | FontRelative(..) | ViewportPercentage(..) | ServoCharacterWidth(..) => {} } match *self {
Absolute(..) |
FontRelative(..) |
ViewportPercentage(..) |
ServoCharacterWidth(..) => {},
}
debug_unreachable!("Forgot an arm in partial_cmp?") debug_unreachable!("Forgot an arm in partial_cmp?")
}, },
} }
@ -645,7 +665,9 @@ impl PartialOrd for FontRelativeLength {
// See https://github.com/rust-lang/rust/issues/68867. rustc isn't // See https://github.com/rust-lang/rust/issues/68867. rustc isn't
// able to figure it own on its own so we help. // able to figure it own on its own so we help.
_ => unsafe { _ => unsafe {
match *self { Em(..) | Ex(..) | Ch(..) | Rem(..) => {} } match *self {
Em(..) | Ex(..) | Ch(..) | Rem(..) => {},
}
debug_unreachable!("Forgot an arm in partial_cmp?") debug_unreachable!("Forgot an arm in partial_cmp?")
}, },
} }
@ -696,7 +718,9 @@ impl PartialOrd for ViewportPercentageLength {
// See https://github.com/rust-lang/rust/issues/68867. rustc isn't // See https://github.com/rust-lang/rust/issues/68867. rustc isn't
// able to figure it own on its own so we help. // able to figure it own on its own so we help.
_ => unsafe { _ => unsafe {
match *self { Vw(..) | Vh(..) | Vmin(..) | Vmax(..) => {} } match *self {
Vw(..) | Vh(..) | Vmin(..) | Vmax(..) => {},
}
debug_unreachable!("Forgot an arm in partial_cmp?") debug_unreachable!("Forgot an arm in partial_cmp?")
}, },
} }
@ -957,7 +981,8 @@ impl LengthPercentage {
}, },
Token::Function(ref name) => { Token::Function(ref name) => {
let function = CalcNode::math_function(name, location)?; let function = CalcNode::math_function(name, location)?;
let calc = CalcNode::parse_length_or_percentage(context, input, num_context, function)?; let calc =
CalcNode::parse_length_or_percentage(context, input, num_context, function)?;
Ok(LengthPercentage::Calc(Box::new(calc))) Ok(LengthPercentage::Calc(Box::new(calc)))
}, },
_ => return Err(location.new_unexpected_token_error(token.clone())), _ => return Err(location.new_unexpected_token_error(token.clone())),

View file

@ -31,7 +31,7 @@ use style_traits::{CssWriter, ParseError, SpecifiedValueInfo, StyleParseErrorKin
pub use self::align::{AlignContent, AlignItems, AlignSelf, ContentDistribution}; pub use self::align::{AlignContent, AlignItems, AlignSelf, ContentDistribution};
#[cfg(feature = "gecko")] #[cfg(feature = "gecko")]
pub use self::align::{JustifyContent, JustifyItems, JustifySelf, SelfAlignment}; pub use self::align::{JustifyContent, JustifyItems, JustifySelf, SelfAlignment};
pub use self::angle::{Angle, AllowUnitlessZeroAngle}; pub use self::angle::{AllowUnitlessZeroAngle, Angle};
pub use self::background::{BackgroundRepeat, BackgroundSize}; pub use self::background::{BackgroundRepeat, BackgroundSize};
pub use self::basic_shape::FillRule; pub use self::basic_shape::FillRule;
pub use self::border::{BorderCornerRadius, BorderImageSlice, BorderImageWidth}; pub use self::border::{BorderCornerRadius, BorderImageSlice, BorderImageWidth};

View file

@ -22,8 +22,8 @@ use cssparser::Parser;
use selectors::parser::SelectorParseErrorKind; use selectors::parser::SelectorParseErrorKind;
use servo_arc::Arc; use servo_arc::Arc;
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use style_traits::values::specified::AllowedNumericType; use style_traits::values::specified::AllowedNumericType;
use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
/// The specified value of a CSS `<position>` /// The specified value of a CSS `<position>`
pub type Position = GenericPosition<HorizontalPosition, VerticalPosition>; pub type Position = GenericPosition<HorizontalPosition, VerticalPosition>;