Format style component.

This commit is contained in:
chansuke 2018-09-09 16:24:45 +02:00 committed by Emilio Cobos Álvarez
parent 31fc6cd565
commit 8dab4d659a
No known key found for this signature in database
GPG key ID: 056B727BB9C1027C
120 changed files with 2207 additions and 1417 deletions

View file

@ -683,8 +683,13 @@ fn parse_self_position<'i, 't>(
fn list_self_position_keywords(f: KeywordsCollectFn, axis: AxisDirection) {
f(&[
"start", "end", "flex-start", "flex-end",
"center", "self-start", "self-end",
"start",
"end",
"flex-start",
"flex-end",
"center",
"self-start",
"self-end",
]);
if axis == AxisDirection::Inline {
f(&["left", "right"]);

View file

@ -43,8 +43,18 @@ impl BackgroundSize {
}
/// One of the keywords for `background-repeat`.
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq,
SpecifiedValueInfo, ToComputedValue, ToCss)]
#[derive(
Clone,
Copy,
Debug,
Eq,
MallocSizeOf,
Parse,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
#[allow(missing_docs)]
pub enum BackgroundRepeatKeyword {
Repeat,
@ -56,8 +66,7 @@ pub enum BackgroundRepeatKeyword {
/// The specified value for the `background-repeat` property.
///
/// https://drafts.csswg.org/css-backgrounds/#the-background-repeat
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo,
ToCss)]
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss)]
pub enum BackgroundRepeat {
/// `repeat-x`
RepeatX,
@ -91,7 +100,9 @@ impl Parse for BackgroundRepeat {
let horizontal = match BackgroundRepeatKeyword::from_ident(&ident) {
Ok(h) => h,
Err(()) => {
return Err(input.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone())));
return Err(
input.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone()))
);
},
};

View file

