Use the ParserContext along with Parser in the parse function

This commit is contained in:
Ravi Shankar 2016-11-26 14:45:38 +05:30
parent c4f87f451f
commit dee1a65a69
30 changed files with 318 additions and 285 deletions

View file

@ -8,7 +8,7 @@
use Atom; use Atom;
use cssparser::{Delimiter, Parser, SourcePosition, Token, TokenSerializationType}; use cssparser::{Delimiter, Parser, SourcePosition, Token, TokenSerializationType};
use parser::Parse; use parser::{Parse, ParserContext};
use properties::DeclaredValue; use properties::DeclaredValue;
use std::ascii::AsciiExt; use std::ascii::AsciiExt;
use std::borrow::Cow; use std::borrow::Cow;
@ -113,7 +113,7 @@ impl ComputedValue {
} }
impl Parse for SpecifiedValue { impl Parse for SpecifiedValue {
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
let mut references = Some(HashSet::new()); let mut references = Some(HashSet::new());
let (first, css, last) = try!(parse_self_contained_declaration_value(input, &mut references)); let (first, css, last) = try!(parse_self_contained_declaration_value(input, &mut references));
Ok(SpecifiedValue { Ok(SpecifiedValue {

View file

@ -69,8 +69,6 @@ pub fn log_css_error(input: &mut Parser, position: SourcePosition, message: &str
// XXXManishearth Replace all specified value parse impls with impls of this // XXXManishearth Replace all specified value parse impls with impls of this
// trait. This will make it easy to write more generic values in the future. // trait. This will make it easy to write more generic values in the future.
// There may need to be two traits -- one for parsing with context, and one
// for parsing without
pub trait Parse { pub trait Parse {
fn parse(input: &mut Parser) -> Result<Self, ()> where Self: Sized; fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> where Self: Sized;
} }

View file

@ -16,7 +16,7 @@
</%call> </%call>
</%def> </%def>
<%def name="predefined_type(name, type, initial_value, parse_method='parse', needs_context=False, **kwargs)"> <%def name="predefined_type(name, type, initial_value, parse_method='parse', needs_context=True, **kwargs)">
<%call expr="longhand(name, predefined_type=type, **kwargs)"> <%call expr="longhand(name, predefined_type=type, **kwargs)">
#[allow(unused_imports)] #[allow(unused_imports)]
use app_units::Au; use app_units::Au;
@ -283,7 +283,7 @@
% if not property.derived_from: % if not property.derived_from:
pub fn parse_declared(context: &ParserContext, input: &mut Parser) pub fn parse_declared(context: &ParserContext, input: &mut Parser)
-> Result<DeclaredValue<SpecifiedValue>, ()> { -> Result<DeclaredValue<SpecifiedValue>, ()> {
match input.try(CSSWideKeyword::parse) { match input.try(|i| CSSWideKeyword::parse(context, i)) {
Ok(CSSWideKeyword::InheritKeyword) => Ok(DeclaredValue::Inherit), Ok(CSSWideKeyword::InheritKeyword) => Ok(DeclaredValue::Inherit),
Ok(CSSWideKeyword::InitialKeyword) => Ok(DeclaredValue::Initial), Ok(CSSWideKeyword::InitialKeyword) => Ok(DeclaredValue::Initial),
Ok(CSSWideKeyword::UnsetKeyword) => Ok(DeclaredValue::${ Ok(CSSWideKeyword::UnsetKeyword) => Ok(DeclaredValue::${
@ -515,7 +515,7 @@
% endif % endif
</%def> </%def>
<%def name="four_sides_shorthand(name, sub_property_pattern, parser_function)"> <%def name="four_sides_shorthand(name, sub_property_pattern, parser_function, needs_context=True)">
<%self:shorthand name="${name}" sub_properties="${ <%self:shorthand name="${name}" sub_properties="${
' '.join(sub_property_pattern % side ' '.join(sub_property_pattern % side
for side in ['top', 'right', 'bottom', 'left'])}"> for side in ['top', 'right', 'bottom', 'left'])}">
@ -524,8 +524,14 @@
use super::parse_four_sides; use super::parse_four_sides;
use values::specified; use values::specified;
pub fn parse_value(_: &ParserContext, input: &mut Parser) -> Result<Longhands, ()> { pub fn parse_value(context: &ParserContext, input: &mut Parser) -> Result<Longhands, ()> {
let (top, right, bottom, left) = try!(parse_four_sides(input, ${parser_function})); let (top, right, bottom, left) =
% if needs_context:
try!(parse_four_sides(input, |i| ${parser_function}(context, i)));
% else:
try!(parse_four_sides(input, ${parser_function}));
let _unused = context;
% endif
Ok(Longhands { Ok(Longhands {
% for side in ["top", "right", "bottom", "left"]: % for side in ["top", "right", "bottom", "left"]:
${to_rust_ident(sub_property_pattern % side)}: Some(${side}), ${to_rust_ident(sub_property_pattern % side)}: Some(${side}),

View file

@ -120,9 +120,9 @@ ${helpers.predefined_type("background-color", "CSSColor",
} }
} }
pub fn parse(_context: &ParserContext, input: &mut Parser) pub fn parse(context: &ParserContext, input: &mut Parser)
-> Result<SpecifiedValue, ()> { -> Result<SpecifiedValue, ()> {
Ok(try!(Position::parse(input))) Ok(try!(Position::parse(context, input)))
} }
</%helpers:vector_longhand> </%helpers:vector_longhand>
@ -302,7 +302,7 @@ ${helpers.single_keyword("background-origin",
}) })
} }
pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> {
let width; let width;
if let Ok(value) = input.try(|input| { if let Ok(value) = input.try(|input| {
match input.next() { match input.next() {
@ -318,7 +318,7 @@ ${helpers.single_keyword("background-origin",
}) { }) {
return Ok(value) return Ok(value)
} else { } else {
width = try!(specified::LengthOrPercentageOrAuto::parse(input)) width = try!(specified::LengthOrPercentageOrAuto::parse(context, input))
} }
let height; let height;
@ -330,7 +330,7 @@ ${helpers.single_keyword("background-origin",
}) { }) {
height = value height = value
} else { } else {
height = try!(specified::LengthOrPercentageOrAuto::parse(input)); height = try!(specified::LengthOrPercentageOrAuto::parse(context, input));
} }
Ok(SpecifiedValue::Explicit(ExplicitSize { Ok(SpecifiedValue::Explicit(ExplicitSize {

View file

@ -18,7 +18,8 @@
% for side in ALL_SIDES: % for side in ALL_SIDES:
${helpers.predefined_type("border-%s-style" % side[0], "BorderStyle", ${helpers.predefined_type("border-%s-style" % side[0], "BorderStyle",
"specified::BorderStyle::none", "specified::BorderStyle::none",
need_clone=True, animatable=False, logical = side[1])} needs_context=False, need_clone=True,
animatable=False, logical = side[1])}
% endfor % endfor
% for side in ALL_SIDES: % for side in ALL_SIDES:
@ -32,9 +33,9 @@
pub type SpecifiedValue = BorderWidth; pub type SpecifiedValue = BorderWidth;
#[inline] #[inline]
pub fn parse(_context: &ParserContext, input: &mut Parser) pub fn parse(context: &ParserContext, input: &mut Parser)
-> Result<SpecifiedValue, ()> { -> Result<SpecifiedValue, ()> {
BorderWidth::parse(input) BorderWidth::parse(context, input)
} }
pub mod computed_value { pub mod computed_value {
@ -503,12 +504,12 @@ ${helpers.single_keyword("-moz-float-edge", "content-box margin-box",
} }
impl Parse for SingleSpecifiedValue { impl Parse for SingleSpecifiedValue {
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
if input.try(|input| input.expect_ident_matching("auto")).is_ok() { if input.try(|input| input.expect_ident_matching("auto")).is_ok() {
return Ok(SingleSpecifiedValue::Auto); return Ok(SingleSpecifiedValue::Auto);
} }
if let Ok(len) = input.try(|input| LengthOrPercentage::parse(input)) { if let Ok(len) = input.try(|input| LengthOrPercentage::parse(context, input)) {
return Ok(SingleSpecifiedValue::LengthOrPercentage(len)); return Ok(SingleSpecifiedValue::LengthOrPercentage(len));
} }
@ -517,10 +518,10 @@ ${helpers.single_keyword("-moz-float-edge", "content-box margin-box",
} }
} }
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
let mut values = vec![]; let mut values = vec![];
for _ in 0..4 { for _ in 0..4 {
let value = input.try(|input| SingleSpecifiedValue::parse(input)); let value = input.try(|input| SingleSpecifiedValue::parse(context, input));
match value { match value {
Ok(val) => values.push(val), Ok(val) => values.push(val),
Err(_) => break, Err(_) => break,
@ -709,8 +710,8 @@ ${helpers.single_keyword("-moz-float-edge", "content-box margin-box",
} }
impl Parse for PercentageOrNumber { impl Parse for PercentageOrNumber {
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
if let Ok(per) = input.try(|input| Percentage::parse(input)) { if let Ok(per) = input.try(|input| Percentage::parse(context, input)) {
return Ok(PercentageOrNumber::Percentage(per)); return Ok(PercentageOrNumber::Percentage(per));
} }
@ -719,12 +720,12 @@ ${helpers.single_keyword("-moz-float-edge", "content-box margin-box",
} }
} }
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
let mut fill = input.try(|input| input.expect_ident_matching("fill")).is_ok(); let mut fill = input.try(|input| input.expect_ident_matching("fill")).is_ok();
let mut values = vec![]; let mut values = vec![];
for _ in 0..4 { for _ in 0..4 {
let value = input.try(|input| PercentageOrNumber::parse(input)); let value = input.try(|input| PercentageOrNumber::parse(context, input));
match value { match value {
Ok(val) => values.push(val), Ok(val) => values.push(val),
Err(_) => break, Err(_) => break,

View file

@ -183,8 +183,8 @@ ${helpers.single_keyword("clear", "none left right both",
} }
/// baseline | sub | super | top | text-top | middle | bottom | text-bottom /// baseline | sub | super | top | text-top | middle | bottom | text-bottom
/// | <percentage> | <length> /// | <percentage> | <length>
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
input.try(specified::LengthOrPercentage::parse) input.try(|i| specified::LengthOrPercentage::parse(context, i))
.map(SpecifiedValue::LengthOrPercentage) .map(SpecifiedValue::LengthOrPercentage)
.or_else(|()| { .or_else(|()| {
match_ignore_ascii_case! { try!(input.expect_ident()), match_ignore_ascii_case! { try!(input.expect_ident()),
@ -359,8 +359,8 @@ ${helpers.single_keyword("overflow-x", "visible hidden scroll auto",
computed_value::T(vec![get_initial_single_value()]) computed_value::T(vec![get_initial_single_value()])
} }
pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> {
Ok(SpecifiedValue(try!(input.parse_comma_separated(Time::parse)))) Ok(SpecifiedValue(try!(input.parse_comma_separated(|i| Time::parse(context, i)))))
} }
</%helpers:longhand> </%helpers:longhand>
@ -416,7 +416,7 @@ ${helpers.single_keyword("overflow-x", "visible hidden scroll auto",
pub mod computed_value { pub mod computed_value {
use euclid::point::Point2D; use euclid::point::Point2D;
use parser::Parse; use parser::{Parse, ParserContext};
use std::fmt; use std::fmt;
use style_traits::ToCss; use style_traits::ToCss;
use values::specified; use values::specified;
@ -432,7 +432,7 @@ ${helpers.single_keyword("overflow-x", "visible hidden scroll auto",
} }
impl Parse for TransitionTimingFunction { impl Parse for TransitionTimingFunction {
fn parse(input: &mut ::cssparser::Parser) -> Result<Self, ()> { fn parse(_context: &ParserContext, input: &mut ::cssparser::Parser) -> Result<Self, ()> {
if let Ok(function_name) = input.try(|input| input.expect_function()) { if let Ok(function_name) = input.try(|input| input.expect_function()) {
return match_ignore_ascii_case! { function_name, return match_ignore_ascii_case! { function_name,
"cubic-bezier" => { "cubic-bezier" => {
@ -559,8 +559,10 @@ ${helpers.single_keyword("overflow-x", "visible hidden scroll auto",
computed_value::T(vec![get_initial_single_value()]) computed_value::T(vec![get_initial_single_value()])
} }
pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> {
Ok(SpecifiedValue(try!(input.parse_comma_separated(TransitionTimingFunction::parse)))) Ok(SpecifiedValue(try!(input.parse_comma_separated(|i| {
TransitionTimingFunction::parse(context, i)
}))))
} }
</%helpers:longhand> </%helpers:longhand>
@ -606,7 +608,7 @@ ${helpers.single_keyword("overflow-x", "visible hidden scroll auto",
computed_value::T(Vec::new()) computed_value::T(Vec::new())
} }
pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> {
Ok(SpecifiedValue(try!(input.parse_comma_separated(SingleSpecifiedValue::parse)))) Ok(SpecifiedValue(try!(input.parse_comma_separated(SingleSpecifiedValue::parse))))
} }
@ -633,7 +635,7 @@ ${helpers.single_keyword("overflow-x", "visible hidden scroll auto",
pub mod computed_value { pub mod computed_value {
use Atom; use Atom;
use parser::Parse; use parser::{Parse, ParserContext};
use std::fmt; use std::fmt;
use std::ops::Deref; use std::ops::Deref;
use style_traits::ToCss; use style_traits::ToCss;
@ -651,7 +653,7 @@ ${helpers.single_keyword("overflow-x", "visible hidden scroll auto",
pub use self::AnimationName as SingleComputedValue; pub use self::AnimationName as SingleComputedValue;
impl Parse for AnimationName { impl Parse for AnimationName {
fn parse(input: &mut ::cssparser::Parser) -> Result<Self, ()> { fn parse(_context: &ParserContext, input: &mut ::cssparser::Parser) -> Result<Self, ()> {
use cssparser::Token; use cssparser::Token;
Ok(match input.next() { Ok(match input.next() {
Ok(Token::Ident(ref value)) if value != "none" => AnimationName(Atom::from(&**value)), Ok(Token::Ident(ref value)) if value != "none" => AnimationName(Atom::from(&**value)),
@ -692,9 +694,9 @@ ${helpers.single_keyword("overflow-x", "visible hidden scroll auto",
computed_value::T(vec![]) computed_value::T(vec![])
} }
pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> {
use std::borrow::Cow; use std::borrow::Cow;
Ok(SpecifiedValue(try!(input.parse_comma_separated(SingleSpecifiedValue::parse)))) Ok(SpecifiedValue(try!(input.parse_comma_separated(|i| SingleSpecifiedValue::parse(context, i)))))
} }
impl ComputedValueAsSpecified for SpecifiedValue {} impl ComputedValueAsSpecified for SpecifiedValue {}
@ -728,7 +730,7 @@ ${helpers.single_keyword("overflow-x", "visible hidden scroll auto",
use values::NoViewportPercentage; use values::NoViewportPercentage;
pub mod computed_value { pub mod computed_value {
use parser::Parse; use parser::{Parse, ParserContext};
use std::fmt; use std::fmt;
use style_traits::ToCss; use style_traits::ToCss;
@ -742,7 +744,7 @@ ${helpers.single_keyword("overflow-x", "visible hidden scroll auto",
} }
impl Parse for AnimationIterationCount { impl Parse for AnimationIterationCount {
fn parse(input: &mut ::cssparser::Parser) -> Result<Self, ()> { fn parse(_context: &ParserContext, input: &mut ::cssparser::Parser) -> Result<Self, ()> {
if input.try(|input| input.expect_ident_matching("infinite")).is_ok() { if input.try(|input| input.expect_ident_matching("infinite")).is_ok() {
return Ok(AnimationIterationCount::Infinite) return Ok(AnimationIterationCount::Infinite)
} }
@ -796,8 +798,10 @@ ${helpers.single_keyword("overflow-x", "visible hidden scroll auto",
} }
#[inline] #[inline]
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
Ok(SpecifiedValue(try!(input.parse_comma_separated(AnimationIterationCount::parse)))) Ok(SpecifiedValue(try!(input.parse_comma_separated(|i| {
AnimationIterationCount::parse(context, i)
}))))
} }
#[inline] #[inline]
@ -997,13 +1001,13 @@ ${helpers.single_keyword("animation-fill-mode",
pub use self::computed_value::ComputedMatrix as SpecifiedMatrix; pub use self::computed_value::ComputedMatrix as SpecifiedMatrix;
fn parse_two_lengths_or_percentages(input: &mut Parser) fn parse_two_lengths_or_percentages(context: &ParserContext, input: &mut Parser)
-> Result<(specified::LengthOrPercentage, -> Result<(specified::LengthOrPercentage,
specified::LengthOrPercentage),()> { specified::LengthOrPercentage),()> {
let first = try!(specified::LengthOrPercentage::parse(input)); let first = try!(specified::LengthOrPercentage::parse(context, input));
let second = input.try(|input| { let second = input.try(|input| {
try!(input.expect_comma()); try!(input.expect_comma());
specified::LengthOrPercentage::parse(input) specified::LengthOrPercentage::parse(context, input)
}).unwrap_or(specified::LengthOrPercentage::zero()); }).unwrap_or(specified::LengthOrPercentage::zero());
Ok((first, second)) Ok((first, second))
} }
@ -1017,11 +1021,12 @@ ${helpers.single_keyword("animation-fill-mode",
Ok((first, second)) Ok((first, second))
} }
fn parse_two_angles(input: &mut Parser) -> Result<(specified::Angle, specified::Angle),()> { fn parse_two_angles(context: &ParserContext, input: &mut Parser)
let first = try!(specified::Angle::parse(input)); -> Result<(specified::Angle, specified::Angle),()> {
let first = try!(specified::Angle::parse(context, input));
let second = input.try(|input| { let second = input.try(|input| {
try!(input.expect_comma()); try!(input.expect_comma());
specified::Angle::parse(input) specified::Angle::parse(context, input)
}).unwrap_or(specified::Angle(0.0)); }).unwrap_or(specified::Angle(0.0));
Ok((first, second)) Ok((first, second))
} }
@ -1160,7 +1165,7 @@ ${helpers.single_keyword("animation-fill-mode",
computed_value::T(None) computed_value::T(None)
} }
pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> {
if input.try(|input| input.expect_ident_matching("none")).is_ok() { if input.try(|input| input.expect_ident_matching("none")).is_ok() {
return Ok(SpecifiedValue(Vec::new())) return Ok(SpecifiedValue(Vec::new()))
} }
@ -1211,7 +1216,7 @@ ${helpers.single_keyword("animation-fill-mode",
}, },
"translate" => { "translate" => {
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
let (tx, ty) = try!(parse_two_lengths_or_percentages(input)); let (tx, ty) = try!(parse_two_lengths_or_percentages(context, input));
result.push(SpecifiedOperation::Translate(TranslateKind::Translate, result.push(SpecifiedOperation::Translate(TranslateKind::Translate,
tx, tx,
ty, ty,
@ -1221,7 +1226,7 @@ ${helpers.single_keyword("animation-fill-mode",
}, },
"translatex" => { "translatex" => {
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
let tx = try!(specified::LengthOrPercentage::parse(input)); let tx = try!(specified::LengthOrPercentage::parse(context, input));
result.push(SpecifiedOperation::Translate( result.push(SpecifiedOperation::Translate(
TranslateKind::TranslateX, TranslateKind::TranslateX,
tx, tx,
@ -1232,7 +1237,7 @@ ${helpers.single_keyword("animation-fill-mode",
}, },
"translatey" => { "translatey" => {
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
let ty = try!(specified::LengthOrPercentage::parse(input)); let ty = try!(specified::LengthOrPercentage::parse(context, input));
result.push(SpecifiedOperation::Translate( result.push(SpecifiedOperation::Translate(
TranslateKind::TranslateY, TranslateKind::TranslateY,
specified::LengthOrPercentage::zero(), specified::LengthOrPercentage::zero(),
@ -1243,7 +1248,7 @@ ${helpers.single_keyword("animation-fill-mode",
}, },
"translatez" => { "translatez" => {
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
let tz = try!(specified::Length::parse(input)); let tz = try!(specified::Length::parse(context, input));
result.push(SpecifiedOperation::Translate( result.push(SpecifiedOperation::Translate(
TranslateKind::TranslateZ, TranslateKind::TranslateZ,
specified::LengthOrPercentage::zero(), specified::LengthOrPercentage::zero(),
@ -1254,11 +1259,11 @@ ${helpers.single_keyword("animation-fill-mode",
}, },
"translate3d" => { "translate3d" => {
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
let tx = try!(specified::LengthOrPercentage::parse(input)); let tx = try!(specified::LengthOrPercentage::parse(context, input));
try!(input.expect_comma()); try!(input.expect_comma());
let ty = try!(specified::LengthOrPercentage::parse(input)); let ty = try!(specified::LengthOrPercentage::parse(context, input));
try!(input.expect_comma()); try!(input.expect_comma());
let tz = try!(specified::Length::parse(input)); let tz = try!(specified::Length::parse(context, input));
result.push(SpecifiedOperation::Translate( result.push(SpecifiedOperation::Translate(
TranslateKind::Translate3D, TranslateKind::Translate3D,
tx, tx,
@ -1309,28 +1314,28 @@ ${helpers.single_keyword("animation-fill-mode",
}, },
"rotate" => { "rotate" => {
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
let theta = try!(specified::Angle::parse(input)); let theta = try!(specified::Angle::parse(context,input));
result.push(SpecifiedOperation::Rotate(0.0, 0.0, 1.0, theta)); result.push(SpecifiedOperation::Rotate(0.0, 0.0, 1.0, theta));
Ok(()) Ok(())
})) }))
}, },
"rotatex" => { "rotatex" => {
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
let theta = try!(specified::Angle::parse(input)); let theta = try!(specified::Angle::parse(context,input));
result.push(SpecifiedOperation::Rotate(1.0, 0.0, 0.0, theta)); result.push(SpecifiedOperation::Rotate(1.0, 0.0, 0.0, theta));
Ok(()) Ok(())
})) }))
}, },
"rotatey" => { "rotatey" => {
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
let theta = try!(specified::Angle::parse(input)); let theta = try!(specified::Angle::parse(context,input));
result.push(SpecifiedOperation::Rotate(0.0, 1.0, 0.0, theta)); result.push(SpecifiedOperation::Rotate(0.0, 1.0, 0.0, theta));
Ok(()) Ok(())
})) }))
}, },
"rotatez" => { "rotatez" => {
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
let theta = try!(specified::Angle::parse(input)); let theta = try!(specified::Angle::parse(context,input));
result.push(SpecifiedOperation::Rotate(0.0, 0.0, 1.0, theta)); result.push(SpecifiedOperation::Rotate(0.0, 0.0, 1.0, theta));
Ok(()) Ok(())
})) }))
@ -1343,7 +1348,7 @@ ${helpers.single_keyword("animation-fill-mode",
try!(input.expect_comma()); try!(input.expect_comma());
let az = try!(specified::parse_number(input)); let az = try!(specified::parse_number(input));
try!(input.expect_comma()); try!(input.expect_comma());
let theta = try!(specified::Angle::parse(input)); let theta = try!(specified::Angle::parse(context,input));
// TODO(gw): Check the axis can be normalized!! // TODO(gw): Check the axis can be normalized!!
result.push(SpecifiedOperation::Rotate(ax, ay, az, theta)); result.push(SpecifiedOperation::Rotate(ax, ay, az, theta));
Ok(()) Ok(())
@ -1351,28 +1356,28 @@ ${helpers.single_keyword("animation-fill-mode",
}, },
"skew" => { "skew" => {
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
let (theta_x, theta_y) = try!(parse_two_angles(input)); let (theta_x, theta_y) = try!(parse_two_angles(context, input));
result.push(SpecifiedOperation::Skew(theta_x, theta_y)); result.push(SpecifiedOperation::Skew(theta_x, theta_y));
Ok(()) Ok(())
})) }))
}, },
"skewx" => { "skewx" => {
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
let theta_x = try!(specified::Angle::parse(input)); let theta_x = try!(specified::Angle::parse(context,input));
result.push(SpecifiedOperation::Skew(theta_x, specified::Angle(0.0))); result.push(SpecifiedOperation::Skew(theta_x, specified::Angle(0.0)));
Ok(()) Ok(())
})) }))
}, },
"skewy" => { "skewy" => {
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
let theta_y = try!(specified::Angle::parse(input)); let theta_y = try!(specified::Angle::parse(context,input));
result.push(SpecifiedOperation::Skew(specified::Angle(0.0), theta_y)); result.push(SpecifiedOperation::Skew(specified::Angle(0.0), theta_y));
Ok(()) Ok(())
})) }))
}, },
"perspective" => { "perspective" => {
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
let d = try!(specified::Length::parse(input)); let d = try!(specified::Length::parse(context, input));
result.push(SpecifiedOperation::Perspective(d)); result.push(SpecifiedOperation::Perspective(d));
Ok(()) Ok(())
})) }))
@ -1547,7 +1552,6 @@ ${helpers.single_keyword("-moz-appearance",
// Non-standard: https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-binding // Non-standard: https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-binding
${helpers.predefined_type("-moz-binding", "UrlOrNone", "computed_value::T::None", ${helpers.predefined_type("-moz-binding", "UrlOrNone", "computed_value::T::None",
needs_context=True,
products="gecko", products="gecko",
animatable="False", animatable="False",
disable_when_testing="True")} disable_when_testing="True")}

View file

@ -37,9 +37,9 @@
pub fn get_initial_value() -> computed_value::T { pub fn get_initial_value() -> computed_value::T {
RGBA { red: 0., green: 0., blue: 0., alpha: 1. } /* black */ RGBA { red: 0., green: 0., blue: 0., alpha: 1. } /* black */
} }
pub fn parse_specified(_context: &ParserContext, input: &mut Parser) pub fn parse_specified(context: &ParserContext, input: &mut Parser)
-> Result<DeclaredValue<SpecifiedValue>, ()> { -> Result<DeclaredValue<SpecifiedValue>, ()> {
let value = try!(CSSColor::parse(input)); let value = try!(CSSColor::parse(context, input));
let rgba = match value.parsed { let rgba = match value.parsed {
CSSParserColor::RGBA(rgba) => rgba, CSSParserColor::RGBA(rgba) => rgba,
CSSParserColor::CurrentColor => return Ok(DeclaredValue::Inherit) CSSParserColor::CurrentColor => return Ok(DeclaredValue::Inherit)

View file

@ -273,8 +273,8 @@ ${helpers.single_keyword("column-fill", "auto balance",
Au::from_px(3) // medium Au::from_px(3) // medium
} }
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
BorderWidth::parse(input) BorderWidth::parse(context, input)
} }
</%helpers:longhand> </%helpers:longhand>

View file

@ -125,7 +125,7 @@ ${helpers.predefined_type("opacity",
} }
} }
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
use app_units::Au; use app_units::Au;
let mut lengths = [specified::Length::Absolute(Au(0)); 4]; let mut lengths = [specified::Length::Absolute(Au(0)); 4];
let mut lengths_parsed = false; let mut lengths_parsed = false;
@ -140,11 +140,11 @@ ${helpers.predefined_type("opacity",
} }
} }
if !lengths_parsed { if !lengths_parsed {
if let Ok(value) = input.try(specified::Length::parse) { if let Ok(value) = input.try(|i| specified::Length::parse(context, i)) {
lengths[0] = value; lengths[0] = value;
let mut length_parsed_count = 1; let mut length_parsed_count = 1;
while length_parsed_count < 4 { while length_parsed_count < 4 {
if let Ok(value) = input.try(specified::Length::parse) { if let Ok(value) = input.try(|i| specified::Length::parse(context, i)) {
lengths[length_parsed_count] = value lengths[length_parsed_count] = value
} else { } else {
break break
@ -162,7 +162,7 @@ ${helpers.predefined_type("opacity",
} }
} }
if color.is_none() { if color.is_none() {
if let Ok(value) = input.try(specified::CSSColor::parse) { if let Ok(value) = input.try(|i| specified::CSSColor::parse(context, i)) {
color = Some(value); color = Some(value);
continue continue
} }
@ -352,16 +352,16 @@ ${helpers.predefined_type("opacity",
} }
} }
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
use app_units::Au; use app_units::Au;
use std::ascii::AsciiExt; use std::ascii::AsciiExt;
use values::specified::Length; use values::specified::Length;
fn parse_argument(input: &mut Parser) -> Result<Option<Length>, ()> { fn parse_argument(context: &ParserContext, input: &mut Parser) -> Result<Option<Length>, ()> {
if input.try(|input| input.expect_ident_matching("auto")).is_ok() { if input.try(|input| input.expect_ident_matching("auto")).is_ok() {
Ok(None) Ok(None)
} else { } else {
Length::parse(input).map(Some) Length::parse(context, input).map(Some)
} }
} }
@ -373,21 +373,21 @@ ${helpers.predefined_type("opacity",
} }
input.parse_nested_block(|input| { input.parse_nested_block(|input| {
let top = try!(parse_argument(input)); let top = try!(parse_argument(context, input));
let right; let right;
let bottom; let bottom;
let left; let left;
if input.try(|input| input.expect_comma()).is_ok() { if input.try(|input| input.expect_comma()).is_ok() {
right = try!(parse_argument(input)); right = try!(parse_argument(context, input));
try!(input.expect_comma()); try!(input.expect_comma());
bottom = try!(parse_argument(input)); bottom = try!(parse_argument(context, input));
try!(input.expect_comma()); try!(input.expect_comma());
left = try!(parse_argument(input)); left = try!(parse_argument(context, input));
} else { } else {
right = try!(parse_argument(input)); right = try!(parse_argument(context, input));
bottom = try!(parse_argument(input)); bottom = try!(parse_argument(context, input));
left = try!(parse_argument(input)); left = try!(parse_argument(context, input));
} }
Ok(SpecifiedValue(Some(SpecifiedClipRect { Ok(SpecifiedValue(Some(SpecifiedClipRect {
top: top.unwrap_or(Length::Absolute(Au(0))), top: top.unwrap_or(Length::Absolute(Au(0))),
@ -627,7 +627,7 @@ ${helpers.predefined_type("opacity",
computed_value::T::new(Vec::new()) computed_value::T::new(Vec::new())
} }
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
let mut filters = Vec::new(); let mut filters = Vec::new();
if input.try(|input| input.expect_ident_matching("none")).is_ok() { if input.try(|input| input.expect_ident_matching("none")).is_ok() {
return Ok(SpecifiedValue(filters)) return Ok(SpecifiedValue(filters))
@ -640,13 +640,13 @@ ${helpers.predefined_type("opacity",
"brightness" => parse_factor(input).map(SpecifiedFilter::Brightness), "brightness" => parse_factor(input).map(SpecifiedFilter::Brightness),
"contrast" => parse_factor(input).map(SpecifiedFilter::Contrast), "contrast" => parse_factor(input).map(SpecifiedFilter::Contrast),
"grayscale" => parse_factor(input).map(SpecifiedFilter::Grayscale), "grayscale" => parse_factor(input).map(SpecifiedFilter::Grayscale),
"hue-rotate" => Angle::parse(input).map(SpecifiedFilter::HueRotate), "hue-rotate" => Angle::parse(context, input).map(SpecifiedFilter::HueRotate),
"invert" => parse_factor(input).map(SpecifiedFilter::Invert), "invert" => parse_factor(input).map(SpecifiedFilter::Invert),
"opacity" => parse_factor(input).map(SpecifiedFilter::Opacity), "opacity" => parse_factor(input).map(SpecifiedFilter::Opacity),
"saturate" => parse_factor(input).map(SpecifiedFilter::Saturate), "saturate" => parse_factor(input).map(SpecifiedFilter::Saturate),
"sepia" => parse_factor(input).map(SpecifiedFilter::Sepia), "sepia" => parse_factor(input).map(SpecifiedFilter::Sepia),
% if product == "gecko": % if product == "gecko":
"drop-shadow" => parse_drop_shadow(input), "drop-shadow" => parse_drop_shadow(context, input),
% endif % endif
_ => Err(()) _ => Err(())
} }
@ -669,11 +669,12 @@ ${helpers.predefined_type("opacity",
} }
% if product == "gecko": % if product == "gecko":
fn parse_drop_shadow(input: &mut Parser) -> Result<SpecifiedFilter, ()> { fn parse_drop_shadow(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedFilter, ()> {
let offset_x = try!(specified::Length::parse(input)); let offset_x = try!(specified::Length::parse(context, input));
let offset_y = try!(specified::Length::parse(input)); let offset_y = try!(specified::Length::parse(context, input));
let blur_radius = input.try(specified::Length::parse).unwrap_or(specified::Length::from_px(0.0)); let blur_radius = input.try(|i| specified::Length::parse(context, i))
let color = input.try(specified::CSSColor::parse).ok(); .unwrap_or(specified::Length::from_px(0.0));
let color = input.try(|i| specified::CSSColor::parse(context, i)).ok();
Ok(SpecifiedFilter::DropShadow(offset_x, offset_y, blur_radius, color)) Ok(SpecifiedFilter::DropShadow(offset_x, offset_y, blur_radius, color))
} }
% endif % endif
@ -745,7 +746,7 @@ pub struct OriginParseResult {
pub depth: Option<specified::Length> pub depth: Option<specified::Length>
} }
pub fn parse_origin(_: &ParserContext, input: &mut Parser) -> Result<OriginParseResult,()> { pub fn parse_origin(context: &ParserContext, input: &mut Parser) -> Result<OriginParseResult,()> {
use values::specified::{LengthOrPercentage, Percentage}; use values::specified::{LengthOrPercentage, Percentage};
let (mut horizontal, mut vertical, mut depth) = (None, None, None); let (mut horizontal, mut vertical, mut depth) = (None, None, None);
loop { loop {
@ -794,7 +795,7 @@ pub fn parse_origin(_: &ParserContext, input: &mut Parser) -> Result<OriginParse
} }
Ok(()) Ok(())
}) { }) {
match LengthOrPercentage::parse(input) { match LengthOrPercentage::parse(context, input) {
Ok(value) => { Ok(value) => {
if horizontal.is_none() { if horizontal.is_none() {
horizontal = Some(value); horizontal = Some(value);

View file

@ -510,7 +510,7 @@ ${helpers.single_keyword("font-variant-position",
pub mod computed_value { pub mod computed_value {
use cssparser::Parser; use cssparser::Parser;
use parser::Parse; use parser::{Parse, ParserContext};
use std::fmt; use std::fmt;
use style_traits::ToCss; use style_traits::ToCss;
@ -560,7 +560,7 @@ ${helpers.single_keyword("font-variant-position",
impl Parse for FeatureTagValue { impl Parse for FeatureTagValue {
/// https://www.w3.org/TR/css-fonts-3/#propdef-font-feature-settings /// https://www.w3.org/TR/css-fonts-3/#propdef-font-feature-settings
/// <string> [ on | off | <integer> ] /// <string> [ on | off | <integer> ]
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
let tag = try!(input.expect_string()); let tag = try!(input.expect_string());
// allowed strings of length 4 containing chars: <U+20, U+7E> // allowed strings of length 4 containing chars: <U+20, U+7E>
@ -597,11 +597,11 @@ ${helpers.single_keyword("font-variant-position",
} }
/// normal | <feature-tag-value># /// normal | <feature-tag-value>#
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
if input.try(|input| input.expect_ident_matching("normal")).is_ok() { if input.try(|input| input.expect_ident_matching("normal")).is_ok() {
Ok(computed_value::T::Normal) Ok(computed_value::T::Normal)
} else { } else {
input.parse_comma_separated(computed_value::FeatureTagValue::parse) input.parse_comma_separated(|i| computed_value::FeatureTagValue::parse(context, i))
.map(computed_value::T::Tag) .map(computed_value::T::Tag)
} }
} }

View file

@ -50,6 +50,7 @@ ${helpers.single_keyword("stroke-linejoin", "miter round bevel",
${helpers.predefined_type("stroke-miterlimit", "Number", "4.0", ${helpers.predefined_type("stroke-miterlimit", "Number", "4.0",
"parse_at_least_one", products="gecko", "parse_at_least_one", products="gecko",
needs_context=False,
animatable=False)} animatable=False)}
${helpers.predefined_type("stroke-opacity", "Opacity", "1.0", ${helpers.predefined_type("stroke-opacity", "Opacity", "1.0",

View file

@ -200,8 +200,7 @@
#[inline] pub fn get_initial_value() -> computed_value::T { #[inline] pub fn get_initial_value() -> computed_value::T {
computed_value::T::start computed_value::T::start
} }
pub fn parse(_context: &ParserContext, input: &mut Parser) pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
-> Result<SpecifiedValue, ()> {
computed_value::T::parse(input) computed_value::T::parse(input)
} }
</%helpers:longhand> </%helpers:longhand>
@ -645,15 +644,15 @@ ${helpers.single_keyword("text-align-last",
computed_value::T(Vec::new()) computed_value::T(Vec::new())
} }
pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> {
if input.try(|input| input.expect_ident_matching("none")).is_ok() { if input.try(|input| input.expect_ident_matching("none")).is_ok() {
Ok(SpecifiedValue(Vec::new())) Ok(SpecifiedValue(Vec::new()))
} else { } else {
input.parse_comma_separated(parse_one_text_shadow).map(SpecifiedValue) input.parse_comma_separated(|i| parse_one_text_shadow(context, i)).map(SpecifiedValue)
} }
} }
fn parse_one_text_shadow(input: &mut Parser) -> Result<SpecifiedTextShadow,()> { fn parse_one_text_shadow(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedTextShadow,()> {
use app_units::Au; use app_units::Au;
let mut lengths = [specified::Length::Absolute(Au(0)); 3]; let mut lengths = [specified::Length::Absolute(Au(0)); 3];
let mut lengths_parsed = false; let mut lengths_parsed = false;
@ -661,11 +660,11 @@ ${helpers.single_keyword("text-align-last",
loop { loop {
if !lengths_parsed { if !lengths_parsed {
if let Ok(value) = input.try(specified::Length::parse) { if let Ok(value) = input.try(|i| specified::Length::parse(context, i)) {
lengths[0] = value; lengths[0] = value;
let mut length_parsed_count = 1; let mut length_parsed_count = 1;
while length_parsed_count < 3 { while length_parsed_count < 3 {
if let Ok(value) = input.try(specified::Length::parse) { if let Ok(value) = input.try(|i| specified::Length::parse(context, i)) {
lengths[length_parsed_count] = value lengths[length_parsed_count] = value
} else { } else {
break break
@ -683,7 +682,7 @@ ${helpers.single_keyword("text-align-last",
} }
} }
if color.is_none() { if color.is_none() {
if let Ok(value) = input.try(specified::CSSColor::parse) { if let Ok(value) = input.try(|i| specified::CSSColor::parse(context, i)) {
color = Some(value); color = Some(value);
continue continue
} }
@ -1024,9 +1023,8 @@ ${helpers.predefined_type(
pub type SpecifiedValue = BorderWidth; pub type SpecifiedValue = BorderWidth;
#[inline] #[inline]
pub fn parse(_context: &ParserContext, input: &mut Parser) pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
-> Result<SpecifiedValue, ()> { BorderWidth::parse(context, input)
BorderWidth::parse(input)
} }
pub mod computed_value { pub mod computed_value {

View file

@ -27,7 +27,6 @@ ${helpers.single_keyword("list-style-type", """
animatable=False)} animatable=False)}
${helpers.predefined_type("list-style-image", "UrlOrNone", "computed_value::T::None", ${helpers.predefined_type("list-style-image", "UrlOrNone", "computed_value::T::None",
needs_context=True,
animatable="False")} animatable="False")}
<%helpers:longhand name="quotes" animatable="False"> <%helpers:longhand name="quotes" animatable="False">

View file

@ -19,7 +19,7 @@ ${helpers.predefined_type("outline-color", "CSSColor", "::cssparser::Color::Curr
pub mod computed_value { pub mod computed_value {
pub use values::specified::BorderStyle as T; pub use values::specified::BorderStyle as T;
} }
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
match SpecifiedValue::parse(input) { match SpecifiedValue::parse(input) {
Ok(SpecifiedValue::hidden) => Err(()), Ok(SpecifiedValue::hidden) => Err(()),
result => result result => result

View file

@ -10,6 +10,7 @@
${helpers.predefined_type("padding-%s" % side[0], "LengthOrPercentage", ${helpers.predefined_type("padding-%s" % side[0], "LengthOrPercentage",
"computed::LengthOrPercentage::Length(Au(0))", "computed::LengthOrPercentage::Length(Au(0))",
"parse_non_negative", "parse_non_negative",
needs_context=False,
animatable=True, animatable=True,
logical = side[1])} logical = side[1])}
% endfor % endfor

View file

@ -96,7 +96,7 @@
} }
impl Parse for computed_value::Keyword { impl Parse for computed_value::Keyword {
fn parse(input: &mut Parser) -> Result<computed_value::Keyword, ()> { fn parse(_context: &ParserContext, input: &mut Parser) -> Result<computed_value::Keyword, ()> {
use std::ascii::AsciiExt; use std::ascii::AsciiExt;
use style_traits::cursor::Cursor; use style_traits::cursor::Cursor;
let ident = try!(input.expect_ident()); let ident = try!(input.expect_ident());
@ -120,8 +120,8 @@
} }
#[cfg(not(feature = "gecko"))] #[cfg(not(feature = "gecko"))]
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
computed_value::Keyword::parse(input) computed_value::Keyword::parse(context, input)
} }
/// cursor: [<url> [<number> <number>]?]# [auto | default | ...] /// cursor: [<url> [<number> <number>]?]# [auto | default | ...]
@ -138,7 +138,7 @@
Ok(computed_value::T { Ok(computed_value::T {
images: images, images: images,
keyword: try!(computed_value::Keyword::parse(input)), keyword: try!(computed_value::Keyword::parse(context, input)),
}) })
} }
</%helpers:longhand> </%helpers:longhand>

View file

@ -95,10 +95,12 @@ ${helpers.single_keyword("align-content", "stretch flex-start flex-end center sp
// Flex item properties // Flex item properties
${helpers.predefined_type("flex-grow", "Number", ${helpers.predefined_type("flex-grow", "Number",
"0.0", "parse_non_negative", "0.0", "parse_non_negative",
needs_context=False,
animatable=True)} animatable=True)}
${helpers.predefined_type("flex-shrink", "Number", ${helpers.predefined_type("flex-shrink", "Number",
"1.0", "parse_non_negative", "1.0", "parse_non_negative",
needs_context=False,
animatable=True)} animatable=True)}
${helpers.single_keyword("align-self", "auto stretch flex-start flex-end center baseline", ${helpers.single_keyword("align-self", "auto stretch flex-start flex-end center baseline",
@ -140,6 +142,7 @@ ${helpers.predefined_type("flex-basis",
"LengthOrPercentageOrAuto", "LengthOrPercentageOrAuto",
"computed::LengthOrPercentageOrAuto::Auto", "computed::LengthOrPercentageOrAuto::Auto",
"parse_non_negative", "parse_non_negative",
needs_context=False,
animatable=True, logical = logical)} animatable=True, logical = logical)}
// min-width, min-height, min-block-size, min-inline-size // min-width, min-height, min-block-size, min-inline-size
@ -147,6 +150,7 @@ ${helpers.predefined_type("flex-basis",
"LengthOrPercentage", "LengthOrPercentage",
"computed::LengthOrPercentage::Length(Au(0))", "computed::LengthOrPercentage::Length(Au(0))",
"parse_non_negative", "parse_non_negative",
needs_context=False,
animatable=True, logical = logical)} animatable=True, logical = logical)}
// max-width, max-height, max-block-size, max-inline-size // max-width, max-height, max-block-size, max-inline-size
@ -154,6 +158,7 @@ ${helpers.predefined_type("flex-basis",
"LengthOrPercentageOrNone", "LengthOrPercentageOrNone",
"computed::LengthOrPercentageOrNone::None", "computed::LengthOrPercentageOrNone::None",
"parse_non_negative", "parse_non_negative",
needs_context=False,
animatable=True, logical = logical)} animatable=True, logical = logical)}
% endfor % endfor

View file

@ -47,16 +47,16 @@
second: None second: None
} }
} }
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
let first = try!(Side::parse(input)); let first = try!(Side::parse(context, input));
let second = Side::parse(input).ok(); let second = Side::parse(context, input).ok();
Ok(SpecifiedValue { Ok(SpecifiedValue {
first: first, first: first,
second: second, second: second,
}) })
} }
impl Parse for Side { impl Parse for Side {
fn parse(input: &mut Parser) -> Result<Side, ()> { fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Side, ()> {
if let Ok(ident) = input.try(|input| input.expect_ident()) { if let Ok(ident) = input.try(|input| input.expect_ident()) {
match_ignore_ascii_case! { ident, match_ignore_ascii_case! { ident,
"clip" => Ok(Side::Clip), "clip" => Ok(Side::Clip),

View file

@ -15,4 +15,5 @@ ${helpers.single_keyword("-moz-box-align", "stretch start center baseline end",
${helpers.predefined_type("-moz-box-flex", "Number", "0.0", "parse_non_negative", ${helpers.predefined_type("-moz-box-flex", "Number", "0.0", "parse_non_negative",
products="gecko", gecko_ffi_name="mBoxFlex", products="gecko", gecko_ffi_name="mBoxFlex",
needs_context=False,
animatable=False)} animatable=False)}

View file

@ -84,7 +84,8 @@ pub mod shorthands {
use values::specified; use values::specified;
pub fn parse_four_sides<F, T>(input: &mut Parser, parse_one: F) -> Result<(T, T, T, T), ()> pub fn parse_four_sides<F, T>(input: &mut Parser, parse_one: F) -> Result<(T, T, T, T), ()>
where F: Fn(&mut Parser) -> Result<T, ()>, F: Copy, T: Clone { where F: Fn(&mut Parser) -> Result<T, ()>, T: Clone
{
// zero or more than four values is invalid. // zero or more than four values is invalid.
// one value sets them all // one value sets them all
// two values set (top, bottom) and (left, right) // two values set (top, bottom) and (left, right)
@ -94,7 +95,7 @@ pub mod shorthands {
let right; let right;
let bottom; let bottom;
let left; let left;
match input.try(parse_one) { match input.try(|i| parse_one(i)) {
Err(()) => { Err(()) => {
right = top.clone(); right = top.clone();
bottom = top.clone(); bottom = top.clone();
@ -102,14 +103,14 @@ pub mod shorthands {
} }
Ok(value) => { Ok(value) => {
right = value; right = value;
match input.try(parse_one) { match input.try(|i| parse_one(i)) {
Err(()) => { Err(()) => {
bottom = top.clone(); bottom = top.clone();
left = right.clone(); left = right.clone();
} }
Ok(value) => { Ok(value) => {
bottom = value; bottom = value;
match input.try(parse_one) { match input.try(|i| parse_one(i)) {
Err(()) => { Err(()) => {
left = right.clone(); left = right.clone();
} }
@ -365,7 +366,7 @@ pub enum CSSWideKeyword {
} }
impl Parse for CSSWideKeyword { impl Parse for CSSWideKeyword {
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
match_ignore_ascii_case! { try!(input.expect_ident()), match_ignore_ascii_case! { try!(input.expect_ident()),
"initial" => Ok(CSSWideKeyword::InitialKeyword), "initial" => Ok(CSSWideKeyword::InitialKeyword),
"inherit" => Ok(CSSWideKeyword::InheritKeyword), "inherit" => Ok(CSSWideKeyword::InheritKeyword),
@ -753,11 +754,11 @@ impl PropertyDeclaration {
in_keyframe_block: bool) in_keyframe_block: bool)
-> PropertyDeclarationParseResult { -> PropertyDeclarationParseResult {
if let Ok(name) = ::custom_properties::parse_name(name) { if let Ok(name) = ::custom_properties::parse_name(name) {
let value = match input.try(CSSWideKeyword::parse) { let value = match input.try(|i| CSSWideKeyword::parse(context, i)) {
Ok(CSSWideKeyword::UnsetKeyword) | // Custom properties are alawys inherited Ok(CSSWideKeyword::UnsetKeyword) | // Custom properties are alawys inherited
Ok(CSSWideKeyword::InheritKeyword) => DeclaredValue::Inherit, Ok(CSSWideKeyword::InheritKeyword) => DeclaredValue::Inherit,
Ok(CSSWideKeyword::InitialKeyword) => DeclaredValue::Initial, Ok(CSSWideKeyword::InitialKeyword) => DeclaredValue::Initial,
Err(()) => match ::custom_properties::SpecifiedValue::parse(input) { Err(()) => match ::custom_properties::SpecifiedValue::parse(context, input) {
Ok(value) => DeclaredValue::Value(value), Ok(value) => DeclaredValue::Value(value),
Err(()) => return PropertyDeclarationParseResult::InvalidValue, Err(()) => return PropertyDeclarationParseResult::InvalidValue,
} }
@ -815,7 +816,7 @@ impl PropertyDeclaration {
return PropertyDeclarationParseResult::ExperimentalProperty return PropertyDeclarationParseResult::ExperimentalProperty
} }
% endif % endif
match input.try(CSSWideKeyword::parse) { match input.try(|i| CSSWideKeyword::parse(context, i)) {
Ok(CSSWideKeyword::InheritKeyword) => { Ok(CSSWideKeyword::InheritKeyword) => {
% for sub_property in shorthand.sub_properties: % for sub_property in shorthand.sub_properties:
result_list.push( result_list.push(

View file

@ -6,17 +6,20 @@
<% from data import to_rust_ident, ALL_SIDES %> <% from data import to_rust_ident, ALL_SIDES %>
${helpers.four_sides_shorthand("border-color", "border-%s-color", "specified::CSSColor::parse")} ${helpers.four_sides_shorthand("border-color", "border-%s-color", "specified::CSSColor::parse")}
${helpers.four_sides_shorthand("border-style", "border-%s-style", ${helpers.four_sides_shorthand("border-style", "border-%s-style",
"specified::BorderStyle::parse")} "specified::BorderStyle::parse",
needs_context=False)}
<%helpers:shorthand name="border-width" sub_properties="${ <%helpers:shorthand name="border-width" sub_properties="${
' '.join('border-%s-width' % side ' '.join('border-%s-width' % side
for side in ['top', 'right', 'bottom', 'left'])}"> for side in ['top', 'right', 'bottom', 'left'])}">
use super::parse_four_sides; use super::parse_four_sides;
use parser::Parse;
use values::specified; use values::specified;
pub fn parse_value(context: &ParserContext, input: &mut Parser) -> Result<Longhands, ()> { pub fn parse_value(context: &ParserContext, input: &mut Parser) -> Result<Longhands, ()> {
let _unused = context; let (top, right, bottom, left) = try!(parse_four_sides(input, |i| specified::BorderWidth::parse(context, i)));
let (top, right, bottom, left) = try!(parse_four_sides(input, specified::BorderWidth::parse));
Ok(Longhands { Ok(Longhands {
% for side in ["top", "right", "bottom", "left"]: % for side in ["top", "right", "bottom", "left"]:
${to_rust_ident('border-%s-width' % side)}: Some(${side}), ${to_rust_ident('border-%s-width' % side)}: Some(${side}),
@ -58,7 +61,7 @@ pub fn parse_border(context: &ParserContext, input: &mut Parser)
let mut any = false; let mut any = false;
loop { loop {
if color.is_none() { if color.is_none() {
if let Ok(value) = input.try(specified::CSSColor::parse) { if let Ok(value) = input.try(|i| specified::CSSColor::parse(context, i)) {
color = Some(value); color = Some(value);
any = true; any = true;
continue continue
@ -72,7 +75,7 @@ pub fn parse_border(context: &ParserContext, input: &mut Parser)
} }
} }
if width.is_none() { if width.is_none() {
if let Ok(value) = input.try(specified::BorderWidth::parse) { if let Ok(value) = input.try(|i| specified::BorderWidth::parse(context, i)) {
width = Some(value); width = Some(value);
any = true; any = true;
continue continue
@ -152,9 +155,7 @@ pub fn parse_border(context: &ParserContext, input: &mut Parser)
use parser::Parse; use parser::Parse;
pub fn parse_value(context: &ParserContext, input: &mut Parser) -> Result<Longhands, ()> { pub fn parse_value(context: &ParserContext, input: &mut Parser) -> Result<Longhands, ()> {
let _ignored = context; let radii = try!(BorderRadius::parse(context, input));
let radii = try!(BorderRadius::parse(input));
Ok(Longhands { Ok(Longhands {
border_top_left_radius: Some(radii.top_left), border_top_left_radius: Some(radii.top_left),
border_top_right_radius: Some(radii.top_right), border_top_right_radius: Some(radii.top_right),

View file

@ -58,7 +58,17 @@ macro_rules! try_parse_one {
continue; continue;
} }
} }
} };
($context: expr, $input: expr, $var: ident, $prop_module: ident) => {
if $var.is_none() {
if let Ok(value) = $input.try(|i| {
$prop_module::computed_value::SingleComputedValue::parse($context, i)
}) {
$var = Some(value);
continue;
}
}
};
} }
<%helpers:shorthand name="transition" <%helpers:shorthand name="transition"
@ -69,7 +79,7 @@ macro_rules! try_parse_one {
use properties::longhands::{transition_delay, transition_duration, transition_property}; use properties::longhands::{transition_delay, transition_duration, transition_property};
use properties::longhands::{transition_timing_function}; use properties::longhands::{transition_timing_function};
pub fn parse_value(_: &ParserContext, input: &mut Parser) -> Result<Longhands, ()> { pub fn parse_value(context: &ParserContext, input: &mut Parser) -> Result<Longhands, ()> {
struct SingleTransition { struct SingleTransition {
transition_property: transition_property::SingleSpecifiedValue, transition_property: transition_property::SingleSpecifiedValue,
transition_duration: transition_duration::SingleSpecifiedValue, transition_duration: transition_duration::SingleSpecifiedValue,
@ -77,14 +87,14 @@ macro_rules! try_parse_one {
transition_delay: transition_delay::SingleSpecifiedValue, transition_delay: transition_delay::SingleSpecifiedValue,
} }
fn parse_one_transition(input: &mut Parser) -> Result<SingleTransition,()> { fn parse_one_transition(context: &ParserContext, input: &mut Parser) -> Result<SingleTransition,()> {
let (mut property, mut duration) = (None, None); let (mut property, mut duration) = (None, None);
let (mut timing_function, mut delay) = (None, None); let (mut timing_function, mut delay) = (None, None);
loop { loop {
try_parse_one!(input, property, transition_property); try_parse_one!(input, property, transition_property);
try_parse_one!(input, duration, transition_duration); try_parse_one!(context, input, duration, transition_duration);
try_parse_one!(input, timing_function, transition_timing_function); try_parse_one!(context, input, timing_function, transition_timing_function);
try_parse_one!(input, delay, transition_delay); try_parse_one!(context, input, delay, transition_delay);
break break
} }
@ -113,7 +123,7 @@ macro_rules! try_parse_one {
}) })
} }
let results = try!(input.parse_comma_separated(parse_one_transition)); let results = try!(input.parse_comma_separated(|i| parse_one_transition(context, i)));
let (mut properties, mut durations) = (Vec::new(), Vec::new()); let (mut properties, mut durations) = (Vec::new(), Vec::new());
let (mut timing_functions, mut delays) = (Vec::new(), Vec::new()); let (mut timing_functions, mut delays) = (Vec::new(), Vec::new());
for result in results { for result in results {
@ -159,7 +169,7 @@ macro_rules! try_parse_one {
use properties::longhands::{animation_delay, animation_iteration_count, animation_direction}; use properties::longhands::{animation_delay, animation_iteration_count, animation_direction};
use properties::longhands::{animation_fill_mode, animation_play_state}; use properties::longhands::{animation_fill_mode, animation_play_state};
pub fn parse_value(_: &ParserContext, input: &mut Parser) -> Result<Longhands, ()> { pub fn parse_value(context: &ParserContext, input: &mut Parser) -> Result<Longhands, ()> {
struct SingleAnimation { struct SingleAnimation {
animation_name: animation_name::SingleSpecifiedValue, animation_name: animation_name::SingleSpecifiedValue,
animation_duration: animation_duration::SingleSpecifiedValue, animation_duration: animation_duration::SingleSpecifiedValue,
@ -171,7 +181,7 @@ macro_rules! try_parse_one {
animation_play_state: animation_play_state::SingleSpecifiedValue, animation_play_state: animation_play_state::SingleSpecifiedValue,
} }
fn parse_one_animation(input: &mut Parser) -> Result<SingleAnimation,()> { fn parse_one_animation(context: &ParserContext, input: &mut Parser) -> Result<SingleAnimation,()> {
let mut duration = None; let mut duration = None;
let mut timing_function = None; let mut timing_function = None;
let mut delay = None; let mut delay = None;
@ -187,14 +197,14 @@ macro_rules! try_parse_one {
// Also, duration must be before delay, see // Also, duration must be before delay, see
// https://drafts.csswg.org/css-animations/#typedef-single-animation // https://drafts.csswg.org/css-animations/#typedef-single-animation
loop { loop {
try_parse_one!(input, duration, animation_duration); try_parse_one!(context, input, duration, animation_duration);
try_parse_one!(input, timing_function, animation_timing_function); try_parse_one!(context, input, timing_function, animation_timing_function);
try_parse_one!(input, delay, animation_delay); try_parse_one!(context, input, delay, animation_delay);
try_parse_one!(input, iteration_count, animation_iteration_count); try_parse_one!(context, input, iteration_count, animation_iteration_count);
try_parse_one!(input, direction, animation_direction); try_parse_one!(input, direction, animation_direction);
try_parse_one!(input, fill_mode, animation_fill_mode); try_parse_one!(input, fill_mode, animation_fill_mode);
try_parse_one!(input, play_state, animation_play_state); try_parse_one!(input, play_state, animation_play_state);
try_parse_one!(input, name, animation_name); try_parse_one!(context, input, name, animation_name);
break break
} }
@ -235,7 +245,7 @@ macro_rules! try_parse_one {
}) })
} }
let results = try!(input.parse_comma_separated(parse_one_animation)); let results = try!(input.parse_comma_separated(|i| parse_one_animation(context, i)));
let mut names = vec![]; let mut names = vec![];
let mut durations = vec![]; let mut durations = vec![];

View file

@ -17,7 +17,7 @@
let mut any = false; let mut any = false;
loop { loop {
if color.is_none() { if color.is_none() {
if let Ok(value) = input.try(specified::CSSColor::parse) { if let Ok(value) = input.try(|i| specified::CSSColor::parse(context, i)) {
color = Some(value); color = Some(value);
any = true; any = true;
continue continue

View file

@ -67,7 +67,7 @@
Ok((grow, shrink)) Ok((grow, shrink))
} }
pub fn parse_value(_: &ParserContext, input: &mut Parser) -> Result<Longhands, ()> { pub fn parse_value(context: &ParserContext, input: &mut Parser) -> Result<Longhands, ()> {
let mut grow = None; let mut grow = None;
let mut shrink = None; let mut shrink = None;
let mut basis = None; let mut basis = None;
@ -88,7 +88,7 @@
} }
} }
if basis.is_none() { if basis.is_none() {
if let Ok(value) = input.try(LengthOrPercentageOrAutoOrContent::parse) { if let Ok(value) = input.try(|i| LengthOrPercentageOrAutoOrContent::parse(context, i)) {
basis = Some(value); basis = Some(value);
continue continue
} }

View file

@ -7,7 +7,7 @@
//! [values]: https://drafts.csswg.org/css-values/ //! [values]: https://drafts.csswg.org/css-values/
pub use cssparser::{RGBA, Parser}; pub use cssparser::{RGBA, Parser};
use parser::Parse; use parser::{Parse, ParserContext};
use std::fmt::{self, Debug}; use std::fmt::{self, Debug};
use style_traits::ToCss; use style_traits::ToCss;
@ -83,7 +83,7 @@ macro_rules! define_keyword_type {
} }
impl Parse for $name { impl Parse for $name {
fn parse(input: &mut ::cssparser::Parser) -> Result<$name, ()> { fn parse(_context: &ParserContext, input: &mut ::cssparser::Parser) -> Result<$name, ()> {
input.expect_ident_matching($css).map(|_| $name) input.expect_ident_matching($css).map(|_| $name)
} }
} }
@ -132,11 +132,11 @@ impl<A: HasViewportPercentage, B: HasViewportPercentage> HasViewportPercentage f
} }
impl<A: Parse, B: Parse> Parse for Either<A, B> { impl<A: Parse, B: Parse> Parse for Either<A, B> {
fn parse(input: &mut Parser) -> Result<Either<A, B>, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Either<A, B>, ()> {
if let Ok(v) = input.try(|i| A::parse(i)) { if let Ok(v) = input.try(|i| A::parse(context, i)) {
Ok(Either::First(v)) Ok(Either::First(v))
} else { } else {
B::parse(input).map(Either::Second) B::parse(context, input).map(Either::Second)
} }
} }
} }

View file

@ -61,19 +61,20 @@ impl<T: Parse + PartialEq + Copy> ShapeSource<T> {
} else if let Ok(url) = input.try(|input| SpecifiedUrl::parse(context, input)) { } else if let Ok(url) = input.try(|input| SpecifiedUrl::parse(context, input)) {
Ok(ShapeSource::Url(url)) Ok(ShapeSource::Url(url))
} else { } else {
fn parse_component<U: Parse>(input: &mut Parser, component: &mut Option<U>) -> bool { fn parse_component<U: Parse>(context: &ParserContext, input: &mut Parser,
component: &mut Option<U>) -> bool {
if component.is_some() { if component.is_some() {
return false; // already parsed this component return false; // already parsed this component
} }
*component = input.try(U::parse).ok(); *component = input.try(|i| U::parse(context, i)).ok();
component.is_some() component.is_some()
} }
let mut shape = None; let mut shape = None;
let mut reference = None; let mut reference = None;
loop { loop {
if !parse_component(input, &mut shape) && if !parse_component(context, input, &mut shape) &&
!parse_component(input, &mut reference) { !parse_component(context, input, &mut reference) {
break; break;
} }
} }
@ -136,23 +137,23 @@ pub enum BasicShape {
} }
impl Parse for BasicShape { impl Parse for BasicShape {
fn parse(input: &mut Parser) -> Result<BasicShape, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<BasicShape, ()> {
match_ignore_ascii_case! { try!(input.expect_function()), match_ignore_ascii_case! { try!(input.expect_function()),
"inset" => { "inset" => {
Ok(BasicShape::Inset( Ok(BasicShape::Inset(
try!(input.parse_nested_block(InsetRect::parse_function_arguments)))) try!(input.parse_nested_block(|i| InsetRect::parse_function_arguments(context, i)))))
}, },
"circle" => { "circle" => {
Ok(BasicShape::Circle( Ok(BasicShape::Circle(
try!(input.parse_nested_block(Circle::parse_function_arguments)))) try!(input.parse_nested_block(|i| Circle::parse_function_arguments(context, i)))))
}, },
"ellipse" => { "ellipse" => {
Ok(BasicShape::Ellipse( Ok(BasicShape::Ellipse(
try!(input.parse_nested_block(Ellipse::parse_function_arguments)))) try!(input.parse_nested_block(|i| Ellipse::parse_function_arguments(context, i)))))
}, },
"polygon" => { "polygon" => {
Ok(BasicShape::Polygon( Ok(BasicShape::Polygon(
try!(input.parse_nested_block(Polygon::parse_function_arguments)))) try!(input.parse_nested_block(|i| Polygon::parse_function_arguments(context, i)))))
}, },
_ => Err(()) _ => Err(())
} }
@ -213,8 +214,8 @@ pub struct InsetRect {
} }
impl InsetRect { impl InsetRect {
pub fn parse_function_arguments(input: &mut Parser) -> Result<InsetRect, ()> { pub fn parse_function_arguments(context: &ParserContext, input: &mut Parser) -> Result<InsetRect, ()> {
let (t, r, b, l) = try!(parse_four_sides(input, LengthOrPercentage::parse)); let (t, r, b, l) = try!(parse_four_sides(input, |i| LengthOrPercentage::parse(context, i)));
let mut rect = InsetRect { let mut rect = InsetRect {
top: t, top: t,
right: r, right: r,
@ -223,19 +224,19 @@ impl InsetRect {
round: None, round: None,
}; };
if let Ok(_) = input.try(|input| input.expect_ident_matching("round")) { if let Ok(_) = input.try(|input| input.expect_ident_matching("round")) {
rect.round = Some(try!(BorderRadius::parse(input))); rect.round = Some(try!(BorderRadius::parse(context, input)));
} }
Ok(rect) Ok(rect)
} }
} }
impl Parse for InsetRect { impl Parse for InsetRect {
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
match_ignore_ascii_case! { try!(input.expect_function()), match_ignore_ascii_case! { try!(input.expect_function()),
"inset" => { "inset" => {
Ok(try!(input.parse_nested_block(InsetRect::parse_function_arguments))) Ok(try!(input.parse_nested_block(|i| InsetRect::parse_function_arguments(context, i))))
}, },
_ => Err(()) _ => Err(())
} }
} }
} }
@ -377,10 +378,10 @@ pub struct Circle {
} }
impl Circle { impl Circle {
pub fn parse_function_arguments(input: &mut Parser) -> Result<Circle, ()> { pub fn parse_function_arguments(context: &ParserContext, input: &mut Parser) -> Result<Circle, ()> {
let radius = input.try(ShapeRadius::parse).ok().unwrap_or_else(Default::default); let radius = input.try(|i| ShapeRadius::parse(context, i)).ok().unwrap_or_else(Default::default);
let position = if let Ok(_) = input.try(|input| input.expect_ident_matching("at")) { let position = if let Ok(_) = input.try(|input| input.expect_ident_matching("at")) {
try!(Position::parse(input)) try!(Position::parse(context, input))
} else { } else {
// Defaults to origin // Defaults to origin
Position { Position {
@ -398,12 +399,12 @@ impl Circle {
} }
impl Parse for Circle { impl Parse for Circle {
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
match_ignore_ascii_case! { try!(input.expect_function()), match_ignore_ascii_case! { try!(input.expect_function()),
"circle" => { "circle" => {
Ok(try!(input.parse_nested_block(Circle::parse_function_arguments))) Ok(try!(input.parse_nested_block(|i| Circle::parse_function_arguments(context, i))))
}, },
_ => Err(()) _ => Err(())
} }
} }
} }
@ -452,12 +453,12 @@ pub struct Ellipse {
impl Ellipse { impl Ellipse {
pub fn parse_function_arguments(input: &mut Parser) -> Result<Ellipse, ()> { pub fn parse_function_arguments(context: &ParserContext, input: &mut Parser) -> Result<Ellipse, ()> {
let (a, b) = input.try(|input| -> Result<_, ()> { let (a, b) = input.try(|input| -> Result<_, ()> {
Ok((try!(ShapeRadius::parse(input)), try!(ShapeRadius::parse(input)))) Ok((try!(ShapeRadius::parse(context, input)), try!(ShapeRadius::parse(context, input))))
}).ok().unwrap_or_default(); }).ok().unwrap_or_default();
let position = if let Ok(_) = input.try(|input| input.expect_ident_matching("at")) { let position = if let Ok(_) = input.try(|input| input.expect_ident_matching("at")) {
try!(Position::parse(input)) try!(Position::parse(context, input))
} else { } else {
// Defaults to origin // Defaults to origin
Position { Position {
@ -476,12 +477,12 @@ impl Ellipse {
} }
impl Parse for Ellipse { impl Parse for Ellipse {
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
match_ignore_ascii_case! { try!(input.expect_function()), match_ignore_ascii_case! { try!(input.expect_function()),
"ellipse" => { "ellipse" => {
Ok(try!(input.parse_nested_block(Ellipse::parse_function_arguments))) Ok(try!(input.parse_nested_block(|i| Ellipse::parse_function_arguments(context, i))))
}, },
_ => Err(()) _ => Err(())
} }
} }
} }
@ -533,16 +534,16 @@ pub struct Polygon {
} }
impl Polygon { impl Polygon {
pub fn parse_function_arguments(input: &mut Parser) -> Result<Polygon, ()> { pub fn parse_function_arguments(context: &ParserContext, input: &mut Parser) -> Result<Polygon, ()> {
let fill = input.try(|input| { let fill = input.try(|input| {
let fill = FillRule::parse(input); let fill = FillRule::parse(context, input);
// only eat the comma if there is something before it // only eat the comma if there is something before it
try!(input.expect_comma()); try!(input.expect_comma());
fill fill
}).ok().unwrap_or_else(Default::default); }).ok().unwrap_or_else(Default::default);
let buf = try!(input.parse_comma_separated(|input| { let buf = try!(input.parse_comma_separated(|input| {
Ok((try!(LengthOrPercentage::parse(input)), Ok((try!(LengthOrPercentage::parse(context, input)),
try!(LengthOrPercentage::parse(input)))) try!(LengthOrPercentage::parse(context, input))))
})); }));
Ok(Polygon { Ok(Polygon {
fill: fill, fill: fill,
@ -552,12 +553,12 @@ impl Polygon {
} }
impl Parse for Polygon { impl Parse for Polygon {
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
match_ignore_ascii_case! { try!(input.expect_function()), match_ignore_ascii_case! { try!(input.expect_function()),
"polygon" => { "polygon" => {
Ok(try!(input.parse_nested_block(Polygon::parse_function_arguments))) Ok(try!(input.parse_nested_block(|i| Polygon::parse_function_arguments(context, i))))
}, },
_ => Err(()) _ => Err(())
} }
} }
} }
@ -629,9 +630,8 @@ impl Default for ShapeRadius {
} }
impl Parse for ShapeRadius { impl Parse for ShapeRadius {
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
input.try(LengthOrPercentage::parse).map(ShapeRadius::Length) input.try(|i| LengthOrPercentage::parse(context, i)).map(ShapeRadius::Length).or_else(|_| {
.or_else(|_| {
match_ignore_ascii_case! { try!(input.expect_ident()), match_ignore_ascii_case! { try!(input.expect_ident()),
"closest-side" => Ok(ShapeRadius::ClosestSide), "closest-side" => Ok(ShapeRadius::ClosestSide),
"farthest-side" => Ok(ShapeRadius::FarthestSide), "farthest-side" => Ok(ShapeRadius::FarthestSide),
@ -716,10 +716,10 @@ impl ToCss for BorderRadius {
} }
impl Parse for BorderRadius { impl Parse for BorderRadius {
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
let widths = try!(parse_one_set_of_border_values(input)); let widths = try!(parse_one_set_of_border_values(context, input));
let heights = if input.try(|input| input.expect_delim('/')).is_ok() { let heights = if input.try(|input| input.expect_delim('/')).is_ok() {
try!(parse_one_set_of_border_values(input)) try!(parse_one_set_of_border_values(context, input))
} else { } else {
widths.clone() widths.clone()
}; };
@ -732,23 +732,23 @@ impl Parse for BorderRadius {
} }
} }
fn parse_one_set_of_border_values(mut input: &mut Parser) fn parse_one_set_of_border_values(context: &ParserContext, mut input: &mut Parser)
-> Result<[LengthOrPercentage; 4], ()> { -> Result<[LengthOrPercentage; 4], ()> {
let a = try!(LengthOrPercentage::parse(input)); let a = try!(LengthOrPercentage::parse(context, input));
let b = if let Ok(b) = input.try(LengthOrPercentage::parse) { let b = if let Ok(b) = input.try(|i| LengthOrPercentage::parse(context, i)) {
b b
} else { } else {
return Ok([a, a, a, a]) return Ok([a, a, a, a])
}; };
let c = if let Ok(c) = input.try(LengthOrPercentage::parse) { let c = if let Ok(c) = input.try(|i| LengthOrPercentage::parse(context, i)) {
c c
} else { } else {
return Ok([a, b, a, b]) return Ok([a, b, a, b])
}; };
if let Ok(d) = input.try(LengthOrPercentage::parse) { if let Ok(d) = input.try(|i| LengthOrPercentage::parse(context, i)) {
Ok([a, b, c, d]) Ok([a, b, c, d])
} else { } else {
Ok([a, b, c, b]) Ok([a, b, c, b])
@ -794,7 +794,7 @@ pub enum FillRule {
impl ComputedValueAsSpecified for FillRule {} impl ComputedValueAsSpecified for FillRule {}
impl Parse for FillRule { impl Parse for FillRule {
fn parse(input: &mut Parser) -> Result<FillRule, ()> { fn parse(_context: &ParserContext, input: &mut Parser) -> Result<FillRule, ()> {
match_ignore_ascii_case! { try!(input.expect_ident()), match_ignore_ascii_case! { try!(input.expect_ident()),
"nonzero" => Ok(FillRule::NonZero), "nonzero" => Ok(FillRule::NonZero),
"evenodd" => Ok(FillRule::EvenOdd), "evenodd" => Ok(FillRule::EvenOdd),
@ -829,8 +829,8 @@ pub enum GeometryBox {
} }
impl Parse for GeometryBox { impl Parse for GeometryBox {
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
if let Ok(shape_box) = input.try(ShapeBox::parse) { if let Ok(shape_box) = input.try(|i| ShapeBox::parse(context, i)) {
Ok(GeometryBox::ShapeBox(shape_box)) Ok(GeometryBox::ShapeBox(shape_box))
} else { } else {
match_ignore_ascii_case! { try!(input.expect_ident()), match_ignore_ascii_case! { try!(input.expect_ident()),
@ -868,7 +868,7 @@ pub enum ShapeBox {
} }
impl Parse for ShapeBox { impl Parse for ShapeBox {
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
match_ignore_ascii_case! { try!(input.expect_ident()), match_ignore_ascii_case! { try!(input.expect_ident()),
"margin-box" => Ok(ShapeBox::Margin), "margin-box" => Ok(ShapeBox::Margin),
"border-box" => Ok(ShapeBox::Border), "border-box" => Ok(ShapeBox::Border),

View file

@ -42,7 +42,7 @@ impl Image {
return Ok(Image::Url(url)); return Ok(Image::Url(url));
} }
Ok(Image::Gradient(try!(Gradient::parse_function(input)))) Ok(Image::Gradient(try!(Gradient::parse_function(context, input))))
} }
/// Creates an already specified image value from an already resolved URL /// Creates an already specified image value from an already resolved URL
@ -92,13 +92,13 @@ impl ToCss for Gradient {
impl Gradient { impl Gradient {
/// Parses a gradient from the given arguments. /// Parses a gradient from the given arguments.
pub fn parse_function(input: &mut Parser) -> Result<Gradient, ()> { pub fn parse_function(context: &ParserContext, input: &mut Parser) -> Result<Gradient, ()> {
let mut repeating = false; let mut repeating = false;
let (gradient_kind, stops) = match_ignore_ascii_case! { try!(input.expect_function()), let (gradient_kind, stops) = match_ignore_ascii_case! { try!(input.expect_function()),
"linear-gradient" => { "linear-gradient" => {
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
let kind = try!(GradientKind::parse_linear(input)); let kind = try!(GradientKind::parse_linear(context, input));
let stops = try!(input.parse_comma_separated(ColorStop::parse)); let stops = try!(input.parse_comma_separated(|i| ColorStop::parse(context, i)));
Ok((kind, stops)) Ok((kind, stops))
}) })
) )
@ -106,16 +106,16 @@ impl Gradient {
"repeating-linear-gradient" => { "repeating-linear-gradient" => {
repeating = true; repeating = true;
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
let kind = try!(GradientKind::parse_linear(input)); let kind = try!(GradientKind::parse_linear(context, input));
let stops = try!(input.parse_comma_separated(ColorStop::parse)); let stops = try!(input.parse_comma_separated(|i| ColorStop::parse(context, i)));
Ok((kind, stops)) Ok((kind, stops))
}) })
) )
}, },
"radial-gradient" => { "radial-gradient" => {
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
let kind = try!(GradientKind::parse_radial(input)); let kind = try!(GradientKind::parse_radial(context, input));
let stops = try!(input.parse_comma_separated(ColorStop::parse)); let stops = try!(input.parse_comma_separated(|i| ColorStop::parse(context, i)));
Ok((kind, stops)) Ok((kind, stops))
}) })
) )
@ -123,8 +123,8 @@ impl Gradient {
"repeating-radial-gradient" => { "repeating-radial-gradient" => {
repeating = true; repeating = true;
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
let kind = try!(GradientKind::parse_radial(input)); let kind = try!(GradientKind::parse_radial(context, input));
let stops = try!(input.parse_comma_separated(ColorStop::parse)); let stops = try!(input.parse_comma_separated(|i| ColorStop::parse(context, i)));
Ok((kind, stops)) Ok((kind, stops))
}) })
) )
@ -151,29 +151,29 @@ pub enum GradientKind {
impl GradientKind { impl GradientKind {
/// Parses a linear gradient kind from the given arguments. /// Parses a linear gradient kind from the given arguments.
pub fn parse_linear(input: &mut Parser) -> Result<GradientKind, ()> { pub fn parse_linear(context: &ParserContext, input: &mut Parser) -> Result<GradientKind, ()> {
let angle_or_corner = try!(AngleOrCorner::parse(input)); let angle_or_corner = try!(AngleOrCorner::parse(context, input));
Ok(GradientKind::Linear(angle_or_corner)) Ok(GradientKind::Linear(angle_or_corner))
} }
/// Parses a radial gradient from the given arguments. /// Parses a radial gradient from the given arguments.
pub fn parse_radial(input: &mut Parser) -> Result<GradientKind, ()> { pub fn parse_radial(context: &ParserContext, input: &mut Parser) -> Result<GradientKind, ()> {
let mut needs_comma = true; let mut needs_comma = true;
// Ending shape and position can be in various order. Checks all probabilities. // Ending shape and position can be in various order. Checks all probabilities.
let (shape, position) = if let Ok(position) = input.try(parse_position) { let (shape, position) = if let Ok(position) = input.try(|i| parse_position(context, i)) {
// Handle just <position> // Handle just <position>
(EndingShape::Ellipse(LengthOrPercentageOrKeyword::Keyword(SizeKeyword::FarthestCorner)), position) (EndingShape::Ellipse(LengthOrPercentageOrKeyword::Keyword(SizeKeyword::FarthestCorner)), position)
} else if let Ok((first, second)) = input.try(parse_two_length) { } else if let Ok((first, second)) = input.try(|i| parse_two_length(context, i)) {
// Handle <LengthOrPercentage> <LengthOrPercentage> <shape>? <position>? // Handle <LengthOrPercentage> <LengthOrPercentage> <shape>? <position>?
let _ = input.try(|input| input.expect_ident_matching("ellipse")); let _ = input.try(|input| input.expect_ident_matching("ellipse"));
(EndingShape::Ellipse(LengthOrPercentageOrKeyword::LengthOrPercentage(first, second)), (EndingShape::Ellipse(LengthOrPercentageOrKeyword::LengthOrPercentage(first, second)),
input.try(parse_position).unwrap_or(Position::center())) input.try(|i| parse_position(context, i)).unwrap_or(Position::center()))
} else if let Ok(length) = input.try(Length::parse) { } else if let Ok(length) = input.try(|i| Length::parse(context, i)) {
// Handle <Length> <circle>? <position>? // Handle <Length> <circle>? <position>?
let _ = input.try(|input| input.expect_ident_matching("circle")); let _ = input.try(|input| input.expect_ident_matching("circle"));
(EndingShape::Circle(LengthOrKeyword::Length(length)), (EndingShape::Circle(LengthOrKeyword::Length(length)),
input.try(parse_position).unwrap_or(Position::center())) input.try(|i| parse_position(context, i)).unwrap_or(Position::center()))
} else if let Ok(keyword) = input.try(SizeKeyword::parse) { } else if let Ok(keyword) = input.try(SizeKeyword::parse) {
// Handle <keyword> <shape-keyword>? <position>? // Handle <keyword> <shape-keyword>? <position>?
let shape = if input.try(|input| input.expect_ident_matching("circle")).is_ok() { let shape = if input.try(|input| input.expect_ident_matching("circle")).is_ok() {
@ -182,24 +182,26 @@ impl GradientKind {
let _ = input.try(|input| input.expect_ident_matching("ellipse")); let _ = input.try(|input| input.expect_ident_matching("ellipse"));
EndingShape::Ellipse(LengthOrPercentageOrKeyword::Keyword(keyword)) EndingShape::Ellipse(LengthOrPercentageOrKeyword::Keyword(keyword))
}; };
(shape, input.try(parse_position).unwrap_or(Position::center())) (shape, input.try(|i| parse_position(context, i)).unwrap_or(Position::center()))
} else { } else {
// Handle <shape-keyword> <length>? <position>? // Handle <shape-keyword> <length>? <position>?
if input.try(|input| input.expect_ident_matching("ellipse")).is_ok() { if input.try(|input| input.expect_ident_matching("ellipse")).is_ok() {
// Handle <ellipse> <LengthOrPercentageOrKeyword>? <position>? // Handle <ellipse> <LengthOrPercentageOrKeyword>? <position>?
let length = input.try(LengthOrPercentageOrKeyword::parse) let length = input.try(|i| LengthOrPercentageOrKeyword::parse(context, i))
.unwrap_or(LengthOrPercentageOrKeyword::Keyword(SizeKeyword::FarthestCorner)); .unwrap_or(LengthOrPercentageOrKeyword::Keyword(SizeKeyword::FarthestCorner));
(EndingShape::Ellipse(length), input.try(parse_position).unwrap_or(Position::center())) (EndingShape::Ellipse(length),
input.try(|i| parse_position(context, i)).unwrap_or(Position::center()))
} else if input.try(|input| input.expect_ident_matching("circle")).is_ok() { } else if input.try(|input| input.expect_ident_matching("circle")).is_ok() {
// Handle <ellipse> <LengthOrKeyword>? <position>? // Handle <ellipse> <LengthOrKeyword>? <position>?
let length = input.try(LengthOrKeyword::parse) let length = input.try(|i| LengthOrKeyword::parse(context, i))
.unwrap_or(LengthOrKeyword::Keyword(SizeKeyword::FarthestCorner)); .unwrap_or(LengthOrKeyword::Keyword(SizeKeyword::FarthestCorner));
(EndingShape::Circle(length), input.try(parse_position).unwrap_or(Position::center())) (EndingShape::Circle(length), input.try(|i| parse_position(context, i))
.unwrap_or(Position::center()))
} else { } else {
// If there is no shape keyword, it should set to default. // If there is no shape keyword, it should set to default.
needs_comma = false; needs_comma = false;
(EndingShape::Ellipse(LengthOrPercentageOrKeyword::Keyword(SizeKeyword::FarthestCorner)), (EndingShape::Ellipse(LengthOrPercentageOrKeyword::Keyword(SizeKeyword::FarthestCorner)),
input.try(parse_position).unwrap_or(Position::center())) input.try(|i| parse_position(context, i)).unwrap_or(Position::center()))
} }
}; };
@ -211,15 +213,16 @@ impl GradientKind {
} }
} }
fn parse_two_length(input: &mut Parser) -> Result<(LengthOrPercentage, LengthOrPercentage), ()> { fn parse_two_length(context: &ParserContext, input: &mut Parser)
let first = try!(LengthOrPercentage::parse(input)); -> Result<(LengthOrPercentage, LengthOrPercentage), ()> {
let second = try!(LengthOrPercentage::parse(input)); let first = try!(LengthOrPercentage::parse(context, input));
let second = try!(LengthOrPercentage::parse(context, input));
Ok((first, second)) Ok((first, second))
} }
fn parse_position(input: &mut Parser) -> Result<Position, ()> { fn parse_position(context: &ParserContext, input: &mut Parser) -> Result<Position, ()> {
try!(input.expect_ident_matching("at")); try!(input.expect_ident_matching("at"));
input.try(Position::parse) input.try(|i| Position::parse(context, i))
} }
/// Specified values for an angle or a corner in a linear gradient. /// Specified values for an angle or a corner in a linear gradient.
@ -246,7 +249,7 @@ impl ToCss for AngleOrCorner {
} }
impl Parse for AngleOrCorner { impl Parse for AngleOrCorner {
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
if input.try(|input| input.expect_ident_matching("to")).is_ok() { if input.try(|input| input.expect_ident_matching("to")).is_ok() {
let (horizontal, vertical) = let (horizontal, vertical) =
if let Ok(value) = input.try(HorizontalDirection::parse) { if let Ok(value) = input.try(HorizontalDirection::parse) {
@ -274,7 +277,7 @@ impl Parse for AngleOrCorner {
} }
(None, None) => unreachable!(), (None, None) => unreachable!(),
} }
} else if let Ok(angle) = input.try(Angle::parse) { } else if let Ok(angle) = input.try(|i| Angle::parse(context, i)) {
try!(input.expect_comma()); try!(input.expect_comma());
Ok(AngleOrCorner::Angle(angle)) Ok(AngleOrCorner::Angle(angle))
} else { } else {
@ -313,10 +316,10 @@ define_css_keyword_enum!(HorizontalDirection: "left" => Left, "right" => Right);
define_css_keyword_enum!(VerticalDirection: "top" => Top, "bottom" => Bottom); define_css_keyword_enum!(VerticalDirection: "top" => Top, "bottom" => Bottom);
impl Parse for ColorStop { impl Parse for ColorStop {
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
Ok(ColorStop { Ok(ColorStop {
color: try!(CSSColor::parse(input)), color: try!(CSSColor::parse(context, input)),
position: input.try(LengthOrPercentage::parse).ok(), position: input.try(|i| LengthOrPercentage::parse(context, i)).ok(),
}) })
} }
} }
@ -357,11 +360,11 @@ pub enum LengthOrKeyword {
} }
impl Parse for LengthOrKeyword { impl Parse for LengthOrKeyword {
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
if let Ok(keyword) = input.try(SizeKeyword::parse) { if let Ok(keyword) = input.try(SizeKeyword::parse) {
Ok(LengthOrKeyword::Keyword(keyword)) Ok(LengthOrKeyword::Keyword(keyword))
} else { } else {
Ok(LengthOrKeyword::Length(try!(Length::parse(input)))) Ok(LengthOrKeyword::Length(try!(Length::parse(context, input))))
} }
} }
} }
@ -385,12 +388,13 @@ pub enum LengthOrPercentageOrKeyword {
impl Parse for LengthOrPercentageOrKeyword { impl Parse for LengthOrPercentageOrKeyword {
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
if let Ok(keyword) = input.try(SizeKeyword::parse) { if let Ok(keyword) = input.try(SizeKeyword::parse) {
Ok(LengthOrPercentageOrKeyword::Keyword(keyword)) Ok(LengthOrPercentageOrKeyword::Keyword(keyword))
} else { } else {
Ok(LengthOrPercentageOrKeyword::LengthOrPercentage(try!(LengthOrPercentage::parse(input)), Ok(LengthOrPercentageOrKeyword::LengthOrPercentage(
try!(LengthOrPercentage::parse(input)))) try!(LengthOrPercentage::parse(context, input)),
try!(LengthOrPercentage::parse(context, input))))
} }
} }
} }

View file

@ -6,7 +6,7 @@ use app_units::Au;
use cssparser::{Parser, Token}; use cssparser::{Parser, Token};
use euclid::size::Size2D; use euclid::size::Size2D;
use font_metrics::FontMetrics; use font_metrics::FontMetrics;
use parser::Parse; use parser::{Parse, ParserContext};
use std::ascii::AsciiExt; use std::ascii::AsciiExt;
use std::cmp; use std::cmp;
use std::fmt; use std::fmt;
@ -338,7 +338,7 @@ impl Length {
} }
impl Parse for Length { impl Parse for Length {
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
Length::parse_internal(input, AllowedNumericType::All) Length::parse_internal(input, AllowedNumericType::All)
} }
} }
@ -753,7 +753,7 @@ impl ToCss for Percentage {
impl Parse for Percentage { impl Parse for Percentage {
#[inline] #[inline]
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
let context = AllowedNumericType::All; let context = AllowedNumericType::All;
match try!(input.next()) { match try!(input.next()) {
Token::Percentage(ref value) if context.is_ok(value.unit_value) => Token::Percentage(ref value) if context.is_ok(value.unit_value) =>
@ -821,7 +821,7 @@ impl LengthOrPercentage {
impl Parse for LengthOrPercentage { impl Parse for LengthOrPercentage {
#[inline] #[inline]
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
LengthOrPercentage::parse_internal(input, AllowedNumericType::All) LengthOrPercentage::parse_internal(input, AllowedNumericType::All)
} }
} }
@ -884,7 +884,7 @@ impl LengthOrPercentageOrAuto {
impl Parse for LengthOrPercentageOrAuto { impl Parse for LengthOrPercentageOrAuto {
#[inline] #[inline]
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
LengthOrPercentageOrAuto::parse_internal(input, AllowedNumericType::All) LengthOrPercentageOrAuto::parse_internal(input, AllowedNumericType::All)
} }
} }
@ -946,7 +946,7 @@ impl LengthOrPercentageOrNone {
impl Parse for LengthOrPercentageOrNone { impl Parse for LengthOrPercentageOrNone {
#[inline] #[inline]
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
LengthOrPercentageOrNone::parse_internal(input, AllowedNumericType::All) LengthOrPercentageOrNone::parse_internal(input, AllowedNumericType::All)
} }
} }
@ -986,7 +986,7 @@ impl ToCss for LengthOrPercentageOrAutoOrContent {
} }
impl Parse for LengthOrPercentageOrAutoOrContent { impl Parse for LengthOrPercentageOrAutoOrContent {
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
let context = AllowedNumericType::NonNegative; let context = AllowedNumericType::NonNegative;
match try!(input.next()) { match try!(input.next()) {
Token::Dimension(ref value, ref unit) if context.is_ok(value.value) => Token::Dimension(ref value, ref unit) if context.is_ok(value.value) =>
@ -1012,7 +1012,7 @@ pub type LengthOrNumber = Either<Length, Number>;
impl LengthOrNumber { impl LengthOrNumber {
pub fn parse_non_negative(input: &mut Parser) -> Result<Self, ()> { pub fn parse_non_negative(input: &mut Parser) -> Result<Self, ()> {
if let Ok(v) = input.try(|i| Length::parse_non_negative(i)) { if let Ok(v) = input.try(Length::parse_non_negative) {
Ok(Either::First(v)) Ok(Either::First(v))
} else { } else {
Number::parse_non_negative(input).map(Either::Second) Number::parse_non_negative(input).map(Either::Second)

View file

@ -38,7 +38,7 @@ pub struct CSSColor {
} }
impl Parse for CSSColor { impl Parse for CSSColor {
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
let start_position = input.position(); let start_position = input.position();
let authored = match input.next() { let authored = match input.next() {
Ok(Token::Ident(s)) => Some(s.into_owned()), Ok(Token::Ident(s)) => Some(s.into_owned()),
@ -197,7 +197,7 @@ impl BorderRadiusSize {
impl Parse for BorderRadiusSize { impl Parse for BorderRadiusSize {
#[inline] #[inline]
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
let first = try!(LengthOrPercentage::parse_non_negative(input)); let first = try!(LengthOrPercentage::parse_non_negative(input));
let second = input.try(LengthOrPercentage::parse_non_negative).unwrap_or(first); let second = input.try(LengthOrPercentage::parse_non_negative).unwrap_or(first);
Ok(BorderRadiusSize(Size2D::new(first, second))) Ok(BorderRadiusSize(Size2D::new(first, second)))
@ -241,7 +241,7 @@ const RAD_PER_TURN: CSSFloat = PI * 2.0;
impl Parse for Angle { impl Parse for Angle {
/// Parses an angle according to CSS-VALUES § 6.1. /// Parses an angle according to CSS-VALUES § 6.1.
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
match try!(input.next()) { match try!(input.next()) {
Token::Dimension(ref value, ref unit) => Angle::parse_dimension(value.value, unit), Token::Dimension(ref value, ref unit) => Angle::parse_dimension(value.value, unit),
Token::Number(ref value) if value.value == 0. => Ok(Angle(0.)), Token::Number(ref value) if value.value == 0. => Ok(Angle(0.)),
@ -265,8 +265,8 @@ impl Angle {
} }
} }
pub fn parse_border_radius(input: &mut Parser) -> Result<BorderRadiusSize, ()> { pub fn parse_border_radius(context: &ParserContext, input: &mut Parser) -> Result<BorderRadiusSize, ()> {
input.try(BorderRadiusSize::parse).or_else(|()| { input.try(|i| BorderRadiusSize::parse(context, i)).or_else(|()| {
match_ignore_ascii_case! { try!(input.expect_ident()), match_ignore_ascii_case! { try!(input.expect_ident()),
"thin" => Ok(BorderRadiusSize::circle( "thin" => Ok(BorderRadiusSize::circle(
LengthOrPercentage::Length(Length::from_px(1.)))), LengthOrPercentage::Length(Length::from_px(1.)))),
@ -299,12 +299,8 @@ pub enum BorderWidth {
Width(Length), Width(Length),
} }
impl BorderWidth { impl Parse for BorderWidth {
pub fn from_length(length: Length) -> Self { fn parse(_context: &ParserContext, input: &mut Parser) -> Result<BorderWidth, ()> {
BorderWidth::Width(length)
}
pub fn parse(input: &mut Parser) -> Result<BorderWidth, ()> {
match input.try(Length::parse_non_negative) { match input.try(Length::parse_non_negative) {
Ok(length) => Ok(BorderWidth::Width(length)), Ok(length) => Ok(BorderWidth::Width(length)),
Err(_) => match_ignore_ascii_case! { try!(input.expect_ident()), Err(_) => match_ignore_ascii_case! { try!(input.expect_ident()),
@ -317,6 +313,12 @@ impl BorderWidth {
} }
} }
impl BorderWidth {
pub fn from_length(length: Length) -> Self {
BorderWidth::Width(length)
}
}
impl ToCss for BorderWidth { impl ToCss for BorderWidth {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self { match *self {
@ -409,7 +411,7 @@ impl Time {
impl ComputedValueAsSpecified for Time {} impl ComputedValueAsSpecified for Time {}
impl Parse for Time { impl Parse for Time {
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
match input.next() { match input.next() {
Ok(Token::Dimension(ref value, ref unit)) => { Ok(Token::Dimension(ref value, ref unit)) => {
Time::parse_dimension(value.value, &unit) Time::parse_dimension(value.value, &unit)
@ -435,7 +437,7 @@ pub struct Number(pub CSSFloat);
impl NoViewportPercentage for Number {} impl NoViewportPercentage for Number {}
impl Parse for Number { impl Parse for Number {
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
parse_number(input).map(Number) parse_number(input).map(Number)
} }
} }
@ -482,7 +484,7 @@ pub struct Opacity(pub CSSFloat);
impl NoViewportPercentage for Opacity {} impl NoViewportPercentage for Opacity {}
impl Parse for Opacity { impl Parse for Opacity {
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
parse_number(input).map(Opacity) parse_number(input).map(Opacity)
} }
} }

View file

@ -9,7 +9,7 @@
use app_units::Au; use app_units::Au;
use cssparser::{Parser, Token}; use cssparser::{Parser, Token};
use parser::Parse; use parser::{Parse, ParserContext};
use std::fmt; use std::fmt;
use style_traits::ToCss; use style_traits::ToCss;
use values::HasViewportPercentage; use values::HasViewportPercentage;
@ -181,14 +181,14 @@ impl Position {
} }
impl Parse for Position { impl Parse for Position {
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
let first = try!(PositionComponent::parse(input)); let first = try!(PositionComponent::parse(context, input));
let second = input.try(PositionComponent::parse) let second = input.try(|i| PositionComponent::parse(context, i))
.unwrap_or(PositionComponent::Keyword(Keyword::Center)); .unwrap_or(PositionComponent::Keyword(Keyword::Center));
// Try to parse third and fourth values // Try to parse third and fourth values
if let Ok(third) = input.try(PositionComponent::parse) { if let Ok(third) = input.try(|i| PositionComponent::parse(context, i)) {
if let Ok(fourth) = input.try(PositionComponent::parse) { if let Ok(fourth) = input.try(|i| PositionComponent::parse(context, i)) {
// Handle 4 value background position // Handle 4 value background position
Position::new(Some(second), Some(fourth), Some(first), Some(third)) Position::new(Some(second), Some(fourth), Some(first), Some(third))
} else { } else {
@ -375,8 +375,8 @@ impl PositionComponent {
} }
impl Parse for PositionComponent { impl Parse for PositionComponent {
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
input.try(LengthOrPercentage::parse) input.try(|i| LengthOrPercentage::parse(context, i))
.map(PositionComponent::Length) .map(PositionComponent::Length)
.or_else(|()| { .or_else(|()| {
match try!(input.next()) { match try!(input.next()) {