@ -268,8 +268,7 @@ impl Ellipse {
ShapeRadius::parse(context, i)?,
ShapeRadius::parse(context, i)?,
))
})
.unwrap_or_default();
}).unwrap_or_default();
let position = if input.try(|i| i.expect_ident_matching("at")).is_ok() {
Position::parse(context, input)?
} else {
@ -416,8 +415,7 @@ impl Polygon {
let fill = FillRule::parse(i)?;
i.expect_comma()?; // only eat the comma if there is something before it
Ok(fill)
})
.unwrap_or_default();
}).unwrap_or_default();
let buf = input.parse_comma_separated(|i| {
Ok(PolygonCoord(
@ -449,11 +447,12 @@ impl Path {
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
let fill = input.try(|i| -> Result<_, ParseError> {
let fill = FillRule::parse(i)?;
i.expect_comma()?;
Ok(fill)
}).unwrap_or_default();
let fill = input
.try(|i| -> Result<_, ParseError> {
let fill = FillRule::parse(i)?;
i.expect_comma()?;
Ok(fill)
}).unwrap_or_default();
let path = SVGPathData::parse(context, input)?;
Ok(Path { fill, path })
}

View file

@ -189,8 +189,7 @@ impl Parse for BorderSpacing {
/// A single border-image-repeat keyword.
#[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq,
SpecifiedValueInfo, ToCss)]
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss)]
pub enum BorderImageRepeatKeyword {
Stretch,
Repeat,
@ -201,8 +200,7 @@ pub enum BorderImageRepeatKeyword {
/// The specified value for the `border-image-repeat` property.
///
/// https://drafts.csswg.org/css-backgrounds/#the-border-image-repeat
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo,
ToComputedValue)]
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)]
pub struct BorderImageRepeat(pub BorderImageRepeatKeyword, pub BorderImageRepeatKeyword);
impl ToCss for BorderImageRepeat {

View file

@ -21,26 +21,23 @@ use values::specified::length::{LengthOrPercentage, NonNegativeLength};
fn in_ua_or_chrome_sheet(context: &ParserContext) -> bool {
use stylesheets::Origin;
context.stylesheet_origin == Origin::UserAgent ||
context.chrome_rules_enabled()
context.stylesheet_origin == Origin::UserAgent || context.chrome_rules_enabled()
}
#[cfg(feature = "gecko")]
fn moz_display_values_enabled(context: &ParserContext) -> bool {
use gecko_bindings::structs;
in_ua_or_chrome_sheet(context) ||
unsafe {
structs::StaticPrefs_sVarCache_layout_css_xul_display_values_content_enabled
}
unsafe { structs::StaticPrefs_sVarCache_layout_css_xul_display_values_content_enabled }
}
#[cfg(feature = "gecko")]
fn moz_box_display_values_enabled(context: &ParserContext) -> bool {
use gecko_bindings::structs;
in_ua_or_chrome_sheet(context) ||
unsafe {
structs::StaticPrefs_sVarCache_layout_css_xul_box_display_values_content_enabled
}
unsafe {
structs::StaticPrefs_sVarCache_layout_css_xul_box_display_values_content_enabled
}
}
/// Defines an elements display type, which consists of
@ -57,8 +54,20 @@ fn moz_box_display_values_enabled(context: &ParserContext) -> bool {
/// Also, when you change this from Gecko you may need to regenerate the
/// C++-side bindings (see components/style/cbindgen.toml).
#[allow(missing_docs)]
#[derive(Clone, Copy, Debug, Eq, FromPrimitive, Hash, MallocSizeOf, Parse,
PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
#[derive(
Clone,
Copy,
Debug,
Eq,
FromPrimitive,
Hash,
MallocSizeOf,
Parse,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[repr(u8)]
pub enum Display {
@ -200,7 +209,10 @@ impl Display {
pub fn is_ruby_type(&self) -> bool {
matches!(
*self,
Display::Ruby | Display::RubyBase | Display::RubyText | Display::RubyBaseContainer |
Display::Ruby |
Display::RubyBase |
Display::RubyText |
Display::RubyBaseContainer |
Display::RubyTextContainer
)
}
@ -346,8 +358,7 @@ impl AnimationIterationCount {
}
/// A value for the `animation-name` property.
#[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq, SpecifiedValueInfo,
ToComputedValue)]
#[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)]
#[value_info(other_values = "none")]
pub struct AnimationName(pub Option<KeyframesName>);
@ -391,8 +402,18 @@ impl Parse for AnimationName {
#[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq,
SpecifiedValueInfo, ToComputedValue, ToCss)]
#[derive(
Clone,
Copy,
Debug,
Eq,
MallocSizeOf,
Parse,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
pub enum ScrollSnapType {
None,
Mandatory,
@ -401,8 +422,18 @@ pub enum ScrollSnapType {
#[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq,
SpecifiedValueInfo, ToComputedValue, ToCss)]
#[derive(
Clone,
Copy,
Debug,
Eq,
MallocSizeOf,
Parse,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
pub enum OverscrollBehavior {
Auto,
Contain,
@ -411,15 +442,24 @@ pub enum OverscrollBehavior {
#[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq,
SpecifiedValueInfo, ToComputedValue, ToCss)]
#[derive(
Clone,
Copy,
Debug,
Eq,
MallocSizeOf,
Parse,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
pub enum OverflowClipBox {
PaddingBox,
ContentBox,
}
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo,
ToComputedValue, ToCss)]
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
/// Provides a rendering hint to the user agent,
/// stating what kinds of changes the author expects
/// to perform on the element
@ -497,11 +537,11 @@ fn change_bits_for_maybe_property(ident: &str, context: &ParserContext) -> WillC
};
match id.as_shorthand() {
Ok(shorthand) => {
shorthand.longhands().fold(WillChangeBits::empty(), |flags, p| {
Ok(shorthand) => shorthand
.longhands()
.fold(WillChangeBits::empty(), |flags, p| {
flags | change_bits_for_longhand(p)
})
}
}),
Err(PropertyDeclarationId::Longhand(longhand)) => change_bits_for_longhand(longhand),
Err(PropertyDeclarationId::Custom(..)) => WillChangeBits::empty(),
}
@ -581,9 +621,8 @@ impl ToCss for TouchAction {
TouchAction::TOUCH_ACTION_NONE => dest.write_str("none"),
TouchAction::TOUCH_ACTION_AUTO => dest.write_str("auto"),
TouchAction::TOUCH_ACTION_MANIPULATION => dest.write_str("manipulation"),
_ if self.contains(
TouchAction::TOUCH_ACTION_PAN_X | TouchAction::TOUCH_ACTION_PAN_Y,
) =>
_ if self
.contains(TouchAction::TOUCH_ACTION_PAN_X | TouchAction::TOUCH_ACTION_PAN_Y) =>
{
dest.write_str("pan-x pan-y")
},
@ -756,8 +795,7 @@ impl Parse for Perspective {
return Ok(GenericPerspective::None);
}
Ok(GenericPerspective::Length(NonNegativeLength::parse(
context,
input,
context, input,
)?))
}
}
@ -789,7 +827,7 @@ impl ToCss for TransitionProperty {
TransitionProperty::Custom(ref name) => {
dest.write_str("--")?;
serialize_atom_name(name, dest)
}
},
TransitionProperty::Unsupported(ref i) => i.to_css(dest),
}
}
@ -805,21 +843,21 @@ impl Parse for TransitionProperty {
let id = match PropertyId::parse_ignoring_rule_type(&ident, context) {
Ok(id) => id,
Err(..) => return Ok(TransitionProperty::Unsupported(
CustomIdent::from_ident(location, ident, &["none"])?,
)),
Err(..) => {
return Ok(TransitionProperty::Unsupported(CustomIdent::from_ident(
location,
ident,
&["none"],
)?))
},
};
Ok(match id.as_shorthand() {
Ok(s) => TransitionProperty::Shorthand(s),
Err(longhand_or_custom) => {
match longhand_or_custom {
PropertyDeclarationId::Longhand(id) => TransitionProperty::Longhand(id),
PropertyDeclarationId::Custom(custom) => {
TransitionProperty::Custom(custom.clone())
}
}
}
Err(longhand_or_custom) => match longhand_or_custom {
PropertyDeclarationId::Longhand(id) => TransitionProperty::Longhand(id),
PropertyDeclarationId::Custom(custom) => TransitionProperty::Custom(custom.clone()),
},
})
}
}
@ -846,19 +884,19 @@ impl TransitionProperty {
Ok(match *self {
TransitionProperty::Shorthand(ShorthandId::All) => {
::gecko_bindings::structs::nsCSSPropertyID::eCSSPropertyExtra_all_properties
}
},
TransitionProperty::Shorthand(ref id) => id.to_nscsspropertyid(),
TransitionProperty::Longhand(ref id) => id.to_nscsspropertyid(),
TransitionProperty::Custom(..) |
TransitionProperty::Unsupported(..) => return Err(()),
TransitionProperty::Custom(..) | TransitionProperty::Unsupported(..) => return Err(()),
})
}
}
#[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq,
SpecifiedValueInfo, ToCss)]
#[derive(
Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss,
)]
/// https://drafts.csswg.org/css-box/#propdef-float
pub enum Float {
Left,
@ -866,13 +904,14 @@ pub enum Float {
None,
// https://drafts.csswg.org/css-logical-props/#float-clear
InlineStart,
InlineEnd
InlineEnd,
}
#[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq,
SpecifiedValueInfo, ToCss)]
#[derive(
Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss,
)]
/// https://drafts.csswg.org/css-box/#propdef-clear
pub enum Clear {
None,
@ -881,14 +920,15 @@ pub enum Clear {
Both,
// https://drafts.csswg.org/css-logical-props/#float-clear
InlineStart,
InlineEnd
InlineEnd,
}
/// https://drafts.csswg.org/css-ui/#propdef-resize
#[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq,
SpecifiedValueInfo, ToCss)]
#[derive(
Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss,
)]
pub enum Resize {
None,
Both,
@ -906,8 +946,19 @@ pub enum Resize {
/// NOTE(emilio): When changing this you may want to regenerate the C++ bindings
/// (see components/style/cbindgen.toml)
#[allow(missing_docs)]
#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq,
SpecifiedValueInfo, ToCss, ToComputedValue)]
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
MallocSizeOf,
Parse,
PartialEq,
SpecifiedValueInfo,
ToCss,
ToComputedValue,
)]
#[repr(u8)]
pub enum Appearance {
/// No appearance at all.

View file

@ -89,11 +89,11 @@ impl<'a, 'b: 'a, 'i: 'a> ::cssparser::ColorComponentParser<'i> for ColorComponen
};
Ok(AngleOrNumber::Angle { degrees })
}
},
Token::Number { value, .. } => Ok(AngleOrNumber::Number { value }),
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {
input.parse_nested_block(|i| CalcNode::parse_angle_or_number(self.0, i))
}
},
t => return Err(location.new_unexpected_token_error(t)),
}
}
@ -120,10 +120,10 @@ impl<'a, 'b: 'a, 'i: 'a> ::cssparser::ColorComponentParser<'i> for ColorComponen
Token::Number { value, .. } => Ok(NumberOrPercentage::Number { value }),
Token::Percentage { unit_value, .. } => {
Ok(NumberOrPercentage::Percentage { unit_value })
}
},
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {
input.parse_nested_block(|i| CalcNode::parse_number_or_percentage(self.0, i))
}
},
t => return Err(location.new_unexpected_token_error(t)),
}
}
@ -169,10 +169,10 @@ impl Parse for Color {
Err(e.location.new_custom_error(StyleParseErrorKind::ValueError(
ValueParseErrorKind::InvalidColor(t),
)))
}
},
_ => Err(e),
}
}
},
}
}
}
@ -276,10 +276,10 @@ impl Color {
}
return parse_hash_color(ident.as_bytes())
.map_err(|()| location.new_custom_error(StyleParseErrorKind::UnspecifiedError));
}
},
ref t => {
return Err(location.new_unexpected_token_error(t.clone()));
}
},
};
if value < 0 {
return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError));
@ -359,11 +359,11 @@ impl Color {
Keyword::MozVisitedhyperlinktext => pres_context.mVisitedLinkColor,
})
})
}
},
#[cfg(feature = "gecko")]
Color::InheritFromBodyQuirk => {
_context.map(|context| ComputedColor::rgba(context.device().body_text_color()))
}
},
}
}
}

View file

@ -22,8 +22,7 @@ impl Parse for ColumnCount {
return Ok(GenericColumnCount::Auto);
}
Ok(GenericColumnCount::Integer(PositiveInteger::parse(
context,
input,
context, input,
)?))
}
}

View file

@ -93,8 +93,7 @@ impl Content {
.try(|input| {
input.expect_comma()?;
ListStyleType::parse(input)
})
.unwrap_or(ListStyleType::Decimal)
}).unwrap_or(ListStyleType::Decimal)
}
#[cfg(feature = "gecko")]
@ -103,8 +102,7 @@ impl Content {
.try(|input| {
input.expect_comma()?;
CounterStyleOrNone::parse(context, input)
})
.unwrap_or(CounterStyleOrNone::decimal())
}).unwrap_or(CounterStyleOrNone::decimal())
}
}

View file

@ -118,9 +118,9 @@ impl Parse for BoxShadow {
let value = input.try::<_, _, ParseError>(|i| {
let horizontal = Length::parse(context, i)?;
let vertical = Length::parse(context, i)?;
let (blur, spread) = match i.try::<_, _, ParseError>(|i| {
Length::parse_non_negative(context, i)
}) {
let (blur, spread) = match i
.try::<_, _, ParseError>(|i| Length::parse_non_negative(context, i))
{
Ok(blur) => {
let spread = i.try(|i| Length::parse(context, i)).ok();
(Some(blur.into()), spread)
@ -143,7 +143,8 @@ impl Parse for BoxShadow {
break;
}
let lengths = lengths.ok_or(input.new_custom_error(StyleParseErrorKind::UnspecifiedError))?;
let lengths =
lengths.ok_or(input.new_custom_error(StyleParseErrorKind::UnspecifiedError))?;
Ok(BoxShadow {
base: SimpleShadow {
color: color,
@ -164,7 +165,8 @@ impl ToComputedValue for BoxShadow {
fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
ComputedBoxShadow {
base: self.base.to_computed_value(context),
spread: self.spread
spread: self
.spread
.as_ref()
.unwrap_or(&Length::zero())
.to_computed_value(context),
@ -271,13 +273,15 @@ impl ToComputedValue for SimpleShadow {
#[inline]
fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
ComputedSimpleShadow {
color: self.color
color: self
.color
.as_ref()
.unwrap_or(&Color::currentcolor())
.to_computed_value(context),
horizontal: self.horizontal.to_computed_value(context),
vertical: self.vertical.to_computed_value(context),
blur: self.blur
blur: self
.blur
.as_ref()
.unwrap_or(&NonNegativeLength::zero())
.to_computed_value(context),

View file

@ -148,9 +148,9 @@ impl ToComputedValue for FontWeight {
#[inline]
fn from_computed_value(computed: &computed::FontWeight) -> Self {
FontWeight::Absolute(AbsoluteFontWeight::Weight(
Number::from_computed_value(&computed.0)
))
FontWeight::Absolute(AbsoluteFontWeight::Weight(Number::from_computed_value(
&computed.0,
)))
}
}
@ -174,9 +174,7 @@ impl AbsoluteFontWeight {
pub fn compute(&self) -> computed::FontWeight {
match *self {
AbsoluteFontWeight::Weight(weight) => {
computed::FontWeight(
weight.get().max(MIN_FONT_WEIGHT).min(MAX_FONT_WEIGHT)
)
computed::FontWeight(weight.get().max(MIN_FONT_WEIGHT).min(MAX_FONT_WEIGHT))
},
AbsoluteFontWeight::Normal => computed::FontWeight::normal(),
AbsoluteFontWeight::Bold => computed::FontWeight::bold(),
@ -194,12 +192,11 @@ impl Parse for AbsoluteFontWeight {
// seem worth it just for a single property with such a weird range,
// so we do the clamping here manually.
if !number.was_calc() &&
(number.get() < MIN_FONT_WEIGHT || number.get() > MAX_FONT_WEIGHT) {
return Err(input.new_custom_error(
StyleParseErrorKind::UnspecifiedError
))
(number.get() < MIN_FONT_WEIGHT || number.get() > MAX_FONT_WEIGHT)
{
return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError));
}
return Ok(AbsoluteFontWeight::Weight(number))
return Ok(AbsoluteFontWeight::Weight(number));
}
Ok(try_match_ident_ignore_ascii_case! { input,
@ -228,7 +225,7 @@ impl ToCss for SpecifiedFontStyle {
angle.to_css(dest)?;
}
Ok(())
}
},
}
}
}
@ -260,7 +257,7 @@ impl ToComputedValue for SpecifiedFontStyle {
generics::FontStyle::Italic => generics::FontStyle::Italic,
generics::FontStyle::Oblique(ref angle) => {
generics::FontStyle::Oblique(FontStyleAngle(Self::compute_angle(angle)))
}
},
}
}
@ -270,12 +267,11 @@ impl ToComputedValue for SpecifiedFontStyle {
generics::FontStyle::Italic => generics::FontStyle::Italic,
generics::FontStyle::Oblique(ref angle) => {
generics::FontStyle::Oblique(Angle::from_computed_value(&angle.0))
}
},
}
}
}
/// The default angle for `font-style: oblique`.
///
/// NOTE(emilio): As of right now this diverges from the spec, which specifies
@ -299,9 +295,10 @@ impl SpecifiedFontStyle {
/// Gets a clamped angle from a specified Angle.
pub fn compute_angle(angle: &Angle) -> ComputedAngle {
ComputedAngle::Deg(
angle.degrees()
angle
.degrees()
.max(FONT_STYLE_OBLIQUE_MIN_ANGLE_DEGREES)
.min(FONT_STYLE_OBLIQUE_MAX_ANGLE_DEGREES)
.min(FONT_STYLE_OBLIQUE_MAX_ANGLE_DEGREES),
)
}
@ -319,11 +316,9 @@ impl SpecifiedFontStyle {
if degrees < FONT_STYLE_OBLIQUE_MIN_ANGLE_DEGREES ||
degrees > FONT_STYLE_OBLIQUE_MAX_ANGLE_DEGREES
{
return Err(input.new_custom_error(
StyleParseErrorKind::UnspecifiedError
));
return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError));
}
return Ok(angle)
return Ok(angle);
}
/// The default angle for `font-style: oblique`.
@ -336,8 +331,7 @@ impl SpecifiedFontStyle {
}
/// The specified value of the `font-style` property.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo,
ToCss)]
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss)]
#[allow(missing_docs)]
pub enum FontStyle {
Specified(SpecifiedFontStyle),
@ -375,7 +369,9 @@ impl Parse for FontStyle {
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Ok(FontStyle::Specified(SpecifiedFontStyle::parse(context, input)?))
Ok(FontStyle::Specified(SpecifiedFontStyle::parse(
context, input,
)?))
}
}
@ -383,8 +379,7 @@ impl Parse for FontStyle {
///
/// https://drafts.csswg.org/css-fonts-4/#font-stretch-prop
#[allow(missing_docs)]
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo,
ToCss)]
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss)]
pub enum FontStretch {
Stretch(Percentage),
Keyword(FontStretchKeyword),
@ -393,8 +388,7 @@ pub enum FontStretch {
}
/// A keyword value for `font-stretch`.
#[derive(Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo,
ToCss)]
#[derive(Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss)]
#[allow(missing_docs)]
pub enum FontStretchKeyword {
Normal,
@ -497,9 +491,7 @@ impl ToComputedValue for FontStretch {
FontStretch::Stretch(ref percentage) => {
computed::FontStretch(NonNegative(percentage.to_computed_value(context)))
},
FontStretch::Keyword(ref kw) => {
computed::FontStretch(NonNegative(kw.compute()))
},
FontStretch::Keyword(ref kw) => computed::FontStretch(NonNegative(kw.compute())),
FontStretch::System(_) => self.compute_system(context),
}
}
@ -690,8 +682,7 @@ impl Parse for FontSizeAdjust {
}
Ok(FontSizeAdjust::Number(Number::parse_non_negative(
context,
input,
context, input,
)?))
}
}
@ -906,10 +897,11 @@ impl FontSize {
// new ones.
//
// This is enough of an edge case to not really matter.
let abs = calc.to_computed_value_zoomed(
context,
FontBaseSize::InheritedStyleButStripEmUnits,
).length_component();
let abs = calc
.to_computed_value_zoomed(
context,
FontBaseSize::InheritedStyleButStripEmUnits,
).length_component();
info = parent.keyword_info.map(|i| i.compose(ratio, abs.into()));
}
@ -1939,8 +1931,7 @@ impl Parse for FontFeatureSettings {
}
}
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo,
ToComputedValue)]
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)]
/// Whether user agents are allowed to synthesize bold or oblique font faces
/// when a font family lacks bold or italic faces
pub struct FontSynthesis {
@ -2217,8 +2208,9 @@ impl Parse for VariationValue<Number> {
}
}
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo,
ToComputedValue, ToCss)]
#[derive(
Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss,
)]
/// text-zoom. Enable if true, disable if false
pub struct XTextZoom(#[css(skip)] pub bool);
@ -2235,8 +2227,7 @@ impl Parse for XTextZoom {
}
}
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo,
ToComputedValue, ToCss)]
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
/// Internal property that reflects the lang attribute
pub struct XLang(#[css(skip)] pub Atom);
@ -2324,8 +2315,7 @@ impl Parse for MozScriptLevel {
}
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[derive(Clone, Copy, Debug, PartialEq, SpecifiedValueInfo, ToComputedValue,
ToCss)]
#[derive(Clone, Copy, Debug, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
/// Specifies the multiplier to be used to adjust font size
/// due to changes in scriptlevel.
///

View file

@ -22,7 +22,8 @@ pub fn parse_flex<'i, 't>(input: &mut Parser<'i, 't>) -> Result<CSSFloat, ParseE
match *input.next()? {
Token::Dimension {
value, ref unit, ..
} if unit.eq_ignore_ascii_case("fr") && value.is_sign_positive() =>
}
if unit.eq_ignore_ascii_case("fr") && value.is_sign_positive() =>
{
Ok(value)
},
@ -76,7 +77,8 @@ impl Parse for TrackSize<LengthOrPercentage> {
}
input.expect_function_matching("fit-content")?;
let lop = input.parse_nested_block(|i| LengthOrPercentage::parse_non_negative(context, i))?;
let lop =
input.parse_nested_block(|i| LengthOrPercentage::parse_non_negative(context, i))?;
Ok(TrackSize::FitContent(lop))
}
}
@ -175,7 +177,9 @@ impl TrackRepeat<LengthOrPercentage, Integer> {
} else {
if values.is_empty() {
// expecting at least one <track-size>
return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError));
return Err(
input.new_custom_error(StyleParseErrorKind::UnspecifiedError)
);
}
names.push(current_names); // final `<line-names>`
@ -217,9 +221,11 @@ impl Parse for TrackList<LengthOrPercentage, Integer> {
// assume that everything is <fixed-size>. This flag is useful when we encounter <auto-repeat>
let mut atleast_one_not_fixed = false;
loop {
current_names.extend_from_slice(&mut input
.try(parse_line_names)
.unwrap_or(vec![].into_boxed_slice()));
current_names.extend_from_slice(
&mut input
.try(parse_line_names)
.unwrap_or(vec![].into_boxed_slice()),
);
if let Ok(track_size) = input.try(|i| TrackSize::parse(context, i)) {
if !track_size.is_fixed() {
atleast_one_not_fixed = true;
@ -244,13 +250,17 @@ impl Parse for TrackList<LengthOrPercentage, Integer> {
atleast_one_not_fixed = true;
if auto_repeat.is_some() {
// only <fixed-repeat>
return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError));
return Err(
input.new_custom_error(StyleParseErrorKind::UnspecifiedError)
);
}
},
RepeatType::Auto => {
if auto_repeat.is_some() || atleast_one_not_fixed {
// We've either seen <auto-repeat> earlier, or there's at least one non-fixed value
return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError));
return Err(
input.new_custom_error(StyleParseErrorKind::UnspecifiedError)
);
}
list_type = TrackListType::Auto(values.len() as u16 + auto_offset);
@ -342,7 +352,8 @@ impl ToComputedValue for TrackList<LengthOrPercentage, Integer> {
list_type: self.list_type.to_computed_value(context),
values: values,
line_names: line_names.into_boxed_slice(),
auto_repeat: self.auto_repeat
auto_repeat: self
.auto_repeat
.clone()
.map(|repeat| repeat.to_computed_value(context)),
}

View file

@ -55,19 +55,19 @@ impl SpecifiedValueInfo for Gradient {
fn collect_completion_keywords(f: KeywordsCollectFn) {
// This list here should keep sync with that in Gradient::parse.
f(&[
"linear-gradient",
"-webkit-linear-gradient",
"-moz-linear-gradient",
"repeating-linear-gradient",
"-webkit-repeating-linear-gradient",
"-moz-repeating-linear-gradient",
"radial-gradient",
"-webkit-radial-gradient",
"-moz-radial-gradient",
"repeating-radial-gradient",
"-webkit-repeating-radial-gradient",
"-moz-repeating-radial-gradient",
"-webkit-gradient",
"linear-gradient",
"-webkit-linear-gradient",
"-moz-linear-gradient",
"repeating-linear-gradient",
"-webkit-repeating-linear-gradient",
"-moz-repeating-linear-gradient",
"radial-gradient",
"-webkit-radial-gradient",
"-moz-radial-gradient",
"repeating-radial-gradient",
"-webkit-repeating-radial-gradient",
"-moz-repeating-radial-gradient",
"-webkit-gradient",
]);
}
}
@ -239,9 +239,9 @@ impl Parse for Gradient {
#[cfg(feature = "gecko")]
{
use gecko_bindings::structs;
if compat_mode == CompatMode::Moz && !unsafe {
structs::StaticPrefs_sVarCache_layout_css_prefixes_gradients
} {
if compat_mode == CompatMode::Moz &&
!unsafe { structs::StaticPrefs_sVarCache_layout_css_prefixes_gradients }
{
return Err(input.new_custom_error(StyleParseErrorKind::UnexpectedFunction(func)));
}
}
@ -760,9 +760,9 @@ impl LineDirection {
// There is no `to` keyword in webkit prefixed syntax. If it's consumed,
// parsing should throw an error.
CompatMode::WebKit if to_ident.is_ok() => {
return Err(i.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(
"to".into(),
)))
return Err(
i.new_custom_error(SelectorParseErrorKind::UnexpectedIdent("to".into()))
)
},
_ => {},
}
@ -969,8 +969,7 @@ impl Parse for PaintWorklet {
.try(|input| {
input.expect_comma()?;
input.parse_comma_separated(|input| SpecifiedValue::parse(input))
})
.unwrap_or(vec![]);
}).unwrap_or(vec![]);
Ok(PaintWorklet { name, arguments })
})
}

View file

@ -566,14 +566,16 @@ impl Length {
match *token {
Token::Dimension {
value, ref unit, ..
} if num_context.is_ok(context.parsing_mode, value) =>
}
if num_context.is_ok(context.parsing_mode, value) =>
{
return NoCalcLength::parse_dimension(context, value, unit)
.map(Length::NoCalc)
.map_err(|()| location.new_unexpected_token_error(token.clone()))
},
Token::Number { value, .. } if num_context.is_ok(context.parsing_mode, value) => {
if value != 0. && !context.parsing_mode.allows_unitless_lengths() &&
if value != 0. &&
!context.parsing_mode.allows_unitless_lengths() &&
!allow_quirks.allowed(context.quirks_mode)
{
return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError));
@ -753,7 +755,8 @@ impl LengthOrPercentage {
match *token {
Token::Dimension {
value, ref unit, ..
} if num_context.is_ok(context.parsing_mode, value) =>
}
if num_context.is_ok(context.parsing_mode, value) =>
{
return NoCalcLength::parse_dimension(context, value, unit)
.map(LengthOrPercentage::Length)
@ -767,7 +770,8 @@ impl LengthOrPercentage {
)))
},
Token::Number { value, .. } if num_context.is_ok(context.parsing_mode, value) => {
if value != 0. && !context.parsing_mode.allows_unitless_lengths() &&
if value != 0. &&
!context.parsing_mode.allows_unitless_lengths() &&
!allow_quirks.allowed(context.quirks_mode)
{
return Err(location.new_unexpected_token_error(token.clone()));
@ -780,8 +784,9 @@ impl LengthOrPercentage {
}
}
let calc = input
.parse_nested_block(|i| CalcNode::parse_length_or_percentage(context, i, num_context))?;
let calc = input.parse_nested_block(|i| {
CalcNode::parse_length_or_percentage(context, i, num_context)
})?;
Ok(LengthOrPercentage::Calc(Box::new(calc)))
}
@ -871,7 +876,8 @@ impl LengthOrPercentageOrAuto {
match *token {
Token::Dimension {
value, ref unit, ..
} if num_context.is_ok(context.parsing_mode, value) =>
}
if num_context.is_ok(context.parsing_mode, value) =>
{
return NoCalcLength::parse_dimension(context, value, unit)
.map(LengthOrPercentageOrAuto::Length)
@ -885,7 +891,8 @@ impl LengthOrPercentageOrAuto {
)))
},
Token::Number { value, .. } if num_context.is_ok(context.parsing_mode, value) => {
if value != 0. && !context.parsing_mode.allows_unitless_lengths() &&
if value != 0. &&
!context.parsing_mode.allows_unitless_lengths() &&
!allow_quirks.allowed(context.quirks_mode)
{
return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError));
@ -902,8 +909,9 @@ impl LengthOrPercentageOrAuto {
}
}
let calc = input
.parse_nested_block(|i| CalcNode::parse_length_or_percentage(context, i, num_context))?;
let calc = input.parse_nested_block(|i| {
CalcNode::parse_length_or_percentage(context, i, num_context)
})?;
Ok(LengthOrPercentageOrAuto::Calc(Box::new(calc)))
}
@ -998,8 +1006,7 @@ impl Parse for NonNegativeLengthOrPercentageOrAuto {
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Ok(NonNegative(LengthOrPercentageOrAuto::parse_non_negative(
context,
input,
context, input,
)?))
}
}
@ -1028,7 +1035,8 @@ impl LengthOrPercentageOrNone {
match *token {
Token::Dimension {
value, ref unit, ..
} if num_context.is_ok(context.parsing_mode, value) =>
}
if num_context.is_ok(context.parsing_mode, value) =>
{
return NoCalcLength::parse_dimension(context, value, unit)
.map(LengthOrPercentageOrNone::Length)
@ -1042,7 +1050,8 @@ impl LengthOrPercentageOrNone {
)))
},
Token::Number { value, .. } if num_context.is_ok(context.parsing_mode, value) => {
if value != 0. && !context.parsing_mode.allows_unitless_lengths() &&
if value != 0. &&
!context.parsing_mode.allows_unitless_lengths() &&
!allow_quirks.allowed(context.quirks_mode)
{
return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError));
@ -1059,8 +1068,9 @@ impl LengthOrPercentageOrNone {
}
}
let calc = input
.parse_nested_block(|i| CalcNode::parse_length_or_percentage(context, i, num_context))?;
let calc = input.parse_nested_block(|i| {
CalcNode::parse_length_or_percentage(context, i, num_context)
})?;
Ok(LengthOrPercentageOrNone::Calc(Box::new(calc)))
}

View file

@ -15,8 +15,7 @@ use values::generics::CounterStyleOrNone;
/// Specified and computed `list-style-type` property.
#[cfg(feature = "gecko")]
#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo,
ToComputedValue, ToCss)]
#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
pub enum ListStyleType {
/// <counter-style> | none
CounterStyle(CounterStyleOrNone),
@ -79,8 +78,7 @@ impl Parse for ListStyleType {
/// FIXME(emilio): It's a shame that this allocates all the time it's computed,
/// probably should just be refcounted.
/// FIXME This can probably derive ToCss.
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo,
ToComputedValue)]
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)]
pub struct Quotes(#[css(if_empty = "none")] pub Box<[(Box<str>, Box<str>)]>);
impl ToCss for Quotes {

View file

@ -151,8 +151,20 @@ fn parse_number_with_clamping_mode<'i, 't>(
// FIXME(emilio): Should move to border.rs
#[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Ord, Parse, PartialEq,
PartialOrd, SpecifiedValueInfo, ToComputedValue, ToCss)]
#[derive(
Clone,
Copy,
Debug,
Eq,
MallocSizeOf,
Ord,
Parse,
PartialEq,
PartialOrd,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
pub enum BorderStyle {
None = -1,
Solid = 6,
@ -330,8 +342,7 @@ impl Parse for GreaterThanOrEqualToOneNumber {
///
/// FIXME(emilio): Should probably use Either.
#[allow(missing_docs)]
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo,
ToCss)]
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss)]
pub enum NumberOrPercentage {
Percentage(Percentage),
Number(Number),
@ -369,8 +380,7 @@ impl Parse for NumberOrPercentage {
}
#[allow(missing_docs)]
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, PartialOrd,
SpecifiedValueInfo, ToCss)]
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, PartialOrd, SpecifiedValueInfo, ToCss)]
pub struct Opacity(Number);
impl Parse for Opacity {
@ -630,13 +640,16 @@ impl ToComputedValue for ClipRect {
fn to_computed_value(&self, context: &Context) -> super::computed::ClipRect {
super::computed::ClipRect {
top: self.top.as_ref().map(|top| top.to_computed_value(context)),
right: self.right
right: self
.right
.as_ref()
.map(|right| right.to_computed_value(context)),
bottom: self.bottom
bottom: self
.bottom
.as_ref()
.map(|bottom| bottom.to_computed_value(context)),
left: self.left
left: self
.left
.as_ref()
.map(|left| left.to_computed_value(context)),
}
@ -760,8 +773,7 @@ impl AllowQuirks {
/// An attr(...) rule
///
/// `[namespace? `|`]? ident`
#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo,
ToComputedValue)]
#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)]
#[css(function)]
pub struct Attr {
/// Optional namespace prefix and URL.
@ -814,7 +826,10 @@ impl Attr {
let prefix = Prefix::from(ns.as_ref());
let ns = match get_namespace_for_prefix(&prefix, context) {
Some(ns) => ns,
None => return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)),
None => {
return Err(location
.new_custom_error(StyleParseErrorKind::UnspecifiedError))
},
};
Some((prefix, ns))
} else {

View file

@ -12,8 +12,18 @@ use values::specified::SVGPathData;
/// The offset-path value.
///
/// https://drafts.fxtf.org/motion-1/#offset-path-property
#[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq,
SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss)]
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedZero,
ToComputedValue,
ToCss,
)]
pub enum OffsetPath {
// We could merge SVGPathData into ShapeSource, so we could reuse them. However,
// we don't want to support other value for offset-path, so use SVGPathData only for now.
@ -37,7 +47,7 @@ impl OffsetPath {
impl Parse for OffsetPath {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
// Parse none.
if input.try(|i| i.expect_ident_matching("none")).is_ok() {

View file

@ -10,8 +10,19 @@ use selectors::parser::SelectorParseErrorKind;
use style_traits::ParseError;
use values::specified::BorderStyle;
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Ord, PartialEq, PartialOrd,
SpecifiedValueInfo, ToComputedValue, ToCss)]
#[derive(
Clone,
Copy,
Debug,
Eq,
MallocSizeOf,
Ord,
PartialEq,
PartialOrd,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
/// <https://drafts.csswg.org/css-ui/#propdef-outline-style>
pub enum OutlineStyle {
/// auto

View file

@ -45,8 +45,19 @@ pub enum PositionComponent<S> {
}
/// A keyword for the X direction.
#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq,
SpecifiedValueInfo, ToComputedValue, ToCss)]
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
MallocSizeOf,
Parse,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
#[allow(missing_docs)]
pub enum X {
Left,
@ -54,8 +65,19 @@ pub enum X {
}
/// A keyword for the Y direction.
#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq,
SpecifiedValueInfo, ToComputedValue, ToCss)]
#[derive(
Clone,
Copy,
Debug,
Eq,
Hash,
MallocSizeOf,
Parse,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
#[allow(missing_docs)]
pub enum Y {
Top,
@ -128,10 +150,12 @@ impl Position {
}
let y_keyword = Y::parse(input)?;
let lop_and_x_pos: Result<_, ParseError> = input.try(|i| {
let y_lop = i.try(|i| LengthOrPercentage::parse_quirky(context, i, allow_quirks))
let y_lop = i
.try(|i| LengthOrPercentage::parse_quirky(context, i, allow_quirks))
.ok();
if let Ok(x_keyword) = i.try(X::parse) {
let x_lop = i.try(|i| LengthOrPercentage::parse_quirky(context, i, allow_quirks))
let x_lop = i
.try(|i| LengthOrPercentage::parse_quirky(context, i, allow_quirks))
.ok();
let x_pos = PositionComponent::Side(x_keyword, x_lop);
return Ok((y_lop, x_pos));
@ -411,8 +435,9 @@ impl ToCss for LegacyPosition {
}
}
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo,
ToComputedValue, ToCss)]
#[derive(
Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss,
)]
/// Auto-placement algorithm Option
pub enum AutoFlow {
/// The auto-placement algorithm places items by filling each row in turn,
@ -423,8 +448,9 @@ pub enum AutoFlow {
Column,
}
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo,
ToComputedValue, ToCss)]
#[derive(
Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss,
)]
/// Controls how the auto-placement algorithm works
/// specifying exactly how auto-placed items get flowed into the grid
pub struct GridAutoFlow {
@ -630,8 +656,7 @@ impl Parse for TemplateAreas {
}
/// Arc type for `Arc<TemplateAreas>`
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo,
ToComputedValue, ToCss)]
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
pub struct TemplateAreasArc(#[ignore_malloc_size_of = "Arc"] pub Arc<TemplateAreas>);
impl Parse for TemplateAreasArc {
@ -685,8 +710,12 @@ impl<'a> Iterator for TemplateAreasTokenizer<'a> {
}
fn is_name_code_point(c: char) -> bool {
c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '\u{80}' || c == '_' ||
c >= '0' && c <= '9' || c == '-'
c >= 'A' && c <= 'Z' ||
c >= 'a' && c <= 'z' ||
c >= '\u{80}' ||
c == '_' ||
c >= '0' && c <= '9' ||
c == '-'
}
/// This property specifies named grid areas.

View file

@ -32,8 +32,7 @@ impl Resolution {
/// Convert this resolution value to dppx units.
pub fn to_dppx(&self) -> CSSFloat {
match *self {
Resolution::X(f) |
Resolution::Dppx(f) => f,
Resolution::X(f) | Resolution::Dppx(f) => f,
_ => self.to_dpi() / 96.0,
}
}
@ -42,8 +41,7 @@ impl Resolution {
pub fn to_dpi(&self) -> CSSFloat {
match *self {
Resolution::Dpi(f) => f,
Resolution::X(f) |
Resolution::Dppx(f) => f * 96.0,
Resolution::X(f) | Resolution::Dppx(f) => f * 96.0,
Resolution::Dpcm(f) => f * 2.54,
}
}

View file

@ -61,7 +61,8 @@ impl SourceSizeList {
/// Evaluate this <source-size-list> to get the final viewport length.
pub fn evaluate(&self, device: &Device, quirks_mode: QuirksMode) -> Au {
let matching_source_size = self.source_sizes
let matching_source_size = self
.source_sizes
.iter()
.find(|source_size| source_size.condition.matches(device, quirks_mode));

View file

@ -173,8 +173,7 @@ const PAINT_ORDER_MASK: u8 = 0b11;
///
/// Higher priority values, i.e. the values specified first,
/// will be painted first (and may be covered by paintings of lower priority)
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo,
ToComputedValue)]
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)]
pub struct SVGPaintOrder(pub u8);
impl SVGPaintOrder {
@ -281,8 +280,7 @@ impl ToCss for SVGPaintOrder {
/// Specified MozContextProperties value.
/// Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-context-properties)
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo,
ToComputedValue, ToCss)]
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
pub struct MozContextProperties(pub CustomIdent);
impl Parse for MozContextProperties {

View file

@ -16,12 +16,12 @@ use values::CSSFloat;
use values::animated::{Animate, Procedure};
use values::distance::{ComputeSquaredDistance, SquaredDistance};
/// The SVG path data.
///
/// https://www.w3.org/TR/SVG11/paths.html#PathData
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedZero,
ToComputedValue)]
#[derive(
Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue,
)]
pub struct SVGPathData(Box<[PathCommand]>);
impl SVGPathData {
@ -46,7 +46,11 @@ impl SVGPathData {
subpath_start: CoordPair::new(0.0, 0.0),
pos: CoordPair::new(0.0, 0.0),
};
let result = self.0.iter().map(|seg| seg.normalize(&mut state)).collect::<Vec<_>>();
let result = self
.0
.iter()
.map(|seg| seg.normalize(&mut state))
.collect::<Vec<_>>();
SVGPathData(result.into_boxed_slice())
}
}
@ -55,7 +59,7 @@ impl ToCss for SVGPathData {
#[inline]
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: fmt::Write
W: fmt::Write,
{
dest.write_char('"')?;
{
@ -76,7 +80,7 @@ impl Parse for SVGPathData {
// str::Char iterator to check each character.
fn parse<'i, 't>(
_context: &ParserContext,
input: &mut Parser<'i, 't>
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
let location = input.current_source_location();
let path_string = input.expect_string()?.as_ref();
@ -103,7 +107,9 @@ impl Animate for SVGPathData {
return Err(());
}
let result = self.normalize().0
let result = self
.normalize()
.0
.iter()
.zip(other.normalize().0.iter())
.map(|(a, b)| a.animate(&b, procedure))
@ -117,7 +123,8 @@ impl ComputeSquaredDistance for SVGPathData {
if self.0.len() != other.0.len() {
return Err(());
}
self.normalize().0
self.normalize()
.0
.iter()
.zip(other.normalize().0.iter())
.map(|(this, other)| this.compute_squared_distance(&other))
@ -131,8 +138,17 @@ impl ComputeSquaredDistance for SVGPathData {
/// points of the Bézier curve in the spec.
///
/// https://www.w3.org/TR/SVG11/paths.html#PathData
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq,
SpecifiedValueInfo, ToAnimatedZero)]
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedZero,
)]
#[allow(missing_docs)]
#[repr(C, u8)]
pub enum PathCommand {
@ -140,21 +156,43 @@ pub enum PathCommand {
/// https://www.w3.org/TR/SVG/paths.html#__svg__SVGPathSeg__PATHSEG_UNKNOWN
Unknown,
/// The "moveto" command.
MoveTo { point: CoordPair, absolute: IsAbsolute },
MoveTo {
point: CoordPair,
absolute: IsAbsolute,
},
/// The "lineto" command.
LineTo { point: CoordPair, absolute: IsAbsolute },
LineTo {
point: CoordPair,
absolute: IsAbsolute,
},
/// The horizontal "lineto" command.
HorizontalLineTo { x: CSSFloat, absolute: IsAbsolute },
/// The vertical "lineto" command.
VerticalLineTo { y: CSSFloat, absolute: IsAbsolute },
/// The cubic Bézier curve command.
CurveTo { control1: CoordPair, control2: CoordPair, point: CoordPair, absolute: IsAbsolute },
CurveTo {
control1: CoordPair,
control2: CoordPair,
point: CoordPair,
absolute: IsAbsolute,
},
/// The smooth curve command.
SmoothCurveTo { control2: CoordPair, point: CoordPair, absolute: IsAbsolute },
SmoothCurveTo {
control2: CoordPair,
point: CoordPair,
absolute: IsAbsolute,
},
/// The quadratic Bézier curve command.
QuadBezierCurveTo { control1: CoordPair, point: CoordPair, absolute: IsAbsolute },
QuadBezierCurveTo {
control1: CoordPair,
point: CoordPair,
absolute: IsAbsolute,
},
/// The smooth quadratic Bézier curve command.
SmoothQuadBezierCurveTo { point: CoordPair, absolute: IsAbsolute },
SmoothQuadBezierCurveTo {
point: CoordPair,
absolute: IsAbsolute,
},
/// The elliptical arc curve command.
EllipticalArc {
rx: CSSFloat,
@ -165,7 +203,7 @@ pub enum PathCommand {
#[animation(constant)]
sweep_flag: ArcFlag,
point: CoordPair,
absolute: IsAbsolute
absolute: IsAbsolute,
},
/// The "closepath" command.
ClosePath,
@ -191,74 +229,138 @@ impl PathCommand {
state.pos = state.subpath_start;
ClosePath
},
MoveTo { mut point, absolute } => {
MoveTo {
mut point,
absolute,
} => {
if !absolute.is_yes() {
point += state.pos;
}
state.pos = point;
state.subpath_start = point;
MoveTo { point, absolute: IsAbsolute::Yes }
MoveTo {
point,
absolute: IsAbsolute::Yes,
}
},
LineTo { mut point, absolute } => {
LineTo {
mut point,
absolute,
} => {
if !absolute.is_yes() {
point += state.pos;
}
state.pos = point;
LineTo { point, absolute: IsAbsolute::Yes }
LineTo {
point,
absolute: IsAbsolute::Yes,
}
},
HorizontalLineTo { mut x, absolute } => {
if !absolute.is_yes() {
x += state.pos.0;
}
state.pos.0 = x;
HorizontalLineTo { x, absolute: IsAbsolute::Yes }
HorizontalLineTo {
x,
absolute: IsAbsolute::Yes,
}
},
VerticalLineTo { mut y, absolute } => {
if !absolute.is_yes() {
y += state.pos.1;
}
state.pos.1 = y;
VerticalLineTo { y, absolute: IsAbsolute::Yes }
VerticalLineTo {
y,
absolute: IsAbsolute::Yes,
}
},
CurveTo { mut control1, mut control2, mut point, absolute } => {
CurveTo {
mut control1,
mut control2,
mut point,
absolute,
} => {
if !absolute.is_yes() {
control1 += state.pos;
control2 += state.pos;
point += state.pos;
}
state.pos = point;
CurveTo { control1, control2, point, absolute: IsAbsolute::Yes }
CurveTo {
control1,
control2,
point,
absolute: IsAbsolute::Yes,
}
},
SmoothCurveTo { mut control2, mut point, absolute } => {
SmoothCurveTo {
mut control2,
mut point,
absolute,
} => {
if !absolute.is_yes() {
control2 += state.pos;
point += state.pos;
}
state.pos = point;
SmoothCurveTo { control2, point, absolute: IsAbsolute::Yes }
SmoothCurveTo {
control2,
point,
absolute: IsAbsolute::Yes,
}
},
QuadBezierCurveTo { mut control1, mut point, absolute } => {
QuadBezierCurveTo {
mut control1,
mut point,
absolute,
} => {
if !absolute.is_yes() {
control1 += state.pos;
point += state.pos;
}
state.pos = point;
QuadBezierCurveTo { control1, point, absolute: IsAbsolute::Yes }
QuadBezierCurveTo {
control1,
point,
absolute: IsAbsolute::Yes,
}
},
SmoothQuadBezierCurveTo { mut point, absolute } => {
SmoothQuadBezierCurveTo {
mut point,
absolute,
} => {
if !absolute.is_yes() {
point += state.pos;
}
state.pos = point;
SmoothQuadBezierCurveTo { point, absolute: IsAbsolute::Yes }
SmoothQuadBezierCurveTo {
point,
absolute: IsAbsolute::Yes,
}
},
EllipticalArc { rx, ry, angle, large_arc_flag, sweep_flag, mut point, absolute } => {
EllipticalArc {
rx,
ry,
angle,
large_arc_flag,
sweep_flag,
mut point,
absolute,
} => {
if !absolute.is_yes() {
point += state.pos;
}
state.pos = point;
EllipticalArc {
rx, ry, angle, large_arc_flag, sweep_flag, point, absolute: IsAbsolute::Yes
rx,
ry,
angle,
large_arc_flag,
sweep_flag,
point,
absolute: IsAbsolute::Yes,
}
},
}
@ -268,7 +370,7 @@ impl PathCommand {
impl ToCss for PathCommand {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: fmt::Write
W: fmt::Write,
{
use self::PathCommand::*;
match *self {
@ -278,13 +380,18 @@ impl ToCss for PathCommand {
dest.write_char(if absolute.is_yes() { 'M' } else { 'm' })?;
dest.write_char(' ')?;
point.to_css(dest)
}
},
LineTo { point, absolute } => {
dest.write_char(if absolute.is_yes() { 'L' } else { 'l' })?;
dest.write_char(' ')?;
point.to_css(dest)
}
CurveTo { control1, control2, point, absolute } => {
},
CurveTo {
control1,
control2,
point,
absolute,
} => {
dest.write_char(if absolute.is_yes() { 'C' } else { 'c' })?;
dest.write_char(' ')?;
control1.to_css(dest)?;
@ -293,14 +400,26 @@ impl ToCss for PathCommand {
dest.write_char(' ')?;
point.to_css(dest)
},
QuadBezierCurveTo { control1, point, absolute } => {
QuadBezierCurveTo {
control1,
point,
absolute,
} => {
dest.write_char(if absolute.is_yes() { 'Q' } else { 'q' })?;
dest.write_char(' ')?;
control1.to_css(dest)?;
dest.write_char(' ')?;
point.to_css(dest)
},
EllipticalArc { rx, ry, angle, large_arc_flag, sweep_flag, point, absolute } => {
EllipticalArc {
rx,
ry,
angle,
large_arc_flag,
sweep_flag,
point,
absolute,
} => {
dest.write_char(if absolute.is_yes() { 'A' } else { 'a' })?;
dest.write_char(' ')?;
rx.to_css(dest)?;
@ -325,7 +444,11 @@ impl ToCss for PathCommand {
dest.write_char(' ')?;
y.to_css(dest)
},
SmoothCurveTo { control2, point, absolute } => {
SmoothCurveTo {
control2,
point,
absolute,
} => {
dest.write_char(if absolute.is_yes() { 'S' } else { 's' })?;
dest.write_char(' ')?;
control2.to_css(dest)?;
@ -343,8 +466,17 @@ impl ToCss for PathCommand {
/// The path command absolute type.
#[allow(missing_docs)]
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq,
SpecifiedValueInfo, ToAnimatedZero)]
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedZero,
)]
#[repr(u8)]
pub enum IsAbsolute {
Yes,
@ -360,8 +492,18 @@ impl IsAbsolute {
}
/// The path coord type.
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq,
SpecifiedValueInfo, ToAnimatedZero, ToCss)]
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedZero,
ToCss,
)]
#[repr(C)]
pub struct CoordPair(CSSFloat, CSSFloat);
@ -390,7 +532,7 @@ impl ToCss for ArcFlag {
#[inline]
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: fmt::Write
W: fmt::Write,
{
(self.0 as i32).to_css(dest)
}
@ -403,7 +545,6 @@ impl ComputeSquaredDistance for ArcFlag {
}
}
/// SVG Path parser.
struct PathParser<'a> {
chars: Peekable<Cloned<slice::Iter<'a, u8>>>,
@ -508,12 +649,16 @@ impl<'a> PathParser<'a> {
skip_wsp(&mut self.chars);
let point = parse_coord(&mut self.chars)?;
let absolute = if command == b'M' { IsAbsolute::Yes } else { IsAbsolute::No };
self.path.push(PathCommand::MoveTo { point, absolute } );
let absolute = if command == b'M' {
IsAbsolute::Yes
} else {
IsAbsolute::No
};
self.path.push(PathCommand::MoveTo { point, absolute });
// End of string or the next character is a possible new command.
if !skip_wsp(&mut self.chars) ||
self.chars.peek().map_or(true, |c| c.is_ascii_alphabetic()) {
if !skip_wsp(&mut self.chars) || self.chars.peek().map_or(true, |c| c.is_ascii_alphabetic())
{
return Ok(());
}
skip_comma_wsp(&mut self.chars);
@ -573,11 +718,9 @@ impl<'a> PathParser<'a> {
/// Parse elliptical arc curve command.
fn parse_elliptical_arc(&mut self, absolute: IsAbsolute) -> Result<(), ()> {
// Parse a flag whose value is '0' or '1'; otherwise, return Err(()).
let parse_flag = |iter: &mut Peekable<Cloned<slice::Iter<u8>>>| {
match iter.next() {
Some(c) if c == b'0' || c == b'1' => Ok(ArcFlag(c == b'1')),
_ => Err(()),
}
let parse_flag = |iter: &mut Peekable<Cloned<slice::Iter<u8>>>| match iter.next() {
Some(c) if c == b'0' || c == b'1' => Ok(ArcFlag(c == b'1')),
_ => Err(()),
};
parse_arguments!(self, absolute, EllipticalArc, [
rx => parse_number,
@ -590,7 +733,6 @@ impl<'a> PathParser<'a> {
}
}
/// Parse a pair of numbers into CoordPair.
fn parse_coord(iter: &mut Peekable<Cloned<slice::Iter<u8>>>) -> Result<CoordPair, ()> {
let x = parse_number(iter)?;
@ -608,8 +750,15 @@ fn parse_coord(iter: &mut Peekable<Cloned<slice::Iter<u8>>>) -> Result<CoordPair
/// The "number" syntax in https://www.w3.org/TR/SVG/paths.html#PathDataBNF
fn parse_number(iter: &mut Peekable<Cloned<slice::Iter<u8>>>) -> Result<CSSFloat, ()> {
// 1. Check optional sign.
let sign = if iter.peek().map_or(false, |&sign| sign == b'+' || sign == b'-') {
if iter.next().unwrap() == b'-' { -1. } else { 1. }
let sign = if iter
.peek()
.map_or(false, |&sign| sign == b'+' || sign == b'-')
{
if iter.next().unwrap() == b'-' {
-1.
} else {
1.
}
} else {
1.
};
@ -623,8 +772,7 @@ fn parse_number(iter: &mut Peekable<Cloned<slice::Iter<u8>>>) -> Result<CSSFloat
}
while iter.peek().map_or(false, |n| n.is_ascii_digit()) {
integral_part =
integral_part * 10. + (iter.next().unwrap() - b'0') as f64;
integral_part = integral_part * 10. + (iter.next().unwrap() - b'0') as f64;
}
iter.peek().map_or(false, |&n| n == b'.')
@ -656,8 +804,15 @@ fn parse_number(iter: &mut Peekable<Cloned<slice::Iter<u8>>>) -> Result<CSSFloat
if iter.peek().map_or(false, |&exp| exp == b'E' || exp == b'e') {
// Consume 'E' or 'e'.
iter.next();
let exp_sign = if iter.peek().map_or(false, |&sign| sign == b'+' || sign == b'-') {
if iter.next().unwrap() == b'-' { -1. } else { 1. }
let exp_sign = if iter
.peek()
.map_or(false, |&sign| sign == b'+' || sign == b'-')
{
if iter.next().unwrap() == b'-' {
-1.
} else {
1.
}
} else {
1.
};
@ -671,7 +826,9 @@ fn parse_number(iter: &mut Peekable<Cloned<slice::Iter<u8>>>) -> Result<CSSFloat
}
if value.is_finite() {
Ok(value.min(::std::f32::MAX as f64).max(::std::f32::MIN as f64) as CSSFloat)
Ok(value
.min(::std::f32::MAX as f64)
.max(::std::f32::MIN as f64) as CSSFloat)
} else {
Err(())
}

View file

@ -8,8 +8,9 @@ use cssparser::Parser;
use parser::{Parse, ParserContext};
use style_traits::{ParseError, StyleParseErrorKind};
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo,
ToComputedValue, ToCss)]
#[derive(
Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss,
)]
/// span. for `<col span>` pres attr
pub struct XSpan(#[css(skip)] pub i32);

View file

@ -94,7 +94,10 @@ impl Parse for LineHeight {
{
Ok(GenericLineHeight::MozBlockHeight)
},
ident => Err(location.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone()))),
ident => {
Err(location
.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone())))
},
}
}
}
@ -587,8 +590,7 @@ impl TextEmphasisKeywordValue {
}
/// Fill mode for the text-emphasis-style property
#[derive(Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo,
ToCss)]
#[derive(Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss)]
pub enum TextEmphasisFillMode {
/// `filled`
Filled,
@ -597,8 +599,7 @@ pub enum TextEmphasisFillMode {
}
/// Shape keyword for the text-emphasis-style property
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq,
SpecifiedValueInfo, ToCss)]
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss)]
pub enum TextEmphasisShapeKeyword {
/// `dot`
Dot,
@ -724,8 +725,18 @@ impl Parse for TextEmphasisStyle {
}
/// The allowed horizontal values for the `text-emphasis-position` property.
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq,
SpecifiedValueInfo, ToComputedValue, ToCss)]
#[derive(
Clone,
Copy,
Debug,
Eq,
MallocSizeOf,
Parse,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
pub enum TextEmphasisHorizontalWritingModeValue {
/// Draw marks over the text in horizontal writing mode.
Over,
@ -734,8 +745,18 @@ pub enum TextEmphasisHorizontalWritingModeValue {
}
/// The allowed vertical values for the `text-emphasis-position` property.
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq,
SpecifiedValueInfo, ToComputedValue, ToCss)]
#[derive(
Clone,
Copy,
Debug,
Eq,
MallocSizeOf,
Parse,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
pub enum TextEmphasisVerticalWritingModeValue {
/// Draws marks to the right of the text in vertical writing mode.
Right,
@ -744,8 +765,9 @@ pub enum TextEmphasisVerticalWritingModeValue {
}
/// Specified value of `text-emphasis-position` property.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo,
ToComputedValue, ToCss)]
#[derive(
Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss,
)]
pub struct TextEmphasisPosition(
pub TextEmphasisHorizontalWritingModeValue,
pub TextEmphasisVerticalWritingModeValue,
@ -846,8 +868,7 @@ impl Parse for MozTabSize {
return Ok(GenericMozTabSize::Number(number));
}
Ok(GenericMozTabSize::Length(NonNegativeLength::parse(
context,
input,
context, input,
)?))
}
}

View file

@ -92,7 +92,8 @@ impl Time {
// ParsingMode::DEFAULT directly.
Ok(&Token::Dimension {
value, ref unit, ..
}) if clamping_mode.is_ok(ParsingMode::DEFAULT, value) =>
})
if clamping_mode.is_ok(ParsingMode::DEFAULT, value) =>
{
return Time::parse_dimension(value, unit, /* from_calc = */ false)
.map_err(|()| location.new_custom_error(StyleParseErrorKind::UnspecifiedError));

View file

@ -52,9 +52,8 @@ impl Parse for CursorKind {
) -> Result<Self, ParseError<'i>> {
let location = input.current_source_location();
let ident = input.expect_ident()?;
CursorKind::from_css_keyword(&ident).map_err(|_| {
location.new_custom_error(StyleParseErrorKind::UnspecifiedError)
})
CursorKind::from_css_keyword(&ident)
.map_err(|_| location.new_custom_error(StyleParseErrorKind::UnspecifiedError))
}
}
@ -74,8 +73,7 @@ impl Parse for CursorImage {
}
/// Specified value of `-moz-force-broken-image-icon`
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo,
ToComputedValue)]
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue)]
pub struct MozForceBrokenImageIcon(pub bool);
impl MozForceBrokenImageIcon {